Python's http.server Module
This article introduces Python's http.server module for creating HTTP servers and http.cookies module for managing cookies, providing practical examples for web development tasks.
It introduces Python's http.server module for creating HTTP servers and http.cookies module for managing cookies, providing practical examples for web development tasks.
The article covers creating a simple HTTP server, specifying IP addresses, customizing handlers, using different ports, and implementing HTTPS. It also demonstrates creating and parsing cookies, adding cookies to requests, and setting expiration times.
Code examples include:
import http.server
import socketserver
PORT = 8000
class MyHandler(http.server.SimpleHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.send_header("Content-type", "text/html")
self.end_headers()
self.wfile.write(b"Hello, World!")
with socketserver.TCPServer(("", PORT), MyHandler) as httpd:
print("Server started at port", PORT)
httpd.serve_forever()Another example shows creating a custom handler for different paths:
import http.server
import socketserver
class MyHandler(http.server.BaseHTTPRequestHandler):
def do_GET(self):
if self.path == "/":
self.send_response(200)
self.send_header("Content-type", "text/html")
self.end_headers()
self.wfile.write(b"<h1>Welcome to My Server!</h1>")
elif self.path == "/about":
self.send_response(200)
self.send_header("Content-type", "text/html")
self.end_headers()
self.wfile.write(b"<h2>About Us</h2>")
else:
self.send_response(404)
self.send_header("Content-type", "text/html")
self.end_headers()
self.wfile.write(b"<h3>Page Not Found</h3>")
with socketserver.TCPServer(("", PORT), MyHandler) as httpd:
print("Server started at port", PORT)
httpd.serve_forever()The article also includes examples for HTTPS, cookie management, and saving/loading cookies, with code snippets preserved as shown.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
