PHP转Python开发者:无框架用Python开发Web应用可行吗?
Absolutely! You absolutely can build web applications using pure Python, no frameworks needed. This is actually a fantastic approach for learning, since it forces you to understand the core mechanics of HTTP requests, responses, and how web servers handle communication—stuff that frameworks abstract away.
Let’s walk through a few simple examples using Python’s built-in http.server module, which lets you create basic web servers right out of the box.
1. Hello World Web Page
The simplest example is a server that returns a "Hello World" HTML page for every request:
from http.server import BaseHTTPRequestHandler, HTTPServer class HelloHandler(BaseHTTPRequestHandler): def do_GET(self): # Send response status code self.send_response(200) # Send headers self.send_header('Content-type', 'text/html') self.end_headers() # Send the response body self.wfile.write(b"<html><body><h1>Hello, World!</h1></body></html>") def run(server_class=HTTPServer, handler_class=HelloHandler, port=8000): server_address = ('', port) httpd = server_class(server_address, handler_class) print(f"Starting server on port {port}...") try: httpd.serve_forever() except KeyboardInterrupt: httpd.server_close() print("Server stopped.") if __name__ == '__main__': run()
Save this as hello_server.py, run it with python hello_server.py, then visit http://localhost:8000 in your browser. You’ll see your Hello World page!
2. Simple Counter (with in-memory state)
To build a counter that increments every time you visit the page, you’ll need to track state. Since we’re not using a database or framework, we can use a global variable (note: this will reset when you restart the server, which is fine for learning):
from http.server import BaseHTTPRequestHandler, HTTPServer # Global variable to track the count counter = 0 class CounterHandler(BaseHTTPRequestHandler): global counter def do_GET(self): global counter counter += 1 self.send_response(200) self.send_header('Content-type', 'text/html') self.end_headers() response = f"<html><body><h1>Count: {counter}</h1></body></html>" self.wfile.write(response.encode('utf-8')) def run(port=8000): server_address = ('', port) httpd = HTTPServer(server_address, CounterHandler) print(f"Starting counter server on port {port}...") try: httpd.serve_forever() except KeyboardInterrupt: httpd.server_close() print("Server stopped.") if __name__ == '__main__': run()
Each time you refresh http://localhost:8000, the count will go up by 1.
3. Basic JSON API
For a simple API that returns JSON data (e.g., a user object or status info), you can set the correct Content-type header and send JSON-encoded text:
from http.server import BaseHTTPRequestHandler, HTTPServer import json class APIHandler(BaseHTTPRequestHandler): def do_GET(self): # Check the path to serve different endpoints if self.path == '/api/user': user_data = { 'id': 1, 'name': 'Alice', 'email': 'alice@example.com' } self.send_response(200) self.send_header('Content-type', 'application/json') self.end_headers() # Convert dict to JSON string and encode to bytes self.wfile.write(json.dumps(user_data).encode('utf-8')) else: # Handle 404 for unknown paths self.send_response(404) self.send_header('Content-type', 'text/html') self.end_headers() self.wfile.write(b"<html><body><h1>404 Not Found</h1></body></html>") def run(port=8000): server_address = ('', port) httpd = HTTPServer(server_address, APIHandler) print(f"Starting API server on port {port}...") try: httpd.serve_forever() except KeyboardInterrupt: httpd.server_close() print("Server stopped.") if __name__ == '__main__': run()
Visit http://localhost:8000/api/user and you’ll get a JSON response. Try any other path, and you’ll get a 404 error.
A few notes to keep in mind:
- The
http.servermodule is meant for development and learning only—it’s not secure or efficient enough for production use. - As you scale beyond these simple examples, you’ll quickly realize why frameworks exist: handling routing, request parsing, sessions, databases, etc., manually gets tedious fast. But for learning the basics, this is perfect.
- You can also explore the
cgimodule if you want to handle form data, but that’s a bit more old-school.
So yes, pure Python is totally capable of building simple web pages and APIs—this is a great way to get a solid understanding of how web tech works before diving into frameworks.
内容的提问来源于stack exchange,提问作者Ali Marasizadeh

