Flask 101: Serve Images

Welcome to part 4 of the the Flask 101 Series. 


  1. Flask 101: Create a Basic Python Web App
  2. Flask 101: Add JSON to your Python Web App
  3. Flask 101: Use HTML templates & send variables 
  4. Flask 101: Serve Images – This tutorial
  5. Flask 101: Serve CSV Files

For this tutorial, we will create a random image generator.

Also the full code for this project is available on my GitHub repo.


1 – Setup

If you want to use a Python 3 virtual environment, you can follow this post for example. But all you really need is to install Flask

# Install flask
pip install flask

Create the following directory and files, leave them empty for now. We fill fill them later.


As in part 3, you will need some images to serve. For simplicity you can just download the ones on my GitHub repo here.


2 – Create your flask application

So far your directory structure should look like this

   .. more images ... 


Now open the file named myapp.py that you have created above, and add the content below. We are basically doing 3 things there:

  1. def random_image()
    this one is in charge for returning one of the images inside your static/ directory at random
  2. @app.route(‘/’)
    this is the main – and only – route of this app. It takes a random image and serves it through the send_file() method.


from flask import Flask, send_file
import os
import random

app = Flask(__name__)

def random_image():
    Return a random image from the ones in the static/ directory
    img_dir = "./static"
    img_list = os.listdir(img_dir)
    img_path = os.path.join(img_dir, random.choice(img_list))
    return img_path

def myapp():
    Returns a random image directly through send_file
    image = random_image()
    return send_file(image, mimetype='image/png')


3 – Run your app

In the same directory as myapp.py, create a file named runapp.sh with the following contents.

export FLASK_APP=myapp
export FLASK_ENV=development
flask run

Close the file, then in the command line, run it with

# Execute this in the command line inside the same directory 
bash runapp.sh

You should see the following output

* Serving Flask app "myapp" (lazy loading)
* Environment: development
* Debug mode: on
* Running on (Press CTRL+C to quit)
* Restarting with stat
* Debugger is active!
* Debugger PIN: 319-407-766


5 – Test your app