Linking Flask Static Files
url_for builds the address of a static file. The static name points at the static folder.
Write a CSS file
This code writes style.css into the static folder.
import os
os.makedirs("static", exist_ok=True)
with open("static/style.css", "w") as f:
f.write("h1 { color: blue; }")Build the static link
The view calls url_for with static and the file name. It returns the built address as text.
from flask import Flask, url_for
app = Flask(__name__)
@app.route("/links")
def links():
return "CSS: " + url_for("static", filename="style.css")Ask for the link
The test client asks for /links and prints the built address.
client = app.test_client()
print(client.get("/links").data.decode())Example
import os
os.makedirs("static", exist_ok=True)
with open("static/style.css", "w") as f:
f.write("h1 { color: blue; }")
from flask import Flask, url_for
app = Flask(__name__)
@app.route("/links")
def links():
return "CSS: " + url_for("static", filename="style.css")
client = app.test_client()
print(client.get("/links").data.decode())Key points
- url_for("static", filename="style.css") builds the address.
- The address starts with /static/.
- Build static links with url_for, never by hand.
- The filename is the path inside the static folder.
In this example, style.css is written into the static folder first. The view builds the file address with url_for("static", filename="style.css"). The test client asks for /links and prints the built address.
Note
The first argument is the word static, not a route name.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does url_for("static", filename="style.css") return?