zoukankan      html  css  js  c++  java
  • 3. Flask路由系统

    一、常用路由系统

    - @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'])
    

    二、路由参数

    1. methods

    ​ methods:当前url地址,允许访问的请求方式,默认不写为GET方法

    @app.route("/info", methods=["GET", "POST"])
    def student_info():
        stu_id = int(request.args["id"])
        # Python3.6的新特性 f"{变量名}"
        return f"Hello Old boy {stu_id}"  
    

    2. endpoint

    ​ endpoint:反向url地址,默认为仕途函数名(url_for)

    from flask import url_for
    
    @app.route("/info", methods=["GET", "POST"], endpoint="r_info")
    def student_info():
        print(url_for("r_info"))  # /info
        stu_id = int(request.args["id"])
        return f"Hello Old boy {stu_id}" 
    

    3. defaults

    ​ defaults:视图函数的参数默认值{"nid": 1}

    from flask import url_for
    
    @app.route("/info", methods=["GET", "POST"], endpoint="r_info", defaults={"nid": 100})
    def student_info(nid):  #这里形参必须有个nid接收
        print(url_for("r_info"))  # /info
        # stu_id = int(request.args["id"])
        print(nid)  # 100
        return f"Hello Old boy {nid}"
    

    4. strict_slashes

    ​ strict_slashes:url地址结尾符"/"的控制;False:无论结尾"/"是否存在均可访问;True:结尾必须不能是"/"

    # 访问地址 : /info 
    @app.route("/info", strict_slashes=True)
    def student_info():
        return "Hello Old boy info"
    # 访问地址 : /infos  or  /infos/
    @app.route("/infos", strict_slashes=False)
    def student_infos():
        return "Hello Old boy infos"
    

    5. redirect_to

    ​ redirect_to:url地址重定向,且为308永久重定向

    # 访问地址 : /info 浏览器跳转至 /infos;如:老网页仍有用户,新网页上线使用。
    @app.route("/info", strict_slashes=True, redirect_to="/infos")
    def student_info():
        return "Hello Old boy info"
    @app.route("/infos", strict_slashes=False)
    def student_infos():
        return "Hello Old boy infos"
    

    6. subdomain

    ​ subdomain : 子域名前缀 subdomian=”cnblogs” 这样写可以得到 cnblogs.aspx.com 前提是app.config[“SERVER_NAME”] = “aspx.com”

    app.config["SERVER_NAME"] = "aspx.com"
    @app.route("/info",subdomain="cnblogs")
    def student_info():
        return "Hello cnblogs info"
    # 访问地址为:  cnblogs.aspx.com/info
    

    7. 动态参数路由

    ​ 就是在url后定义一个参数接收;但是这种动态参数路由,在url_for的时候,一定要将动态参数名+参数值添加进去,否则会抛出参数错误的异常

    from flask import url_for
    
    # 访问地址 : http://127.0.0.1:5000/info/1
    @app.route("/info/<int:nid>", methods=["GET", "POST"], endpoint="r_info")
    def student_info(nid):
        print(url_for("r_info",nid=2))  # /info/2
        return f"Hello Old boy {nid}" 
    
    1. 多个参数传递
    
    from flask import url_for
    # 访问地址 : http://127.0.0.1:5000/info/1
    @app.route("/info/<nid1>/<nid2>", methods=["GET", "POST"], endpoint="r_info")
    def student_info(nid):
        print(url_for("r_info",nid=2,nid=3))  # /info/2/3
        return f"Hello Old boy {nid}" 
    

    三、支持正则表达式

    1. 默认支持转换器

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

    2. 路由支持正则匹配

    from flask import Flask, views, url_for
    from werkzeug.routing import BaseConverter
    
    app = Flask(import_name=__name__)
    
    # 1. 写RegexConverter类
    class RegexConverter(BaseConverter):
        """
        自定义URL匹配正则表达式
        """
        def __init__(self, map, regex):
            super(RegexConverter, self).__init__(map)
            self.regex = regex
    
        def to_python(self, value):
            """
            路由匹配时,匹配成功后传递给视图函数中参数的值
            :param value:
            :return:
            """
            return int(value)
    
        def to_url(self, value):
            """
            使用url_for反向生成URL时,传递的参数经过该方法处理,返回的值用于生成URL中的参数
            :param value:
            :return:
            """
            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()
    
  • 相关阅读:
    后缀名文件说明
    转行小白成长路-java篇
    转行小白成长路-java篇
    转行小白成长路-java篇
    转行小白成长路-java篇
    转行小白成长路-java篇
    转行小白成长路-java篇
    转行小白成长路-java篇
    转行小白成长路-java篇
    转行小白成长路-java篇
  • 原文地址:https://www.cnblogs.com/hq82/p/12636187.html
Copyright © 2011-2022 走看看