flask视图函数自定义转换器

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

内容简介:通过自定义转换器来实现对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)

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

查看所有标签

猜你喜欢:

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

Designing Data-Intensive Applications

Designing Data-Intensive Applications

Martin Kleppmann / O'Reilly Media / 2017-4-2 / USD 44.99

Data is at the center of many challenges in system design today. Difficult issues need to be figured out, such as scalability, consistency, reliability, efficiency, and maintainability. In addition, w......一起来看看 《Designing Data-Intensive Applications》 这本书的介绍吧!

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

在线XML、JSON转换工具

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具