Dynamically generate Flask routes

前端 未结 3 1082
渐次进展
渐次进展 2021-01-05 10:50

I am trying to dynamically generate routes in Flask from a list. I want to dynamically generate view functions and endpoints and add them with add_url_rule.

3条回答
  •  庸人自扰
    2021-01-05 11:38

    Not too familiar with Flask, so it is possible that there is a cleaner way to do this. (If someone who is knowledgeable about Flask thinks that my method is inherently wrong, I'll gladly delete my answer if they explain why in a comment.) Now that I got that disclaimer out of the way, here are my thoughts:

    app.route("/") is a decorator function. The @ notation is just syntactic sugar for something like index = app.route("/")(index). Therefore, you should be able to do something like this...

    routes = [
        ("/", index),
        ("/about", about)
    ]
    for route, view_func in routes:
        view_func = app.route(route)(view_func)
    

    which would allow you to create the Flask routes from dynamically created routes and functions.

提交回复
热议问题