• Flask之路由相关


    1.装饰器中的参数

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

    2.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}"  # Python3.6的新特性 f"{变量名}"

    3.defaults 视图函数中的默认参数值

    from flask import url_for,Flask
    app = Flask(__name__)
    @app.route("/info", methods=["GET", "POST"], endpoint="r_info", defaults={"nid": 100})
    def student_info(nid):
        print(url_for("r_info"))  # /info
        # stu_id = int(request.args["id"])
        print(nid)  # 100
        return f"Hello Old boy {nid}"  # Python3.6的新特性 f"{变量名}"
    app.run(debug=True)

    4.strict_slashes=True 是否严格遵循路由地址  (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 : url地址重定向

    from flask import Flask
    app = Flask(__name__)
    # 访问地址 : /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"
    app.run(debug=True)

     6.subdomain 子域名前缀

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

    7.动态路由参数

    from flask import Flask
    app = Flask(__name__)
    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}"  # Python3.6的新特性 f"{变量名}"# 访问地址为:  DragonFire.pythonav.com/info
    app.run(debug=True)

    注意:

    <int:nid> 就是在url后定义一个参数接收

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

  • 相关阅读:
    python之timeit模块
    python isinstance函数
    继承
    冒泡排序&&选择排序
    监听器
    被钝化的代码
    Ajax验证用户名
    原生ajax访问服务器所展现的现象
    今天
    随机点名
  • 原文地址:https://www.cnblogs.com/wqzn/p/10238643.html
Copyright © 2020-2023  润新知