Pass in a list of possible routes to Flask?

2024/10/14 19:28:26

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?

Answer

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 Flaskapp = 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 Flaskapp = Flask(__name__)options = ['option1', 'option2']@app.route("/<any({}):segment>".format(str(options)[1:-1]))
def hello(segment):return "Hello {}!".format(segment)app.run()
https://en.xdnf.cn/q/69376.html

Related Q&A

Tornado @run_on_executor is blocking

I would like to ask how tornado.concurrent.run_on_executor (later just run_on_executor) works, because I probably do not understand how to run synchronous task to not block the main IOLoop.All the exa…

Using Pandas read_csv() on an open file twice

As I was experimenting with pandas, I noticed some odd behavior of pandas.read_csv and was wondering if someone with more experience could explain what might be causing it.To start, here is my basic cl…

Disable Jedi linting for Python in Visual Studio Code

I have set my linter for Python to Pylint, but I still get error messages from Jedi. I even went to settings.json and added the line "python.linting.jediEnabled": false, but the line, though …

Bar plot with timedelta as bar width

I have a pandas dataframe with a column containing timestamps (start) and another column containing timedeltas (duration) to indicate duration.Im trying to plot a bar chart showing these durations with…

Take screenshot of second monitor with python on OSX

I am trying to make an ambient light system with Python. I have gotten pyscreenshot to save a screenshot correctly, but I cant figure out how to get it to screenshot my second monitor (if this is even …

Invoking the __call__ method of a superclass

http://code.google.com/p/python-hidden-markov/source/browse/trunk/Markov.pyContains a class HMM, which inherits from BayesianModel, which is a new-style class. Each has a __call__ method. HMMs __call__…

Efficent way to split a large text file in python [duplicate]

This question already has answers here:Sorting text file by using Python(3 answers)Closed 10 years ago.this is a previous question where to improve the time performance of a function in python i need t…

Creating a unique id in a python dataclass

I need a unique (unsigned int) id for my python data class. This is very similar to this so post, but without explicit ctors. import attr from attrs import field from itertools import count @attr.s(aut…

How to get all the models (one for each set of parameters) using GridSearchCV?

From my understanding: best_estimator_ provides the estimator with highest score; best_score_ provides the score of the selected estimator; cv_results_ may be exploited to get the scores of all estimat…

How do I perform deep equality comparisons of two lists of tuples?

I want to compare two lists of tuples:larry = [(1,a), (2, b)] moe = [(2, b), (1, a)]such that the order of the items in the list may differ. Are there library functions to do this ?>> deep_equal…