[go: up one dir, main page]

Open In App

How to serve static files in Flask

Last Updated : 23 Jan, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Flask is a lightweight Web Server Gateway Interface or WSGI framework for web applications written in Python. It is designed to make web application development fast and easy and can scale to complex applications. This article describes and demonstrates how to serve various static files in Flask. 

Serving Static Files in Flask

Let’s configure the virtual environment first. Although this step is optional, we always recommend using a dedicated development environment for each project. This can be achieved in a Python virtual environment.

Now that we have created our Flask app, let’s see how to serve static files using the Flask app we just created. First, static files are files served by a web server and do not change over time like CSS and Javascript files used in web applications to improve user experience. Below you will find a demonstration of various static files served by the Flask app.

File Structure 

How to serve static files in Flask

 

HTML File

Serving HTML files using Flask is fairly simple just create a templates folder in the project root directory and create the HTML files, as templates/index.html. Here, we are passing text, and with the help of Jinja {{message}}, we are printing text that is present in the variable.

HTML




<html>
 <head>
   <title>Flask Static Demo</title>
 </head>
 <body>
   <h1>{{message}}</h1>
 </body>
</html>


main.py

In main.py we render the HTML file when we run it, we are using the render_template() function provided by Flask to render the HTML file. The final code looks like this:

Python3




from flask import Flask
from flask import render_template
  
# creates a Flask application
app = Flask(__name__)
  
  
@app.route("/")
def hello():
    message = "Hello, World"
    return render_template('index.html'
                           message=message)
  
# run the application
if __name__ == "__main__":
    app.run(debug=True)


Output:

The Flask is up and running on localhost port http://127.0.0.1:5000/

How to serve static files in Flask

 

Serve CSS file in Flask

Now serving a CSS file is the same as an HTML file but instead of /templates folder, we create a static folder in the root directory and add all CSS files to it, For simplicity, we have used a very simple CSS file.

CSS




h1{
    color: red;
    font-size: 36px;
}


Now, let us link it with the HTML template file using the link tag referring to the CSS file in the static folder.

HTML




<html>
  <head>
    <title>Flask Static Demo</title>
    <link rel="stylesheet" href="/static/style.css" />
  </head>
  <body>
    <h1>{{message}}</h1>
  </body>
</html>


Output:

How to serve static files in Flask

 

Serve JavaScript file in Flask

To serve Javascript it is the same as a CSS file create a javascript file in the static folder.

Javascript




document.write("This is a Javascript static file")


Now link it with the HTML and run the Flask app.

HTML




<html>
  <head>
    <title>Flask Static Demo</title>
    <link rel="stylesheet" href="/static/style.css" />
  </head>
  <body>
    <h1>{{message}}</h1>
  
    <script src="/static/serve.js" charset="utf-8"></script>
  </body>
</html>


Output:

How to serve static files in Flask

 

Serve Media files in Flask (Image, Video, Audio)

You can also use Flask to serve media files such as images, videos, audio files, text files, and PDFs. You can use the same /static folder that you used for CSS and Javascript to serve these kinds of files.

Place all media files in a static folder and associate them with their respective HTML files as shown below. Once all template files have been processed, create routes in main.py for all static files you want to render.

Images

Create an image.html file in the templates folder and add the following code to the main.py and image.html respectively.

Python3




# Images
@app.route("/image")
def serve_image():
    message = "Image Route"
    return render_template('image.html', message=message)


templates/images.html

HTML




<html>
  <head>
    <title>Flask Static Demo</title>
    <link rel="stylesheet" href="/static/style.css" />
  </head>
  <body>
    <h1>{{message}}</h1>
  
    <img src="/static/cat.jpg" alt="Cat image" width="20%" height="auto" />
  
    <script src="/static/serve.js" charset="utf-8"></script>
  </body>
</html>


Output:

How to serve static files in Flask

 

Video Files

To serve a video file, create a video.html file in your templates folder and add the following code to your main.py and video.html files.

Python3




# video
@app.route("/video")
def serve_video():
    message = "Video Route"
    return render_template('video.html', message=message)


templates/video.html

As you see the mp4 video file is been served by Flask over localhost.

HTML




<html>
  <head>
    <title>Flask Static Demo</title>
    <link rel="stylesheet" href="/static/style.css" />
  </head>
  <body>
    <h1>{{message}}</h1>
  
    <video width="320" height="240" controls>
      <source src="/static/ocean_video.mp4" type="video/mp4" />
    </video>
  
    <script src="/static/serve.js" charset="utf-8"></script>
  </body>
</html>


Output:

How to serve static files in Flask\

 

Audio Files

Respectively an audio file can be served by creating an audio.html template file and adding the following code to the main.py.

