如何用Python搭建HTTP服务器托管文件及实现目录读取?
解决方案
一、托管JSON文件的HTTP服务器
用Python内置的http.server模块自定义请求处理器,既能托管静态JSON文件,也能返回目录结构:
import os from http.server import HTTPServer, SimpleHTTPRequestHandler import json class CustomHandler(SimpleHTTPRequestHandler): def do_GET(self): # 请求路径为/list时,返回目录文件列表 if self.path == '/list': self.send_response(200) self.send_header('Content-Type', 'application/json') self.end_headers() # 遍历当前目录,整理文件/文件夹信息 file_list = [] for entry in os.listdir('.'): item_type = 'file' if os.path.isfile(entry) else 'directory' file_list.append({'name': entry, 'type': item_type}) self.wfile.write(json.dumps(file_list).encode('utf-8')) return # 其他路径默认处理静态文件(包括JSON) super().do_GET() if __name__ == '__main__': server_address = ('', 8000) httpd = HTTPServer(server_address, CustomHandler) print(f"服务器运行在 http://localhost:8000") print("访问 /list 获取目录内容,直接访问文件名可查看JSON文件") httpd.serve_forever()
把需要托管的JSON文件放在脚本同目录下,运行后通过http://localhost:8000/你的文件名.json访问JSON内容,通过http://localhost:8000/list获取目录结构。
二、客户端请求程序
用requests库发送请求,读取服务器目录内容:
import requests import json def fetch_server_dir(server_url): try: # 请求目录列表 resp = requests.get(f"{server_url}/list") resp.raise_for_status() dir_content = resp.json() print("服务器目录内容:") for item in dir_content: print(f"- {item['name']} ({item['type']})") # 如需获取单个JSON文件内容,取消下面注释 # json_resp = requests.get(f"{server_url}/你的文件名.json") # print("\nJSON文件内容:") # print(json_resp.json()) except requests.exceptions.RequestException as e: print(f"请求失败:{e}") if __name__ == '__main__': fetch_server_dir("http://localhost:8000")
注意事项
- 运行客户端前先安装依赖:
pip install requests - 若服务器不在本地,把
localhost替换为服务器的实际IP地址 - 端口被占用时,修改服务器代码中的
8000为其他可用端口
内容的提问来源于stack exchange,提问作者Arm64
相关产品推荐
相关产品推荐

