12

I'm trying to serve a static file using flask. I don't know how to use the url_for function. All my routes generating dynamic content are working fine, I've imported url_for, but when I have this code:

@app.route('/')
def home():
    return url_for('static', filename='hi.html')

Along with my 'hi.html' file (which has some basic html in it) sitting in directory static, what I get when I load the page is literally this:

/static/hi.html

Am I just using url_for incorrectly?

Brad Koch
  • 19,267
  • 19
  • 110
  • 137
user1276273
  • 1,963
  • 3
  • 16
  • 16

3 Answers3

21

url_for just returns, precisely, the URL for that file. It sounds like you want to redirect to the URL for that file. Instead, you are just sending the text of the URL to the client as a response.

from flask import url_for, redirect

@app.route('/')
def home():
    return redirect(url_for('static', filename='hi.html'))
Michael Greene
  • 10,343
  • 1
  • 41
  • 43
8

You are getting the correct output for what you are doing. url_for generates the url for the arguments you give it. In your case, you are generating the url for the hi.html file in the static directory. If you want to actually output the file, you would want to

from flask import render_template, url_for

...

    return render_template(url_for("static", filename="hi.html"))

But at this point, your static directory would need to be under the templates directory (where ever that is configured to live).

If you are going to be serving static html files like this, then my suggestion would be to serve them outside of the flask application by routing traffic to /static/.* directly from your web server. There are plenty of examples on the web for doing this using nginx or apache.

Derek Dowling
  • 479
  • 1
  • 4
  • 15
sberry
  • 128,281
  • 18
  • 138
  • 165
  • Thanks - I have every intention of serving them directly from my web server, just while I'm developing i want to be able to serve them using flask, and more than anything it was just driving me crazy. – user1276273 Apr 08 '13 at 16:35
0

Nowadays, files in /static/ are served automatically, and only referred to with url_for.
But there is send_from_directory - see this excellent answer: https://stackoverflow.com/a/20648053

handle
  • 5,859
  • 3
  • 54
  • 82