传递给Flask的可能路线列表?

时间:2017-03-25 05:22:37

标签: python api flask routing

我正在学习Flask并且对动态路由有疑问:是否可以传入已接受路由的列表?我注意到any转换器有潜力,但很难找到使用它的例子。基本上我有不同的端点组,应该在它们之间触发相同的操作。这就是我的意思:

cities = [New York, London, Tokyo]
food = [eggs, bacon, cheese]
actions = [run, walk, jump]

我可以做类似

的事情
@app.route('/<string:var>', methods = ['GET'])
def doSomething(var):
    if var in cities:
         travel(var)
    else if var in food:
         eat(var)
    else if var in action:
         perform(var)

但有什么方法可以做到这样吗?

@app.route('/<any(cities):var>', methods = ['GET'])
    def travel(var):

@app.route('/<any(food):var>', methods = ['GET'])
    def eat(var)

@app.route('/<any(actions):var>', methods = ['GET'])
    def perform(var)

另外,我希望这些列表是动态的。所以我真正想要的是:

cities = myDb.("SELECT cities FROM country")
@app.route('/<any(cities):var>', methods = ['GET'])
    def travel(var):

有没有办法实现这一目标,还是我在一条动态路线中阻止了一切?

2 个答案:

答案 0 :(得分:2)

Flask基于Werkzeug,并且它具有AnyConverter

基本上,它允许您声明Werkzeug规则,如下所示:

Rule('/<any(about, help, imprint, class, "foo,bar"):page_name>')

所以基本上对于烧瓶而言,它转化为:

from flask import Flask

app = Flask(__name__)


@app.route("/<any('option1', 'option2'):segment>")
def hello(segment):
    return "Hello {}!".format(segment)

app.run()

或者,如果您希望在应用启动时动态生成这些列表:

from flask import Flask

app = Flask(__name__)

options = ['option1', 'option2']


@app.route("/<any({}):segment>".format(str(options)[1:-1]))
def hello(segment):
    return "Hello {}!".format(segment)


app.run()

答案 1 :(得分:0)

这会接受任何字符串,检查列表并调用相应的函数:

from flask import Flask

app = Flask(__name__)

food = ['eggs', 'bacon', 'cheese']
actions = ['run', 'walk', 'jump']
cities = ['New York', 'London, Tokyo']  # or
# cities = myDb.("SELECT cities FROM world")

@app.route('/<string:var>')
def doSomething(var):
    if var in cities:
        return travel(var)
    elif var in food:
        return eat(var)
    elif var in actions:
        return perform(var)
    else:
        # prevent error
        return 'not found'

def travel(var):
    return 'travel to ' + var

def eat(var):
    return 'eat some ' + var

def perform(var):
    return 'have fun and ' + var

if __name__ == "__main__":
    app.run(debug=True)