文章目录
route()装饰器源码解析
@app.route('/index1')
def hello_world(): # put application's code here
return 'Hello World!'
@setupmethod
def route(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]:
"""Decorate a view function to register it with the given URL
rule and options. Calls :meth:`add_url_rule`, which has more
details about the implementation.
.. code-block:: python
@app.route("/")
def index():
return "Hello, World!"
See :ref:`url-route-registrations`.
The endpoint name for the route defaults to the name of the view
function if the ``endpoint`` parameter isn't passed.
The ``methods`` parameter defaults to ``["GET"]``. ``HEAD`` and
``OPTIONS`` are added automatically.
:param rule: The URL rule string.
:param options: Extra options passed to the
:class:`~werkzeug.routing.Rule` object.
"""
def decorator(f: T_route) -> T_route:
endpoint = options.pop("endpoint", None)
self.add_url_rule(rule, endpoint, f, **options)
return f
return decorator
本质:
app.router()—>本质上就是self.add_url_rule,self就是flask对象app
注册路由方式一:常规注册
@app.router('/') # 推荐使用 def index(): ...
方式二:本质操作
app.add_url_rule('/', view_func=index)
路由参数
路由规则[rule]
-
转换器:单个参数
- @app.route(‘/arg/<name>/’) # 默认字符串
- @app.route(‘/arg/<int:name>/’) # 限制值的类型为整形
- @app.route(‘/arg/<float:name>/’) # 限制值的类型为浮点形
- @app.route(‘/arg/<path:name>/’) # 值的类型为字符串但是路由地址的分隔符/是作为参数值的1部分
-
多个参数
-
@app.route(‘/args/<name>/<int:age>/’)
@app.route('/index/<int:nid>',methods=['GET','POST']) def index(nid): print("int类型: ", nid) return "返回结果是: int类型的nid"
-
@app.route(‘/args/<name>_<int:age>/’)
-
别名[endpoint]
当前路由的别名,如果不传,默认将函数名作为endpoint,如果函数名重名,就会有两个重名的地址,报错
-
主要用来反向解析源码
endpoint = _endpoint_from_view_func(view_func)
-
反向生成url
即:url_for(‘名称’) # url_for 通过 endpoint 的值反向解析出 url
from flask import url_for @app.route('/index', methods=['GET','POST'], endpoint="first") def index(): h1 = url_for("first") h2 = url_for("login") # 不起别名 使用默认名 h3 = url_for("logout") # 不起别名 使用默认名 print(h1, h2, h3) return "index" @app.route('/login',methods=['GET','POST']) def login(): return "login" @app.route('/logout',methods=['GET','POST']) def logout(): return "logout" GET 请求 /index /login /logout
处理请求的视图函数[view_fun]
-
FBV
@app.route('/login',methods=['GET','POST']) def login(): return "login"
-
CBV
在flask 中,cbv 可以选择继承 View (django 继承的是View) 和 MethodView 两个类
如果继承 View 类,需要重写 dispatch 方法
如果继承 MethodView 类,直接写 get , post 方法即可
class HomeView(MethodView): methods = ['GET'] # 允许请求方式 decorators = [auth, ] # 加载装饰器 def get(self): print(request.path) return 'cbv的homeview' # 添加路由 # name 是路由别名,跟endpoint一个作用,但是cbv必须传name 也可将路由的加载放在类中 app.add_url_rule('/home',view_func=HomeView.as_view(name='home'))
重定向[redirect_to]
重定向到指定地址
@app.route('/old',methods=['GET','POST'],redirect_to='/new')
def old():
return "老功能"
@app.route('/new',methods=['GET','POST'])
def new():
return "新功能"
请求方式[methods]
methods=[“GET”], 允许的请求方式,如:[“GET”, “POST”]
末尾\
是否严格[strict_slashes]
strict_slashes = None
对URL最后的/
符号是否严格要求,默认不严格
URL无参数时,而函数又需要参数[defaults]
defaults = None, 默认值, 当URL中无参数,函数需要参数时,使用defaults = {‘k’: ‘v’}
为函数提供参数,就是django中的kwargs
子域名访问[subdomain]
subdomain = None
from flask import Flask
app = Flask(__name__)
# 绑定 URL 规则到子域名
@app.route('/', subdomain='admin')
def admin_home():
return 'Admin Home Page'
# 绑定 URL 规则到无子域名的请求
@app.route('/')
def home():
return 'Home Page'
if __name__ == '__main__':
app.run()
当请求的子域名为 admin 时,将触发 admin_home 视图函数;否则,将触发 home 视图函数。
如果在浏览器中访问 http://admin.example.com/,将返回 "Admin Home Page";而访问 http://example.com/,将返回 "Home Page"。