1. 程式人生 > >Flask - 路由

Flask - 路由

itl 添加路由 數據 des con AD cor ref lock

一. 路由和響應函數(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.
"""

Flask - 路由