Python3




# audio
@app.route("/audio")
def serve_audio():
    message = "Audio Route"
    return render_template('audio.html', message=message)


templates/audio.html

HTML




<html>
  <head>
    <title>Flask Static Demo</title>
    <link rel="stylesheet" href="/static/style.css" />
  </head>
  <body>
    <h1>{{message}}</h1>
  
    <audio controls>
      <source src="/static/audio.mp3" />
    </audio>
  
    <script src="/static/serve.js" charset="utf-8"></script>
  </body>
</html>


Output:

How to serve static files in Flask

 

Complete Flask Code

For simplicity, we have created a simple Flask application for a better understanding of how to serve static files in Flask.

Python3




from flask import Flask
from flask import render_template
  
# creates a Flask application
app = Flask(__name__)
  
  
@app.route("/")
def hello():
    message = "Hello, World"
    return render_template('index.html', message=message)
  
  
@app.route("/video")
def serve_video():
    message = "Video Route"
    return render_template('video.html', message=message)
  
  
@app.route("/audio")
def serve_audio():
    message = "Audio Route"
    return render_template('audio.html', message=message)
  
  
@app.route("/image")
def serve_image():
    message = "Image Route"
    return render_template('image.html', message=message)
  
  
# run the application
if __name__ == "__main__":
    app.run(debug=True)


Let’s test the Flask app by running it, to run the app just run the python main.py which will serve output as shown above:

How to serve static files in Flask

 



Previous Article
Next Article

Similar Reads

Documenting Flask Endpoint using Flask-Autodoc
Documentation of endpoints is an essential task in web development and being able to apply it in different frameworks is always a utility. This article discusses how endpoints in Flask can be decorated to generate good documentation of them using the Flask-Autodoc module. This module provides the following features - Helps to document endpoints of
4 min read
How to use Flask-Session in Python Flask ?
Flask Session - Flask-Session is an extension for Flask that supports Server-side Session to your application.The Session is the time between the client logs in to the server and logs out of the server.The data that is required to be saved in the Session is stored in a temporary directory on the server.The data in the Session is stored on the top o
4 min read
How to Integrate Flask-Admin and Flask-Login
In order to merge the admin and login pages, we can utilize a short form or any other login method that only requires the username and password. This is known as integrating the admin page and Flask login since it simply redirects users to the admin page when they log in. Let's is how to implement this in this article. Integrate Flask Admin and Fla
8 min read
Minify HTML in Flask using Flask-Minify
Flask offers HTML rendering as output, it is usually desired that the output HTML should be concise and it serves the purpose as well. In this article, we would display minification of output routes of Flask responses using the library - Flask-Minify. Advantages of MinificationWebsites load faster as fewer lines are there to upload and download.Ban
12 min read
Flask URL Helper Function - Flask url_for()
In this article, we are going to learn about the flask url_for() function of the flask URL helper in Python. Flask is a straightforward, speedy, scalable library, used for building, compact web applications. It is a micro framework, that presents developers, useful tools, and, features, for coding REST APIs, and backend data processing, of web apps
11 min read
Upload Multiple files with Flask
In online apps, uploading files is a common task. Simple HTML forms with encryption set to multipart/form information are all that is required to publish a file into a URL when using Flask for file upload. The file is obtained from the request object by the server-side flask script using the request. In this article, we will look at how to upload m
2 min read
Uploading and Downloading Files in Flask
This article will go over how to upload and download files using a Flask database using Python. Basically, we have a section for uploading files where we can upload files that will automatically save in our database. When we upload a file and submit it, a message stating that your file has been uploaded and displaying the file name on the screen ap
7 min read
How to create PDF files in Flask
Whether it's generating a report, exporting data, or creating catalogs, Python and the Flask web framework provide powerful tools to accomplish this task. In this article, we'll explore how to generate both PDF files using Python and Flask. Creating PDF files in FlaskStep 1: InstallationWe are using Flask to create CSV output. Please refer:- Instal
4 min read
How to merge multiple excel files into a single files with Python ?
Normally, we're working with Excel files, and we surely have come across a scenario where we need to merge multiple Excel files into one. The traditional method has always been using a VBA code inside excel which does the job but is a multi-step process and is not so easy to understand. Another method is manually copying long Excel files into one w
4 min read
Upload and Read Excel File in Flask
In this article, we will look at how to read an Excel file in Flask. We will use the Python Pandas library to parse this excel data as HTML to make our job easier. Pandas additionally depend on openpyxl library to process Excel file formats. Before we begin, make sure that you have installed both Flask and Pandas libraries along with the openpyxl d
3 min read
Article Tags :
Practice Tags :