答案:Python可通过http.server模块或socket实现静态Web服务器。使用http.server模块可在终端运行python -m http.server 8000快速启动服务;也可自定义类继承BaseHTTPRequestHandler处理GET请求,读取本地文件并返回响应,支持基本MIME类型判断,适用于开发调试,但生产环境应使用专业服务器。

Python实现静态Web服务器,核心是搭建一个能读取本地文件并响应HTTP请求的服务。最简单的方式是使用Python内置的http.server模块,也可以用socket手动实现,下面分两种方式说明。
步骤:
python -m http.server 8000
这会启动一个监听8000端口的服务器。浏览器访问https://www.php.cn/link/fcbb3a1c04ec11f1506563c26ca63774就能看到目录列表和文件内容。
立即学习“Python免费学习笔记(深入)”;
自定义端口或绑定地址:
python -m http.server 8080 --bind 127.0.0.1这样只在本机8080端口提供服务。
示例代码:
from http.server import HTTPServer, BaseHTTPRequestHandler
import os
class StaticServer(BaseHTTPRequestHandler):
def do_GET(self):
if self.path == '/':<br>
self.path = '/index.html'<br>
file_path = '.' + self.path
if os.path.exists(file_path) and os.path.isfile(file_path):<br>
self.send_response(200)<br>
# 根据文件类型设置Content-Type<br>
if file_path.endswith('.html'):<br>
self.send_header('Content-type', 'text/html')<br>
elif file_path.endswith('.css'):<br>
self.send_header('Content-type', 'text/css')<br>
elif file_path.endswith('.js'):<br>
self.send_header('Content-type', 'application/javascript')<br>
else:<br>
self.send_header('Content-type', 'application/octet-stream')<br>
self.end_headers()<br>
with open(file_path, 'rb') as f:
self.wfile.write(f.read())
else:
self.send_response(404)
self.send_header('Content-type', 'text/html')
self.end_headers()
self.wfile.write(b'404 Not Found')
if name == 'main':
server = HTTPServer(('localhost', 8000), StaticServer)
print("Serving at https://www.php.cn/link/fcbb3a1c04ec11f1506563c26ca63774")
server.serve_forever()
将上面代码保存为server.py,确保同目录有index.html等静态资源,运行后即可访问。
基本上就这些。用Python搭静态服务器不复杂,关键是理解HTTP响应流程和文件读取机制。
以上就是python静态web服务器如何实现的详细内容,更多请关注php中文网其它相关文章!
python怎么学习?python怎么入门?python在哪学?python怎么学才快?不用担心,这里为大家提供了python速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号