Flask / Flask File Uploads and Media Handling

Serving Static and Media Files

This tutorial will teach you how to serve static and media files in a Flask application.

Tutorial 3 of 5 5 resources in this section

Section overview

5 resources

Explains how to handle file uploads and manage media files in Flask.

1. Introduction

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.

2. Step-by-Step Guide

2.1 Setting up a Flask Application

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)

2.2 Serving Static Files

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') }}">

2.3 Serving Media Files

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.

3. Code Examples

3.1 Example: Serving a CSS File

  1. Create a static/css directory in your application root.
  2. Create a file main.css inside the css directory.
  3. Link to the CSS file in your HTML:
<!-- The `url_for` function generates the URL for the static file -->
<link rel="stylesheet" href="{{ url_for('static', filename='css/main.css') }}">

3.2 Example: Serving a Video File

  1. Create a static/media directory in your application root.
  2. Put a video file video.mp4 inside the media directory.
  3. Link to the video file in your HTML:
<!-- The `url_for` function generates the URL for the video file -->
<video src="{{ url_for('static', filename='media/video.mp4') }}" controls></video>

4. Summary

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.

5. Practice Exercises

  1. Create a Flask application that serves an HTML page with a CSS and a JS file.
  2. Extend the above application to include an image and a video file.
  3. Try serving the static files from a different directory (not the static directory).

Remember, the best way to learn is by doing. Happy coding!

Solutions:

  1. Create a new Flask application and add a route that returns an HTML template. Create a static directory and put your CSS and JS files there. Link to these files in your HTML template using the url_for function.
  2. Put your image and video files in the static directory and link to them in your HTML template using the url_for function.
  3. You can change the static files directory by providing the 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!

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

Text Diff Checker

Compare two pieces of text to find differences.

Use tool

File Size Checker

Check the size of uploaded files.

Use tool

Timestamp Converter

Convert timestamps to human-readable dates.

Use tool

Random String Generator

Generate random alphanumeric strings for API keys or unique IDs.

Use tool

Meta Tag Analyzer

Analyze and generate meta tags for SEO.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help