by Rares Aioanei
IntroductionWhat 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.
PrerequisitesHere 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 pythonIf 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 haveThe instructions for the web server depend on what Python version you have default (e.g. 2 or 3). This is how you check :
$ python -VNotice the capitalized v, the non-capitalized option will start a Python console in verbose mode; use 'quit()' to exit
Python 2.xThe 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 9000This 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.xOnly 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