Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/355.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
flask-Python中的多路由_Python_Flask - Fatal编程技术网

flask-Python中的多路由

flask-Python中的多路由,python,flask,Python,Flask,我是烧瓶Python的初学者。我面临多个路由的问题。我浏览过谷歌搜索。但是没有完全了解如何实施它。 我已经开发了一个flask应用程序,需要为不同的URL重用相同的视图功能 @app.route('/test/contr',methods=["POST", "GET"],contr=None) @app.route('/test/primary', methods=["POST", "GET"]) def test(contr):

我是烧瓶Python的初学者。我面临多个路由的问题。我浏览过谷歌搜索。但是没有完全了解如何实施它。 我已经开发了一个flask应用程序,需要为不同的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个路由调用测试函数。&除了所有其他功能相同外,其他功能都不同。所以我想到了重用。但是没有得到如何使用从函数传递的一些参数来区分测试函数内部的路由,这些参数将调用重定向到此测试函数


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

有几种方法可以处理路由的问题

您可以深入查看
request
对象,了解是哪个规则触发了对view函数的调用

  • request.url\u规则将为您提供作为
    
    @app.route
    装饰器的第一个参数,逐字逐句。这将 包括使用
    指定的路线的任何可变部分
  • 使用默认为视图名称的
    request.endpoint
    但是,可以使用
    端点显式设置该函数
    
    @app.route
    的参数。我更喜欢这个,因为它可以是短的 字符串而不是完整的规则字符串,并且您可以更改规则,而无需更新view函数
下面是一个例子:

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()

另一种方法是将
默认值
字典传递给
@app.route
。字典将作为关键字参数传递给view函数:

@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'))

为什么不为您的两条路线使用两条路线功能?你想在他们之间共享的任何逻辑都可以在他们都调用的第三个函数中。Daniel,我已经创建了许多这样的路由。所以考虑重用代码。如果一个应用程序中有20个页面,我需要为此创建20个路由函数吗?Flask应该有东西做的谢谢你伙计。你救了我一天…这就是我要找的。你能分享任何一份有详细说明的文件吗same@Priyavv:此处有一些信息,可以设置端点,但它基于路由。如果路径是
admin/site
set
endpoint='site'
,则结果将是
admin.site
,而不仅仅是
site