Serve static files through HTTP/(S) with Python 3

A simple guide to serving files over HTTP and HTTPS with Python 3 🐍

Nicolas Dommanget
2 min readJul 27, 2020
Unsplash: Timothy Dykes

Introduction

Recently, I had to create my own https server to build an Expo app (React Native) with turtle-cli on my own device.

Turtle-cli needed to access some files over https. One of the solutions was to make a simple HTTPS server to serve the current folder. Usually I would have done it with Node.js, but change doesn’t hurt.

Let’s see how to build our server with Python 3. You will need:

  • OpenSSL
  • Python3
  • And a computer 😎

Create an HTTP server

To start your server, you need to go inside the folder you want to serve and run this command:

python -m http.server 8000

This will spin up an HTTP server on the port 8000:

HTTP Server

As you can see, Python is serving the howl folder and it was very fast.😎

Need SSL?

We can also support SSL with our server. So, we will need to generate a certificate:

openssl req -x509 -newkey rsa:4096 -keyout key.pem -out cert.pem -days 365

You will be asked some questions:

Generate SSL certificate

You should get two files:

  • cert.pem
  • key.pem

We will use them to create and start our HTTPS server:

Once you have created your file in the directory, you can start it up:

python3 script.py

This will launch the server on the port 4443:

HTTPS Server

Your browser will warn you about security. It is normal, our certificate is valid…

But you can skip the warning and see your files into the browser. 😎

Now, you are able to create your own HTTP/HTTPS server and serve static files using python.

You can find my other articles and follow me here. Thanks for reading, I hope you learned something new today 🚀

--

--

Nicolas Dommanget

Software engineer @mailjet the day, side projects the night.