Running a simple HTTP web server with one terminal command and python

May 10, 2016
by Rares Aioanei

Introduction

What we want to show you in this tip article is how to run a very simple and lightweight web server using only Python as a prerequisite. Use cases can be very
different, depending on your needs : you might need web server functionality in your code (e.g. a microservice), you might want to have a browser-based file manager (you will
soon see what we mean by that) or you just want to test your web page and/or start learning web development and Apache is a bit much for the task.

Prerequisites

Here we can only say “Linux” because, unless you have a very minimal setup, you already have Python installed. This is a guarantee for yum-based distributions
as yum is written in Python. If you don’t have Python installed, on Debian-based distributions you can do

$ sudo apt-get install python

If you’re on RHEL-based distributions and don’t already have Python, just type

$ sudo rpm -ivh $python_rpm_package #you won't be able to run dnf/yum without Python, as stated above

Checking the Python version you have

The instructions for the web server depend on what Python version you have default (e.g. 2 or 3). This is how you check :

 $ python -V 

Notice the capitalized v, the non-capitalized option will start a Python console in verbose mode; use ‘quit()’ to exit

Python 2.x

The Python module we’re gonna use here is SimpleHTTPServer. By default it starts listening on port 8000, but you can add an argument to specify the port:

$ python -m SimpleHTTPServer 9000

This will start a web server on port 9000, and you can test the success of the operation by accessing localhost:$port (9000 in our case). Another use for this is the fact that
you can now access the machine with the web server from anywhere in your LAN (depending on security policies though, mind you) which might prove useful if you want to download
files from the desktop to the laptop, for example.

Python 3.x

Only the name of the module is different here, because the functionality of SimpleHTTPServer is merged into the Python 3 module, called http.server. So with
Python 3, the command becomes

$ python -m http.server 9000

Final words

You will notice that we ran the commands as normal user. Why do we need to do something different if we want the web server to run on port 80 is left as an
exercise to the reader. If you find creative ways or interesting options to use with the concepts above, we’d like to hear them, so write a comment and let us know.



Comments and Discussions
Linux Forum