烧瓶中的多个路由 - Python

时间:2017-09-30 10:35:09

标签: python flask

我是烧瓶的初学者 - Python。我面临着多路由的问题。我经历过谷歌搜索。但是没有完全了解如何实现它。 我开发了一个烧瓶应用程序,我需要为不同的URL重用相同的视图函数。

@app.route('/test/contr',methods=["POST", "GET"],contr=None)
@app.route('/test/primary', methods=["POST", "GET"])
def test(contr):                                          
    if request.method == "POST":
        if contr is None:
            print "inter"
        else:
            main_title = "POST PHASE"
...

我想为2路由调用测试功能。&除了所有其他功能都相同外,它们的功能不同。所以我虽然重用。但是没有得到如何使用从将调用重定向到此测试函数的函数传递的一些参数来区分测试函数内的路由。

我找不到一个很好的教程,从头开始定义多个路由的基础

1 个答案:

答案 0 :(得分:5)

您可以通过多种方式处理此问题。

您可以深入了解request对象,了解哪个规则触发了对视图函数的调用。

  • request.url_rule将为您提供以。提供的规则 @app.route装饰者的第一个参数,逐字逐句。这将 包括用<variable>指定的路线的任何可变部分。
  • 使用默认为视图名称的request.endpoint 但是,它可以使用endpoint显式设置 @app.route的论点。我更喜欢这个,因为它可能很短 字符串而不是完整的规则字符串,您可以更改规则而无需更新视图函数。

以下是一个例子:

from flask import Flask, request

app = Flask(__name__)

@app.route('/test/contr/', endpoint='contr', methods=["POST", "GET"])
@app.route('/test/primary/', endpoint='primary', methods=["POST", "GET"])
def test():
    if request.endpoint == 'contr':
        msg = 'View function test() called from "contr" route'
    elif request.endpoint == 'primary':
        msg = 'View function test() called from "primary" route'
    else:
        msg = 'View function test() called unexpectedly'

    return msg

app.run()

另一种方法是将defaults字典传递给@app.route。字典将作为关键字参数传递给视图函数:

@app.route('/test/contr/', default={'route': 'contr'}, methods=["POST", "GET"])
@app.route('/test/primary/', default={'route': 'primary'}, methods=["POST", "GET"])

def test(**kwargs):
    return 'View function test() called with route {}'.format(kwargs.get('route'))