【Flask】 python学习第一章 - 3.0 正则转换和错误捕捉
3.1正则转换器定义
Class RegexConverter(BaseConverter):
regex = "[0-9]{6}"
app.url_map.converters["re"] = RegexConverter
@app.route("/user/<re:user_id>")
def index():
return "hello wolrd"
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
from flask import Flask from werkzeug.routing import BaseConverter # 创建自定义转换器 class RegexConverter(BaseConverter): regex = "[0-9]{6}" app = Flask(__name__) # 将自己的转换器加入默认的服务器列表中 app.url_map.converters["re"] = RegexConverter # 规则: /user/6位数字 [0-9]{6} # 自定义转换器 @app.route("/user/<re:user_id>") def index(user_id): return "index + %s" % user_id if __name__ == '__main__': app.run(debug=True)
3.2正则自定义转换器
Class RegexConverter(BaseConverter):
def __init__(self, url_map , *args):
super(RegexConverter, self).__init__(url_map)
self.regex = args[0]
app.url_map.converters["re"] = RegexConverter
@app.route("/user/<re(‘[0-9]{6}’):user_id>")
def index():
return "hello wolrd"
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
from flask import Flask from werkzeug.routing import BaseConverter # 创建自定义转换器 class RegexConverter(BaseConverter): # regex = "[0-9]{6}" def __init__(self, url_map, *args): super(RegexConverter, self).__init__(url_map) self.regex = args[0] app = Flask(__name__) # 将自己的转换器加入默认的服务器列表中 app.url_map.converters["re"] = RegexConverter # 规则: /user/6位数字 [0-9]{6} # 自定义转换器 @app.route("/user/<re('[0-9]{5}'):user_id>") def index(user_id): return "index + %s" % user_id if __name__ == '__main__': app.run(debug=True)
3.3 转换器 to_python to_url
class ListConverter():
regex = "(\\d,)+\\d$"
# 匹配参数后 对参数进行处理 再返回到视图函数上去
def to_python(self, value):
return value.split(",")
# 使用url_for 的时候,对视图函数传的参数进行处理,以匹配路由
# redirect(url_for("demo1",user_id=[1,2,3,4]))
def to_url(self, value):
return ",".join(str(v) for v in value)
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
from flask import Flask, redirect, url_for from werkzeug.routing import BaseConverter # 创建自定义转换器 class RegexConverter(BaseConverter): # regex = "[0-9]{6}" def __init__(self, url_map, *args): super(RegexConverter, self).__init__(url_map) self.regex = args[0] class ListConverter(BaseConverter): regex = "(\\d+,)+\\d$" # 匹配参数后 对参数进行处理 再返回到视图函数上去 def to_python(self, value): return value.split(',') # 使用url_for 的时候,对视图函数传的参数进行处理,以匹配路由 def to_url(self, value): result = ",".join(str(v) for v in value) return result app = Flask(__name__) # 将自己的转换器加入默认的服务器列表中 app.url_map.converters["re"] = RegexConverter app.url_map.converters["list"] = ListConverter # 规则: /user/6位数字 [0-9]{6} # 自定义转换器 @app.route("/user/<re('[0-9]{5}'):user_id>") def demo1(user_id): return "index + %s" % user_id @app.route("/users/<list:user_id>") def demo2(user_id): return "uses + %s" % user_id @app.route("/demo3") def demo3(): return redirect(url_for("demo2", user_id=[1, 2, 3, 4])) if __name__ == '__main__': app.run(debug=True)
3.4 错误捕捉
abort(404) #直接抛出 404
@app.errorhandler(404) # 捕捉404 返回不见了
def demo1():
return "页面不见了"