简体   繁体   中英

How can I pass a dict key to a decorator value within flask?

I'm trying to get my app.route decorator to accept a dictionary key as an argument instead of writing out each function separately.

from flask import Flask, render_template


app = Flask(__name__)

pages_dict = {"/url": "html_file.html", "/", "index.html"}


for k, v in pages_dict.items():

    @app.route(key)
    def render():
        return render_template(v)

You used a , comma where you should have used a : colon:

pages_dict = {"url": "html_file", "/", "index.html"}
                                     ^

This is easily corrected to:

pages_dict = {"url": "html_file", "/": "index.html"}

The @app.route() decorator registers endpoints , each of which have to have a unique name. By default the endpoint name is taken from the function, so if you are reusing a function you need to provide a name explicitly:

for k, v in pages_dict.items():
    @app.route(k, endpoint=k)
    def render():
        return render_template(v)

You'll still run into issues with closures here; the v used in render() is going to be bound to the last value from the loops. You probably want to pass it in as an argument to render() instead:

for k, v in pages_dict.items():
    @app.route(k, endpoint=k)
    def render(v=v):
        return render_template(v)

This binds v as a local in render() rather than leave it a closure. See Local variables in Python nested functions for more details.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM