使用Python内置http.server模块可快速搭建Web服务器,通过python -m http.server启动,默认端口8000,可指定端口如8080;通过自定义BaseHTTPRequestHandler处理GET、POST请求,支持返回HTML内容或静态文件;可添加异常处理返回404或500页面,并通过检查client_address实现IP访问限制,结合nohup命令可在后台运行服务。

搭建一个简单的Python Web服务器,核心在于利用Python内置的
http.server
解决方案:
最简启动: 打开终端,导航到你希望作为Web服务器根目录的文件夹。然后输入
python -m http.server
http://localhost:8000
指定端口: 如果8000端口被占用或者你想用其他端口,可以使用
python -m http.server 8080
立即学习“Python免费学习笔记(深入)”;
自定义处理器: 如果你需要更高级的功能,比如处理POST请求或者自定义响应,就需要编写一个自定义的HTTP请求处理器类。这个类需要继承自
http.server.BaseHTTPRequestHandler
do_GET
do_POST
处理GET请求示例:
import http.server
import socketserver
class MyHandler(http.server.BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
message = "<html><body><h1>Hello, World!</h1></body></html>"
self.wfile.write(bytes(message, "utf8"))
PORT = 8000
Handler = MyHandler
with socketserver.TCPServer(("", PORT), Handler) as httpd:
print("serving at port", PORT)
httpd.serve_forever()这段代码创建了一个简单的服务器,当收到GET请求时,会返回一个包含 "Hello, World!" 的HTML页面。
处理POST请求: 处理POST请求稍微复杂一些,你需要读取请求体,解析数据,然后生成响应。
选择端口号其实没什么特别的规则,只要确保它没有被其他程序占用就行。通常,大于1024的端口号是比较安全的,因为小于1024的端口号通常需要root权限才能使用。你可以使用
netstat -an
netstat -ano
在Linux/macOS下,你可以使用
nohup
nohup python -m http.server 8080 &
&
nohup
nohup.out
http.server
index.html
http://localhost:8000/index.html
http://localhost:8000/
index.html
index.html
在自定义的请求处理器类中,你可以通过捕获异常来处理错误。例如,如果用户请求的文件不存在,你可以返回一个404错误页面。
import http.server
import socketserver
import os
class MyHandler(http.server.BaseHTTPRequestHandler):
def do_GET(self):
try:
filepath = self.path[1:] # Remove leading '/'
if filepath == "":
filepath = "index.html" # Default file
with open(filepath, 'rb') as f:
content = f.read()
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
self.wfile.write(content)
except FileNotFoundError:
self.send_response(404)
self.send_header('Content-type', 'text/html')
self.end_headers()
self.wfile.write(bytes("<html><body><h1>404 Not Found</h1></body></html>", "utf8"))
except Exception as e:
self.send_response(500)
self.send_header('Content-type', 'text/html')
self.end_headers()
self.wfile.write(bytes(f"<html><body><h1>500 Internal Server Error</h1><p>{e}</p></body></html>", "utf8"))
PORT = 8000
Handler = MyHandler
with socketserver.TCPServer(("", PORT), Handler) as httpd:
print("serving at port", PORT)
httpd.serve_forever()
这个例子中,如果文件不存在,服务器会返回一个404错误页面;如果发生其他错误,会返回一个500错误页面。
http.server
import http.server
import socketserver
ALLOWED_IPS = ['127.0.0.1', '::1'] # 允许的IP地址列表
class MyHandler(http.server.BaseHTTPRequestHandler):
def do_GET(self):
client_ip = self.client_address[0]
if client_ip not in ALLOWED_IPS:
self.send_response(403) # Forbidden
self.send_header('Content-type', 'text/html')
self.end_headers()
self.wfile.write(bytes("<html><body><h1>403 Forbidden</h1></body></html>", "utf8"))
return
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
message = "<html><body><h1>Hello, World!</h1></body></html>"
self.wfile.write(bytes(message, "utf8"))
PORT = 8000
Handler = MyHandler
with socketserver.TCPServer(("", PORT), Handler) as httpd:
print("serving at port", PORT)
httpd.serve_forever()这个例子中,只有来自
127.0.0.1
::1
以上就是python怎么实现一个简单的Web服务器_python搭建简易Web服务器教程的详细内容,更多请关注php中文网其它相关文章!
python怎么学习?python怎么入门?python在哪学?python怎么学才快?不用担心,这里为大家提供了python速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号