Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass in a list of possible routes to Flask?

I'm learning Flask and have a question about dynamic routing: is it possible to pass in a list of accepted routes? I noticed the any converter which has potential but had a hard time finding examples of it in use. Basically I have different groups of endpoints that should trigger the same action amongst them. Here's what I mean:

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

I could do something like

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

But is there any way I can do something like this?

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

Additionally, I want these lists to be dynamic. So what I really want is something like:

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

Is there any way to achieve this, or am I stuck blocking everything up in one dynamic route?

like image 769
ShaneOH Avatar asked Mar 25 '17 05:03

ShaneOH


People also ask

How do I pass a Flask URL to list?

getlist to get a list of values for a key, rather than a single value. You can pass type=int to make sure all the values are ints. Show activity on this post. Write a custom url converter that accepts a list of ints separated by a delimiter, rather than just one int.


Video Answer


1 Answers

Flask is based on Werkzeug and it has the AnyConverter to do that.

Basically it allows you to declare a Werkzeug rule like this:

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

So basically for flask it translates into:

from flask import Flask

app = Flask(__name__)


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

app.run()

Or if you want those list to be dynamically generated when the app starts:

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()
like image 163
Timothée Jeannin Avatar answered Oct 06 '22 18:10

Timothée Jeannin