~玉米糊~
慢慢来,也会很快。 非宁静无以志学,学什么都一样,慢慢打基础,找规律、认真、坚持,其余的交给时间。

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

路由:Url Path

http://localhost/abc/test.html

abc/test.html

静态路由:Path与路由函数一一对应

动态路由:多个Path与同一个路由函数对应

http://localhost/abc/test.html

http://localhost/xyz/test.html

 

不管访问哪一个Url,都会执行同一个服务端的路由函数

动态路由通过<...>指定动态传递的参数

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

# pip install flask

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(name):
    return f'<h1>hello Bill</h1>'

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

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

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

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

if __name__ == '__main__':
    app.run()

  

posted on 2022-04-21 10:16  yuminhu  阅读(168)  评论(0编辑  收藏  举报