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)

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

查看所有标签

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

Web Security, Privacy and Commerce, 2nd Edition

Web Security, Privacy and Commerce, 2nd Edition

Simson Garfinkel / O'Reilly Media / 2002-01-15 / USD 44.95

Since the first edition of this classic reference was published, World Wide Web use has exploded and e-commerce has become a daily part of business and personal life. As Web use has grown, so have ......一起来看看 《Web Security, Privacy and Commerce, 2nd Edition》 这本书的介绍吧!

CSS 压缩/解压工具
CSS 压缩/解压工具

在线压缩/解压 CSS 代码

JSON 在线解析
JSON 在线解析

在线 JSON 格式化工具

RGB HSV 转换
RGB HSV 转换

RGB HSV 互转工具