Start a web service with a single line of code, making debugging, testing, and lightweight application development smoother!
๐ Why Learn <span>http.server</span>?
<span>http.server</span> is a built-in HTTP service module in the Python standard library, with advantages including:
- ๐ No dependencies: No need to install any third-party packages
- โก Quick startup: Can be run with a single command
- ๐ Convenient for debugging: The easiest way to test interfaces and frontend pages locally
- ๐ Embedded in projects: Quickly build lightweight web services or APIs
๐โ๏ธ Start a Web Service with One Line of Code
# Start a web service in the current directory on port 8000
python -m http.server 8000
๐ Open your browser and visit:
http://127.0.0.1:8000
This will output the directory file structure, and files can be clicked to download directly.
๐ Custom Server: Python Code Version
We can customize the behavior of <span>http.server</span> by writing a Python script.
Example 1: The Simplest HTTP File Service
from http.server import SimpleHTTPRequestHandler, HTTPServer
PORT = 8000
# Use the default file request handler
handler = SimpleHTTPRequestHandler
# Create server object
httpd = HTTPServer(("0.0.0.0", PORT), handler)
print(f"๐ Server started: http://127.0.0.1:{PORT}")
httpd.serve_forever()
Effect:
- Open your browser and visit
<span>http://127.0.0.1:8000</span> - See all files in the current directory
- Files can be clicked to download directly
๐งฉ Practical Example 1: Create a Simple API Service
Want to quickly write a local API? You can do it too.
from http.server import BaseHTTPRequestHandler, HTTPServer
import json
class MyHandler(BaseHTTPRequestHandler):
# Handle GET requests
def do_GET(self):
if self.path == "/ping":
self.send_response(200)
self.send_header("Content-Type", "application/json")
self.end_headers()
self.wfile.write(json.dumps({"msg": "pong"}).encode())
else:
self.send_response(404)
self.end_headers()
self.wfile.write(b"Not Found")
# Handle POST requests
def do_POST(self):
if self.path == "/echo":
length = int(self.headers.get('Content-Length', 0))
body = self.rfile.read(length)
self.send_response(200)
self.send_header("Content-Type", "application/json")
self.end_headers()
self.wfile.write(json.dumps({"echo": body.decode()}).encode())
def run(server_class=HTTPServer, handler_class=MyHandler):
server_address = ("0.0.0.0", 8000)
httpd = server_class(server_address, handler_class)
print("๐ API Server started on http://127.0.0.1:8000")
httpd.serve_forever()
if __name__ == "__main__":
run()
Testing Effects
GET Request
curl http://127.0.0.1:8000/ping
Output:
{"msg": "pong"}
POST Request
curl -X POST -d "Hello World" http://127.0.0.1:8000/echo
Output:
{"echo": "Hello World"}
๐งช Practical Example 2: Temporary File Sharing Service
Want to quickly share a folder with colleagues?
-
Execute in the shared directory:
python -m http.server 9000 -
Let colleagues access via browser:
http://<your IP>:9000 -
Click files to download directly.
๐ Security Considerations
<span>http.server</span>is only suitable for local development and temporary debugging, do not expose it directly to the public network!
Reasons:
- No authentication
- No HTTPS
- No protective measures
If deploying in a production environment, please choose:
- Flask / FastAPI
- Django
- or mature web servers like Nginx, Apache
๐ง Summary
| Scenario | Usage |
|---|---|
| Quickly start a debugging service | <span>python -m http.server</span> |
| File sharing | Quick transfer over local network |
| Prototype API testing | Customize <span>BaseHTTPRequestHandler</span> |
| Learn HTTP protocol | Study request/response headers, status codes |