flask视图函数自定义转换器

栏目: Python · 发布时间: 7年前

内容简介:通过自定义转换器来实现对url中的内容进行更精确的识别,操作如下1、以类的方式定义一个转换器2、将自定义的转换器添加到flask应用中,在flask对象中存在一个属性app.url_map,这个属性下converters对象保存着flask对象中的所有转换器,包括默认的int、float、path,要将自定义的类添加到app.url_map.converters字典中,

通过自定义转换器来实现对url中的内容进行更精确的识别,操作如下

1、以类的方式定义一个转换器

2、将自定义的转换器添加到flask应用中,在flask对象中存在一个属性app.url_map,这个属性下converters对象保存着flask对象中的所有转换器,包括默认的int、float、path,要将自定义的类添加到app.url_map.converters字典中,

3、在路由中使自定义转换器

创建converter_daemo.py内容如下

from flask import Flask
from werkzeug.routing import BaseConverter

app = Flask(__name__)


# 实现一个专门用来处理手机号的转换器
class MobileConverter(BaseConverter):
    def __init__(self, url_map):
        # 将参数url_map传给父类,调用父类方法构造对象,
        super(MobileConverter, self).__init__(url_map)
        # 手机号的正则表达式
        self.regex = r'1[34578]\d{9}'


# 将自定义的转换器添加到flask的应用中,并给这个转换器起名为mobile
app.url_map.converters["mobile"] = MobileConverter


# 在路由中使自定义转换器,匹配手机号,需要自定义一个转换器,在使用函数中使用自定义的转换器
@app.route("/send/<mobile:mobile_num>")
def send_sms(mobile_num):
    return "send sms %s" % mobile_num


if __name__ == '__main__':
    app.run(debug=True)

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

HTTP

HTTP

David Gourley、Brian Totty、Marjorie Sayer、Anshu Aggarwal、Sailu Reddy / O'Reilly Media / 2002-10-7 / USD 54.99

Product Description Web technology has become the foundation for all sorts of critical networked applications and far-reaching methods of data exchange, and beneath it all is a fundamental protocol......一起来看看 《HTTP》 这本书的介绍吧!

在线进制转换器
在线进制转换器

各进制数互转换器

MD5 加密
MD5 加密

MD5 加密工具

XML、JSON 在线转换
XML、JSON 在线转换

在线XML、JSON转换工具