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

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 🚀

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store