#_*_ encoding: utf-8 _*_ @author: ty hery 2019/12/20
from flask import Flask, url_for, current_app, redirect
from werkzeug.routing import BaseConverter
app = Flask(__name__)
@app.route(‘/index‘,methods=[‘GET‘])
@app.route(‘/‘,methods=[‘GET‘])
def index():
url = url_for(‘send_sms‘,mobile= ‘18576483558‘)
# 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
def to_python(self,value):
# value是在路径进行正则表达式匹配的时候提取的参数
print(‘to_python方法被调用了‘,value)
return ‘123‘
# return value
def to_url(self,value):
# 使用url_for的时候被调用了
print(‘to_url方法被调用了‘,value)
# return value
return ‘18576483456‘
# 2, 将自定义的转换器添加到flask的应用中
app.url_map.converters[‘re‘] = RegexConverter
@app.route("/send/<re(r‘1[34578]\d{9}‘):mobile>")
def send_sms(mobile):
return ‘send sms to %s‘ % mobile
@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__‘:
print(‘--哈哈01--‘,app.url_map,‘--哈哈01--‘)
app.run(debug=True)
原文:https://www.cnblogs.com/heris/p/14651043.html