You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让两个Flask路由指向同一函数并按路由响应POST请求?

如何让多个Flask路由指向同一函数并根据路由响应?

当然可行!Flask原生就支持将多个路由绑定到同一个视图函数,你只需要通过请求对象区分当前触发的路由,就能返回对应的响应。下面给你两种常用的实现方式:

方法一:通过请求路径(request.path)判断

这是最直接的方式,通过request.path获取当前请求的URL路径,就能精准区分是哪个路由触发的函数:

from flask import Flask, request

app = Flask(__name__)

# 给两个路由都指定允许的请求方法
@app.route('/client_progress', methods=['POST', 'GET'])
@app.route('/client_update', methods=['POST', 'GET'])
def func_1():
    # 判断当前请求的路由路径
    if request.path == '/client_progress':
        if request.method == 'POST':
            return 'hello world'
        # 补充GET请求的响应逻辑(可选,但建议加上)
        return 'Welcome to client progress page'
    elif request.path == '/client_update':
        if request.method == 'POST':
            return 'Good World'
        # 补充GET请求的响应逻辑
        return 'Welcome to client update page'

方法二:通过路由端点(request.endpoint)判断

你也可以给每个路由指定一个唯一的endpoint标识,后续通过request.endpoint来判断。这种方式的好处是:如果之后需要修改路由的URL,只要endpoint不变,判断逻辑就不用调整:

from flask import Flask, request

app = Flask(__name__)

# 给每个路由指定不同的endpoint
@app.route('/client_progress', methods=['POST', 'GET'], endpoint='client_progress')
@app.route('/client_update', methods=['POST', 'GET'], endpoint='client_update')
def func_1():
    if request.endpoint == 'client_progress':
        if request.method == 'POST':
            return 'hello world'
        return 'Progress page GET response'
    elif request.endpoint == 'client_update':
        if request.method == 'POST':
            return 'Good World'
        return 'Update page GET response'

注意事项

  • 记得给路由明确指定methods参数,避免Flask默认只允许GET请求的问题。
  • 尽量补充每种请求方法的响应逻辑,避免出现请求无返回值的情况(Flask会返回405错误)。

内容的提问来源于stack exchange,提问作者PanDe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 09:03:24