Introduction to http.server
Hello everyone, today we will introduce the http.server module from Python's standard library. This module provides a simple way to quickly start an HTTP server, making it very suitable for lightweight scenarios such as temporary file sharing, testing, and teaching.
Function Demonstration
Take the Windows system as an example: you can either navigate to the folder to be shared for download in a cmd window, or navigate to the target directory in File Explorer of the graphical interface, type cmd and press Enter to open a command line window
When starting the http.server module from the command line, usage differs slightly between Python 2 and Python 3. In Python 3, the SimpleHTTPServer module has been merged into the http.server module:
# python2
python -m SimpleHTTPServer [port]
# python3
python -m http.server [port]
This will start an HTTP server in the current directory, listening on the specified port (port 8000 by default).
Specify the listening port:
python -m SimpleHTTPServer 7800 # Python 2
python -m http.server 7800 # Python 3
Specify the http.server directory
If you want to set the root directory of the HTTP server, you can use the --directory/-d option:
python -m http.server --directory /path/to/dir [port] # Python 3
The above command will set /path/to/dir as the root directory of the HTTP server.
Summary
The Python http.server module provides a simple way to quickly create an HTTP server, and it is especially convenient to start an HTTP server with a single line command. My most common use case is sharing files on an office network (especially large files), but remember to configure the appropriate firewall rules or disable your firewall.
That concludes this introduction to the Python http.server module, and I hope it is helpful to you. If you have any questions, please feel free to leave a comment to discuss, or follow my WeChat Official Account: Yunwei Xiaozhu (运维小猪), thank you!
This is a discussion topic separated from the original thread at https://juejin.cn/post/7369054503084376102



