Flask - 路由

一. 路由和响应函数(View function)的映射是通过装饰器实现的

1.

"""
#装饰器:
def wrapper(func):
    def inner(*args, **kwargs):
        return func(*args, **kwargs)
    return inner

@wrapper 相当于 index = wrapper(index)
def index(request):
    pass
"""

# app.route(‘path‘)将view function注册到一个类似于字典的数据结构中,从而实现路由和响应函数的映射。
url_map = {
    ‘/index‘: index
}

def route(option):  # {‘k1‘:‘v1‘}
    def inner(func, *args, **kwargs):
        url_map[option[‘path‘]] = func

    return inner

# inner = wrapper({‘k1‘:‘v1‘})
# @inner --> inner(index)
@route({‘path‘: ‘/index‘})
def index(request):
    pass

2. app.route源码

def route(self, rule, **options):
    """A decorator that is used to register a view function for a
    given URL rule.  This does the same thing as :meth:`add_url_rule`
    but is intended for decorator usage::

        @app.route(‘/‘)
        def index():
            return ‘Hello World‘

    For more information refer to :ref:`url-route-registrations`.

    :param rule: the URL rule as string
    :param endpoint: the endpoint for the registered URL rule.  Flask
                     itself assumes the name of the view function as
                     endpoint
    :param options: the options to be forwarded to the underlying
                    :class:`~werkzeug.routing.Rule` object.  A change
                    to Werkzeug is handling of method options.  methods
                    is a list of methods this rule should be limited
                    to (``GET``, ``POST`` etc.).  By default a rule
                    just listens for ``GET`` (and implicitly ``HEAD``).
                    Starting with Flask 0.6, ``OPTIONS`` is implicitly
                    added and handled by the standard request handling.
    """

    def decorator(f):
        endpoint = options.pop(‘endpoint‘, None)
        self.add_url_rule(rule, endpoint, f, **options)
        return f

    return decorator

3. app.route自我理解

"""
1. decorator = app.route(‘/‘,methods=[‘GET‘,‘POST‘],endpoint=‘n1‘)
    def route(self, rule, **options):
        # app对象
        # rule= /
        # options = {methods=[‘GET‘,‘POST‘],endpoint=‘n1‘}
        def decorator(f):
            endpoint = options.pop(‘endpoint‘, None)
            self.add_url_rule(rule, endpoint, f, **options) #添加路由的本质!!!!!!!!!
            return f
        return decorator
2. @decorator
    decorator(index)
"""
@app.route(‘/‘,methods=[‘GET‘,‘POST‘],endpoint=‘n1‘)
def index():
    return ‘Hello World!‘

4. 不通过装饰器添加路由,手动添加路由

知道了app.route()里面的self.add_url_rule是本质,所以自己可以手动调用这个方法添加路由

def login():
    return ‘登录‘

app.add_url_rule(‘/login‘, ‘n2‘, login, methods=[‘GET‘,"POST"])

5. 常用的路由系统

@app.route(‘/user/<username>‘)
@app.route(‘/post/<int:post_id>‘)
@app.route(‘/post/<float:post_id>‘)
@app.route(‘/post/<path:path>‘)
@app.route(‘/login‘, methods=[‘GET‘, ‘POST‘])
DEFAULT_CONVERTERS = {
    ‘default‘:          UnicodeConverter,
    ‘string‘:           UnicodeConverter,
    ‘any‘:              AnyConverter,
    ‘path‘:             PathConverter,
    ‘int‘:              IntegerConverter,
    ‘float‘:            FloatConverter,
    ‘uuid‘:             UUIDConverter,
}

6. 还可以用CBV(class bsae view)添加路由,和Django一样,留坑。

from flask import Flask,views

app = Flask(__name__)
app.debug = True
app.secret_key = "asdfasdf"

def auth(func):
    def inner(*args, **kwargs):
        result = func(*args, **kwargs)
        return result
    return inner

class IndexView(views.MethodView):
    methods = [‘GET‘]
    decorators = [auth, ]

    def get(self):
        return ‘Index.GET‘

    def post(self):
        return ‘Index.POST‘

