美文网首页Python
Python基础(45) - 在Flask中如何使用动态路由

Python基础(45) - 在Flask中如何使用动态路由

作者: xianling_he | 来源:发表于2020-03-14 10:42 被阅读0次

    静态路由与动态路由

    • 路由: URL Path
    • http://localhost/abc/test.html 中的abc/test.html 表示要访问的路由地址
    • 静态路由表示Path地址与路由函数是一一对应的关系
    • 动态路由表示有多个Path地址与路由函数是对应的关系
    • 不管访问的是哪个URL,都会执行同一个服务器的路由函数

    使用Flask工具

    • 使用pip install flask 导入包


      hexianling.png
    • 在Pycharm中导入


      hexianling.png
    hexianling.png
    • 代码如下:
    from flask import Flask
    
    app = Flask('__name__')
    
    @app.route('/')
    def index():
        return '<h1>Welcome</h1>'
    
    
    @app.route('/greet')
    def greet():
        return '<h1>So great</h1>'
    
    
    if __name__ == '__main__':
        app.run()
    

    动态路由

    • 使用参数传入到函数中
    @app.route('/greet/<name>')  # name 就是参数
    def greetName(name):
        return '<h1>So great {}</h1>'.format(name)
    
    • 如果静态路由与动态路由有冲突的话,优先使用静态路由
    #比如以下参数可以传任意的参数类型,如果参数 = Bill
    @app.route('/greet/<name>')  # name 就是参数
    def greetName(name):
        return '<h1>So great {}</h1>'.format(name)
    
    # 如果参数Bill 与静态路由相同都是Bill 那使用静态路由
    @app.route('/greet/Bill')
    def greet():
        return '<h1>So great Bill</h1>'
    
    • 动态路由传递多个参数
      使用不同的层级
    @app.route('/greet/<a1>/<a2>/<a3>')
    def arg1(a1,a2,a3):
        return '<h1>{},{},{}</h1>'.format(a1,a2,a3)
    

    相同的层级

    @app.route('/greet/<a1>-<a2>-<a3>')
    def arg2(a1,a2,a3):
        return '<h1>{}-{}-{}</h1>'.format(a1,a2,a3)
    

    总结

    1.静态路由就是一个URL对应的唯一路由函数
    2.动态路由有多个URL对应一个路由函数,动态路由通过<....>指定动态传递的参数

    相关文章

      网友评论

        本文标题:Python基础(45) - 在Flask中如何使用动态路由

        本文链接:https://www.haomeiwen.com/subject/hlhmshtx.html