zoukankan      html  css  js  c++  java
  • flask路由

    典型写法

    #flask的路由是基于装饰器的
    
    @app.route('/detail/<int:nid>',methods=['GET'],endpoint='detail')
    #<int:nid>转换器
    #methods=['GET']该路由允许的请求方式
    #endpoint='detail'   起别名,反向解析时用

    默认转换器

    DEFAULT_CONVERTERS = {
        'default':          UnicodeConverter,
        'string':           UnicodeConverter,      #常用
        'any':              AnyConverter,
        'path':             PathConverter,
        'int':              IntegerConverter,      #常用
        'float':            FloatConverter,
        'uuid':             UUIDConverter,
    }
    View Code

    路由的本质

    #路由的本质虽然是基于装饰器,但本质是:add_url_rule
    #所以可以不用装饰器来配置,直接使用add_url_rule,需要什么参数传参数
    例如:
    def index()
        return 'ok'
    
    app.add_url_rule('/'.view_func=index,endpoint='in')
    
    
    
    ---------------------------------------------------------------
    源码分析
    def route(self, rule, **options):
        def decorator(f):
            endpoint = options.pop("endpoint", None)     #别名默认为空,可以不传
            self.add_url_rule(rule, endpoint, f, **options)   #其实本质就是这个函数
            return f
        return decorator
    
    #加括号执行,相当于把decorator放到index上边,    def decorator(f):此时f就是index
    @app.route('/',methods=['GET','POST'],endpoint=None)  #点进去得到上面的函数
    def index():
        return 'ok'
    
    
    #点add_url_rule进去
        def add_url_rule(
            self,
            rule,
            endpoint=None,
            view_func=None,
            provide_automatic_options=None,
            **options ):#看清楚上边的几个是参数
    
            if endpoint is None:     #如果没有别名  
                                    #下边这个函数是断言,别名为None,返回函数名
                endpoint = _endpoint_from_view_func(view_func)  
            options["endpoint"] = endpoint
            methods = options.pop("methods", None)

    转换器支持正则(自定义转换器)

    #1 写类,继承BaseConverter
    #2 注册:app.url_map.converters['regex'] = RegexConverter
    # 3 使用:@app.route('/index/<regex("d+"):nid>')  正则表达式会当作第二个参数传递到类中
    from flask import Flask, views, url_for
    from werkzeug.routing import BaseConverter
    
    app = Flask(import_name=__name__)
    
    class RegexConverter(BaseConverter):
        """
        自定义URL匹配正则表达式
        """
        def __init__(self, map, regex):
            super(RegexConverter, self).__init__(map)
            self.regex = regex
    
        def to_python(self, value):
            """
            路由匹配时,匹配成功后传递给视图函数中参数的值
            """
            return int(value)
    
        def to_url(self, value):
            """
            使用url_for反向生成URL时,传递的参数经过该方法处理,返回的值用于生成URL中的参数
            """
            val = super(RegexConverter, self).to_url(value)
            return val
    # 添加到flask中
    app.url_map.converters['regex'] = RegexConverter
    @app.route('/index/<regex("d+"):nid>')
    def index(nid):
        print(url_for('index', nid='888'))
        return 'Index'
    
    if __name__ == '__main__':
        app.run()
    View Code

    蓝图

    1 xxx = Blueprint('account', __name__,url_prefix='/xxx') :蓝图URL前缀,表示url的前缀,在该蓝图下所有url都加前缀
    
    2 xxx = Blueprint('account', name,url_prefix='/xxx',template_folder='tpls'):给当前蓝图单独使用templates,向上查找,当前找不到,会找总templates
    
    3 蓝图的befort_request,对当前蓝图有效
    
    4 大型项目,可以模拟出类似于django中app的概念

    目录结构

    -flask_pro
        -flask_test
            -__init__.py
            -static
            -templates
            -views
                -order.py
                -user.py
         -run.py 
            

    __init__.py

    from flask import  Flask
    app=Flask(__name__)
    from flask_test.views import user
    from flask_test.views import order
    app.register_blueprint(user.us)
    app.register_blueprint(order.ord)

    run.py

    from flask_test import  app
    if __name__ == '__main__':
        app.run(port=8008)

    user.py

    from flask import Blueprint
    us=Blueprint('user',__name__)
    
    @us.route('/login')
    def login():
        return 'login'
  • 相关阅读:
    MongoDB中级---->关联多表查询
    Java爬虫,信息抓取的实现
    Android Java汉字转拼音总结
    Android使用Activity用作弹出式对话框
    利用Theme自定义Activity间的切换动画
    ListView滑动删除 ,仿腾讯QQ
    CentOS 6.2+Nginx+Nagios,手机短信和qq邮箱提醒
    玩转Web之easyui(三)-----easy ui dataGird 重新指定url以获取不同数据源信息
    rsyslogd: error during parsing file /etc/rsyslog.conf, on or before line 55: warnings occured in fil
    升级automake和autoconf
  • 原文地址:https://www.cnblogs.com/pdun/p/11205432.html
Copyright © 2011-2022 走看看