Home > Software design >  Create Flask endpoint using a Loop
Create Flask endpoint using a Loop

Time:10-16

I want to create multiple Flask endpoints I read from my Config. Is it possible to make a for or while loop to create them? The Endpoints Address would be variable, but there would be no limit on how many I would need.

My Idea was:

for x in myList: 
   @app.route(var, ...)
   def route():
      do smt ...

Thanks for your help

CodePudding user response:

You can use

app.add_url_rule(rule, endpoint=None, view_func=None, provide_automatic_options=None, **options)

to achieve this. For example:

for endpoint in endpoint_list:
    app.add_url_rule(endpoint['route'], view_func=endpoint['view_func'])

Check out the docs.

Note that the endpoint_list contains records of endpoints. It should be a list of dictionaries, for example:

endpoint_list = [
    {
        "route": "/",
        "view_func": index
    },
    .....
]

Avoid using "list" as the variable name. It would override Python's default list function.

  • Related