95 - 在Flask中如何使用动态路由

1. 静态路由和动态路由有什么区别?

  • 路由
    • Utl Path
    • http://loaclhost/abc/test.html
  • 静态路由
    • Path与路由函数一一对应
  • 动态路由
    • 多个Path与同一个路由函数对应
    • http://loaclhost/abc/test.html
    • http://loaclhost/xyz/test.html
    • 不管访问哪一个Url,都会执行同一个服务端的路由函数

2. 如何使用Flask实现动态路由

'''
pip install flack
'''

from flask import Flask
app = Flask('__name__')

# 静态路由
@app.route('/')
def index():
    return '<h1>root</h1>'

@app.route('/greet')
def greet():
    return '<h1>Hello everyone</h1>'

@app.route('/greet/bill')
def greetBill():
    return '<h1>你好 Bill</h1>'

# 动态路由
@app.route('/greet/<name>')
def greetName(name):
    return '<h1>Hello {}</h1>'.format(name)

'''
如果静态路由和动态路由有冲突,优先使用静态路由
'''

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

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

if __name__ == '__main__':
    app.run()
 * Serving Flask app "__name__" (lazy loading)
 * Environment: production
   WARNING: This is a development server. Do not use it in a production deployment.
   Use a production WSGI server instead.
 * Debug mode: off


 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
127.0.0.1 - - [31/Mar/2020 15:57:45] "GET /greet/bill/1/2 HTTP/1.1" 200 -
127.0.0.1 - - [31/Mar/2020 15:57:54] "GET /greet/1-2-3 HTTP/1.1" 200 -

96 - 用Flask实现转发与重定向

发布了233 篇原创文章 · 获赞 271 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/qq_29339467/article/details/105264212
95