0

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)
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • The too-many-values is one you could easily have debugged yourself.. Then again, so was the typo in the dictionary. – Martijn Pieters Nov 19 '15 at 11:02
  • But to cut a long story short: Stack Overflow is not an interactive debugger. Please stick to one issue per post, don't keep updating it with new issues as they arise. – Martijn Pieters Nov 19 '15 at 11:03
  • Thanks for your help and yeah I'm sorry about that, I should of got those errors. –  Nov 19 '15 at 11:19

1 Answers1

1

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.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • I've also tried this with iteritems but it still can't connect on localhost:5000 but I get no errors when I run the script, I'll keep trying, thanks for the help. –  Nov 19 '15 at 11:20
  • @EvanBlack: your example script has no `app.run()` call or a WSGI setup. Are you sure you started the builtin development server (`app.run()`) or have another WSGI setup? – Martijn Pieters Nov 19 '15 at 11:21
  • I've messed about with it a bit but I can only get it to display one out of the two html pages, i'm going to try creating a function to create functions instead. –  Nov 19 '15 at 14:47
  • @EvanBlack: ah, yes, you'll run into issues with closures. Updated the answer to account for that. – Martijn Pieters Nov 19 '15 at 14:50