The Flask Static Folder
The static folder holds files the app serves as they are. CSS files and images live there.
Write a static file
This code writes hello.txt into the static folder.
import os
os.makedirs("static", exist_ok=True)
with open("static/hello.txt", "w") as f:
f.write("Hello from a static file")Make the app
This line makes the Flask app. The static folder sits beside this file.
from flask import Flask
app = Flask(__name__)Ask for the file
The test client asks for /static/hello.txt and prints the file content, unchanged.
client = app.test_client()
print(client.get("/static/hello.txt").data.decode())Example
import os
os.makedirs("static", exist_ok=True)
with open("static/hello.txt", "w") as f:
f.write("Hello from a static file")
from flask import Flask
app = Flask(__name__)
client = app.test_client()
print(client.get("/static/hello.txt").data.decode())Key points
- Static files live in a folder named static beside the app file.
- Flask serves them at /static/... addresses.
- The file content arrives unchanged.
- Keep pages in templates and files in static.
In this example, hello.txt is written into the static folder first. The app is then made. The test client asks for /static/hello.txt and prints the file content, unchanged.
Note
Flask serves static files only from the static folder.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
Where do static files live in a Flask app?