app.add_url_rule(‘/index‘, view_func=IndexView.as_view(name=‘index‘))  # name=endpoint

if __name__ == ‘__main__‘:
    app.run()

from flask import views

"""
    flask.views
    ~~~~~~~~~~~

    This module provides class-based views inspired by the ones in Django.

    :copyright: ? 2010 by the Pallets team.
    :license: BSD, see LICENSE for more details.
"""

原文地址:https://www.cnblogs.com/allen2333/p/9008305.html

时间: 2024-10-29 18:02:44

Flask - 路由的相关文章

【Flask路由系统】 -- 2019-08-11 19:11:52

目录 动态路由参数 路由参数 methods endpoint defaults strict_slashes redirect_to subdomain 原文: http://106.13.73.98/__/112/ @(Flask路由) *** 动态路由参数 三种用法 <int:xx> 要求输入的url必须是可转换为int类型的 <string:xx> 要求输入的url必须是可转换为String类型 <xx> 默认使用的是可转换为String类型的 开始测试 代码如

【Flask路由系统】 &#538110;

目录 动态路由参数 路由参数 methods endpoint defaults strict_slashes redirect_to subdomain 原文: http://blog.gqylpy.com/gqy/337 "@(Flask路由) *** 动态路由参数 三种用法 <int:xx> 要求输入的url必须是可转换为int类型的 <string:xx> 要求输入的url必须是可转换为String类型 <xx> 默认使用的是可转换为String类型的

flask路由和视图和cookie

什么是路由 """ 客户端(例如web浏览器)把请求发送给Web服务器,Web服务器再把请求发送给Flask程序实例. 程序实例需要知道对每个URL请求运行那些代码,所以保存了一个URL到Python函数的映射关系. 处理URL和函数之间关系的程序称之为路由. """ 看个简单完整的的例子 #!/usr/bin/env python # -*- coding:utf-8 -*- from flask import Flask app = Flas

Flask路由

@app.route() methods:当前url地址,允许访问的请求方式 @app.route("/info", methods=["GET", "POST"]) def student_info(): stu_id = int(request.args.get("id")) return f"{stu_id}" # Python3.6的新特性 f"{变量名}" endpoint:反

flask 路由规划(blueprint)

# 统一路由蓝牙规划 # file:blueprint_route.py from flask import Blueprint route_test = Blueprint("home",__name__) # 路由只有通过app注册后才生效 """ 统一路由规划的优点: 统一前缀 当网站结构复杂后可维护 """ @route_test.route("/") def home(): return &quo

Flask路由+视图补充

一.路由设置的两种方法 1.装饰器 @app.route('/index/') def index(): return 'Hello World!' 2.源码 route->decorator->add_url_rule(rule, endpoint, f, **options) def index(): return 'Hello World!' app.add_url_rule('/index/', None, index) 注意:endpoint的值不能一致 二.参数 rule URL规

Flask快速入门(3) — flask路由的本质

目录 route():就是一个加在index()上的装饰器 add_url_rule():将匹配规定与视图函数的对应关系添加到路由 总结: from flask import Flask app = Flask(__name__) @app.route('/') def index(): return 'ok' if __name__ == '__main__': app.run() 从这个简单的代码入口,来剖析一下路由@app.route('/') route():就是一个加在index()上

flask路由规划蓝图和route

引言: 在写任何web项目的时候路由的配置永远都是不可或缺的,如django中的include方法flask中的Blueprint这些都是用于将多个application中的路由区别开来,如果你要使用restful风格,那么这种路由一定是必须做的,很多教程在编写代码会在每一个视图函数上面写清楚完整的路径,包括请求的参数.以及请求的方法,其实就是为了达到这样的目的 在flask中当一个庞大的系统中有很多小模块,在分配路由的时候怎么处理呢?全部都堆到一个py程序中,调用@app.route? 显然这

Flask路由之重定向

Flask框架提供了请求重定向功能,只需要使用 redirect_to即可, 示例代码如下: from flask import Flask, render_template, request, redirect, session app = Flask(__name__) app.secret_key = 'flask' app.debug = True """ redirect_to: 会将请求index 重定向到index2 """ @ap