码迷,mamicode.com
首页 > 其他好文 > 详细

Flask - 路由

时间:2018-05-08 16:39:36      阅读:202      评论:0      收藏:0      [点我收藏+]

标签:secret   str   django   name   one   实现   mes   源码   调用   

一. 路由和响应函数(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 - 路由

标签:secret   str   django   name   one   实现   mes   源码   调用   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!