In this tutorial, we will be discussing how to serve static and media files in a Flask application. Static files are files that clients download as they are from the server (like CSS, JavaScript, images). Media files are also static but usually refer to larger files like audio and video.
What you will learn:
- Setting up a Flask application
- Serving static files in Flask
- Serving media files in Flask
Prerequisites:
Basic understanding of Python and Flask is required. If you're new to Flask, you might want to check out this Beginner's guide to Flask.
Before we begin, we need to set up a basic Flask application. Flask is a micro web framework written in Python. It's designed to make getting started quick and easy, with the ability to scale up to complex applications.
Here's a simple Flask application:
from flask import Flask
app = Flask(__name__)
@app.route('/')
def home():
return "Hello, World!"
if __name__ == '__main__':
app.run(debug=True)
In Flask, static files are served from a folder called static
in your application root directory. It can contain subdirectories to better organize your files (like css
, js
, img
).
To link a static file in your HTML, you can use the url_for
function. Here's an example of linking a CSS file:
<link rel="stylesheet" href="{{ url_for('static', filename='css/main.css') }}">
For serving larger static files like videos and audios, it's better to use a CDN or a different server optimized for serving static files. If you still want to serve them from your Flask server, place them in the static
folder and link to them just like any other static file.
static/css
directory in your application root.main.css
inside the css
directory.<!-- The `url_for` function generates the URL for the static file -->
<link rel="stylesheet" href="{{ url_for('static', filename='css/main.css') }}">
static/media
directory in your application root.video.mp4
inside the media
directory.<!-- The `url_for` function generates the URL for the video file -->
<video src="{{ url_for('static', filename='media/video.mp4') }}" controls></video>
In this tutorial, we learned how to serve static and media files in a Flask application. We discussed how to set up a Flask application, how to serve static files like CSS and JS, and how to serve larger media files like audio and video.
For further learning, you can explore the Flask Documentation.
static
directory).Remember, the best way to learn is by doing. Happy coding!
static
directory and put your CSS and JS files there. Link to these files in your HTML template using the url_for
function.static
directory and link to them in your HTML template using the url_for
function.static_folder
parameter when creating your Flask app: app = Flask(__name__, static_folder='my_static')
.Tip: Always try to understand the code you're writing, and don't be afraid to experiment and make mistakes. That's the best way to learn!