前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >95 - 在Flask中如何使用动态路由

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

原创
作者头像
ruochen
修改2021-06-28 10:20:11
5.3K0
修改2021-06-28 10:20:11
举报

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

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

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

代码语言:txt
复制
'''
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()
代码语言:txt
复制
 * 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
代码语言:txt
复制
 * 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 -

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1. 静态路由和动态路由有什么区别?
  • 2. 如何使用Flask实现动态路由
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档