flask的转换器

#_*_ encoding: utf-8 _*_   @author: ty  hery   2019/12/20

from  flask import  Flask, url_for, current_app, redirect
from werkzeug.routing import BaseConverter

# 创建flask的应用对象
#__name__表示当前的模块名字
# 模块名,flask以这个模块所在的目录为总目录,默认这个目录中static为静态目录,templates为模板目录
app = Flask(__name__)


# 通过methods限定访问方式
@app.route('/post_only/', methods = ['GET','POST'])  # ',methods = ['get','post']小写大写都行
def post_only():
    return 'post only page'


@app.route('/hi1/') 
@app.route('/hi2/') # 多个路由对应一个函数
def  hi():
    return 'hi page'

@app.route('/index',methods=['GET'])
@app.route('/',methods=['GET'])
def index():
    url = url_for('send_sms',mobile= '18576483558') #  #使用url_for 的函数,通过视图函数的名字找到试图对应的url路径
    # return  'hello flask'
    return  redirect(url)

# @app.route('/goods/<int:goods_id>')
# @app.route('/goods/<float:goods_id>')
@app.route('/goods/<goods_id>') # 不加转换器,默认是str类型普通的字符串规则(除了/的字符串,
# @app.route('/goods/<path:goods_id>') # 不加转换器,默认是str类型普通的字符串规则(除了/的字符串,
def goods_detail(goods_id):
    print(type(goods_id),'第三方',goods_id)
    return  'goods_detail %s' %goods_id

# 1,定义自己的转换器
class RegexConverter(BaseConverter):
    def __init__(self,url_map,regex):
        # 调用父类的初始化方法
        super(RegexConverter, self).__init__(url_map)
        # 将正则表达式的参数保存到对象的属性中,flask会去使用这个属性来进行路由的正则匹配
        self.regex = regex

    # to_python和to_url都是BaseConverter 里面自带的方法
    def to_python(self,value): # to_python是在正则匹配之后返回, value是正则匹配之后接收到的值
        print('to_python 方法被调用')
        # return '123'
        return value

    def  to_url(self,value): # to_url 是在url_for正则匹配之后返回, value是正则匹配之后接收到的值
        print('to_url 方法被调用')
        return '15812345678'

# 1,定义自己的手机号匹配转换器
class MobileConverter(BaseConverter):
    def __init__(self,url_map):
        super(MobileConverter,self).__init__(url_map)
        self.regex = r'1[34578]\d{9}'

# 2, 将自定义的转换器添加到flask的应用中
app.url_map.converters['re'] = RegexConverter
app.url_map.converters['mobile'] = MobileConverter


# @127.0.0.1:5000/send/18612345678
# re(r'1[34578]\d{9}') re携带参数(r'1[34578]\d{9}')去实例化将参数传递给对象的属性中regex,
# flask会去使用这个属性来进行路由的正则表达式     此处的re是万能的转换器
@app.route("/send/<re(r'1[34578]\d{9}'):mobile>")
def send_sms(mobile):  # 访问 http://127.0.0.1:5000/send/18576483558  进过to_python转换之后mobile变为 123
    return 'send sms to %s' % mobile

@app.route("/send_num/<mobile:mobile_num>")
def send_mobile(mobile_num):
    return 'send mobile to %s' % mobile_num

@app.route('/index')
def index():
    url = url_for('send_sms',mobile=18912345678) # url_for的第一个参数是执行的函数,第二个是**kwargs键值对
    # url = url_for('goods_detail',goods_id=18912345678) # url_for的第一个参数是执行的函数,第二个是**kwargs键值对
    # /send/189123456789
    return redirect(url)



@app.route("/huikuan/<int:money>")
def send_money(money):
    print('汇款',money,type(money))
    return 'send sms to %s,typeof %s' %(money,type(money))


@app.route('/post_only',methods=['POST'])
def post_only():
    return 'post only page'


if __name__ == '__main__':
    # 通过url_map可以查看整个flask中的路由信息
    print('查看当前的url_map',app.url_map,'结束')
    app.run(debug=True)
posted @ 2021-04-12 22:56  ty1539  阅读(64)  评论(0编辑  收藏  举报