【Flask】路由详解

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"。
  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Flask是一个轻量级的Web框架,它提供了简单易用的路由功能,可以轻松地创建和管理Web应用程序的路由Flask路由的用法如下: 1. 导入Flask模块和路由函数: ```python from flask import Flask, render_template, request, redirect, url_for ``` 2. 创建Flask应用程序实例: ```python app = Flask(__name__) ``` 3. 定义路由函数: ```python @app.route('/') def index(): return 'Hello, World!' ``` 这个路由函数定义了一个根路由,当用户访问网站根目录时,会返回"Hello, World!"。 4. 运行应用程序: ```python if __name__ == '__main__': app.run() ``` 当你运行这个Python文件时,Flask应用程序将在本地启动,可以通过浏览器访问http://localhost:5000/来查看结果。 除了根路由外,还可以定义其他路由,例如: ```python @app.route('/user/<name>') def user(name): return 'Hello, %s!' % name ``` 这个路由函数定义了一个/user/<name>路由,当用户访问/user/xxx时,会返回"Hello, xxx!",其中xxx是用户输入的任意字符串。 Flask路由还支持HTTP方法,例如: ```python @app.route('/login', methods=['GET', 'POST']) def login(): if request.method == 'POST': # 处理POST请求 return redirect(url_for('index')) else: # 处理GET请求 return render_template('login.html') ``` 这个路由函数定义了一个/login路由,当用户访问/login时,如果是GET请求,会返回login.html模板;如果是POST请求,会执行相应的处理逻辑,并重定向到根路由

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Al6n Lee

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值