• 227.3.flask路由


    1

    from flask import Flask
    
    app = Flask(__name__)
    app.config.from_object("settings.DevelopmentConfig")
    
    
    @app.route("/index", methods=["POST", "GET"])
    def index():
        pass
    
    
    def order():
        return "order"
    
    
    app.add_url_rule("/order", view_func=order)
    
    
    if __name__ == '__main__':
        app.run()
    
    

    2

    # coding=utf-8
    # coding=utf8
    from flask import Flask, url_for
    
    app = Flask(__name__)
    app.config.from_object("settings.DevelopmentConfig")
    
    
    @app.route("/index", methods=["POST", "GET"], endpoint="n1")
    def index():
        v1 = url_for("n1")  # endpoint用于反向生成路由, 默认不起别名endpoint就是他的函数名
        v2 = url_for("n2")
        v3 = url_for("n3")
    
    
    @app.route("/index", methods=["POST", "GET"], endpoint="n2")
    def index2():
        pass
    
    
    @app.route("/index", methods=["POST", "GET"], endpoint="n3")
    def index3():
        pass
    
    
    if __name__ == '__main__':
        app.run()
    
    
    
    

    3

    # coding=utf-8
    # coding=utf8
    from flask import Flask, url_for
    
    app = Flask(__name__)
    app.config.from_object("settings.DevelopmentConfig")
    
    
    @app.route("/index/<int:nid>", methods=["POST", "GET"])
    def index(nid):
        print(nid)  # url后面可以加一个uid, 比如/index/1
        return "index"
    
    
    if __name__ == '__main__':
        app.run()
    
    

    4

    # coding=utf-8
    """自定义装换器"""
    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):
            """
            路由匹配时,匹配成功后传递给视图函数中参数的值
            :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
    
    
    # 执行自定义转换器头to_python
    @app.route('/index/<regex("\d+"):nid>')
    def index(nid):
        # 执行自定义转换器to_url
        print(url_for('index', nid='888'))
        return 'Index'
    
    
    if __name__ == '__main__':
        app.run()
    

    5

    # coding=utf-8
    from flask import Flask
    
    app = Flask(__name__)
    app.config.from_object("settings.DevelopmentConfig")
    
    
    # defaults传进去一个默认值, redirect_to跳转到另一个路由
    @app.route("/old", methods=["POST", "GET"], endpoint="a",
               defaults={"a": 1}, redirect_to="/new", subdomain="")
    def old():
        return "老功能"
    
    
    @app.route("/new", methods=["POST", "GET"])
    def new():
        return "新功能"
    
    
    if __name__ == '__main__':
        app.run()
    

    6

    # coding=utf-8
    from flask import Flask
    
    app = Flask(__name__)
    
    # 定义服务器域名
    app.config["SERVER_NAME"] = "oldboy.com:5000"
    
    
    # subdomain匹配子域名, 比如http://www.oldboy.com:5000/old,  username="www"
    @app.route("/old", methods=["POST", "GET"], subdomain="<username>")
    def old(username):
        print(username)
        return "老功能"
    
    
    @app.route("/new", methods=["POST", "GET"])
    def new():
        return "新功能"
    
    
    if __name__ == '__main__':
        app.run(debug=True)
    
    

    装饰器作业

    # coding=utf-8
    from flask import Flask
    from functools import wraps
    app = Flask(__name__)
    app.config.from_object("settings.DevelopmentConfig")
    
    
    def wapper(func):
        @wapper(func)
        def inner(*arg,**kwargs):
            print("before")
            return func(*arg, **kwargs)
        return inner
    
    
    @app.route("/index", methods=["POST", "GET"])
    @wapper  # 装饰器需要写到route装饰器的下面
    def index():
        pass
    
    
    def order():
        return "order"
    
    
    app.add_url_rule("/order", view_func=order)
    
    
    if __name__ == '__main__':
        app.run()
    
  • 相关阅读:
    Python练习题 016:猴子吃桃
    Date() 及其 如何验证用户输入的日期是合法的
    关于事件触发的一个小tips
    KVO监听导航栏
    使用CoreText动态下载更换字体
    UICollectionView 的使用
    echarts散点图搭配时间轴
    使用百度echarts画图表的步骤
    canvas画图中drawImage使用
    html5canvas简单画图
  • 原文地址:https://www.cnblogs.com/liuzhanghao/p/16337495.html
Copyright © 2020-2023  润新知