Dynamically generate Flask routes

前端 未结 3 1087
渐次进展
渐次进展 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

    This is how i got it to work @this-vidor and @PZP, the get page method is querying an sqlite db (but it could be any db), the generic function def is being looped over and in my actual code list of dictionaries is also being pulled from a db. So basically what I accomplished what I needed. The routes are dynamic. I can turn the routes on and off in the sql with out having to go to app.py to edit them.

    defaultPage = "/"
    
    @app.route(defaultPage)
    def index():
        page = getPage(defaultPage)
        return render_template("index.html", page=page)
    
    
    
    routes = [
        dict(route="/", func="index", page="index"),
        dict(route="/about", func="about", page="about")
    ]
    
    def generic():
        rule = request.url_rule
        page = getPage(rule)
        return render_template('index.html', page=page)
    
    for route in routes:
        app.add_url_rule(
            route["route"], #I believe this is the actual url
            route["page"] # this is the name used for url_for (from the docs)
        )
        app.view_functions[route["func"]] = generic`
    

提交回复
热议问题