Start A HTTP Server In Python
If you have been reading my articles for some time, you would know my love for the Python language. I use it extensively in my own day to day tasks whenever possible. And it all started on the day I have discovered how simple it is to start an HTTP server in python. After reading this, I hope I can convert at least some of you into learning and using python more.
Starting a server
With Python, you can start a simple web server with just one command. ONE COMMAND! That’s all it takes. You run:
python -m http.server
And this will start the server on port 8000 by default.
$ python -m http.server
Serving HTTP on 0.0.0.0 port 8000 (http://0.0.0.0:8000/) ...
And now if you open http://localhost:8000, you’ll see that the server is started and it is serving the pages in your current directory
If you’re on python 2.x series, first of all, you should switch to 3.x. You’re missing a lot of new stuff. But, If you really want to do this on a 2.x python version, then
python -m SimpleHTTPServer
And this will start a server.
Changing the Server port
By default, the server starts on port
8000. If you want to start it on a different port, pass that as the last argument in the server command.
If you want to start a server on port
10001, you'll run
python -m http.server 10001
And this will start the server on the new port.
$ python -m http.server 10001
Serving HTTP on 0.0.0.0 port 10001 (http://0.0.0.0:10001/) ...
Other than just as a testing server, you can use this to start a content hosting server in your own network. Let’s say you have a file on your computer, that you want to transfer from your computer to your phone, you can use this.
Say the files you want to share are in
$ cd users/hello
$ python -m http.server 8080
Serving HTTP on 0.0.0.0 port 8080 (http://0.0.0.0:8080/) ...
And now on your phone, you can go to
http://<your-computer-ip>:8080 and you can see all the files in it. You can then just click on them and download. You don't really need any sharing programs. You can just do this and transfer your files to other devices easily, with just a click of a button. That's Python for you!
That is all for this article.
This is the 18th article as part of my twitter challenge #30DaysOfBlogging. Twelve more articles on various topics, including but not limited to, Java, Git, Vim, Software Development, Python, to come.
If you are interested in contributing to any open source projects and haven’t found the right project or if you were unsure on how to begin, I would like to suggest my own project, Delorean which is a Distributed Version control system, built from scratch in scala. You can contribute not only in the form of code, but also with usage documentation and also by identifying any bugs in its functionality.
Thanks for reading. See you again in the next article.