烧瓶中的多个路由 - Python

Pri*_*v v 2 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"
...
Run Code Online (Sandbox Code Playgroud)

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

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

mha*_*wke 7

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

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

  • request.url_rule将为您提供作为@app.route装饰器的第一个参数提供的规则,逐字逐句.这将包括指定的路径的任何可变部分<variable>.
  • 使用request.endpoint默认为视图函数名称的函数,但是,可以使用endpoint 参数to 显式设置它@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()
Run Code Online (Sandbox Code Playgroud)

另一种方法是将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'))
Run Code Online (Sandbox Code Playgroud)