如何用Python异步HTTP服务器接收Postman的JSON数据创建文件
问题解决:基于aiohttp实现POST请求创建JSON文件
以下是修正后的完整代码,可实现接收Postman发送的JSON数据并生成对应文件:
完整代码
from aiohttp import web import os import json # GET请求:获取指定目录文件列表 async def handle(request): path = "C://Users/berto/Desktop/MEGSI - ESI 1/ITI/Servidor/Ficheiros" dir_list = os.listdir(path) return web.Response(text=json.dumps(dir_list, ensure_ascii=False)) # POST请求:接收JSON数据并创建文件 async def handler(request): def write_to_json_file(path, file_name, data): # 用os.path.join拼接路径,避免跨平台分隔符问题 file_path = os.path.join(path, f"{file_name}.json") # 'w'模式用于创建/覆盖文件,若需追加可改为'a' with open(file_path, 'w', encoding='utf-8') as fp: json.dump(data, fp, ensure_ascii=False, indent=4) try: # 异步读取Postman发送的JSON请求体 request_data = await request.json() # 从请求数据中提取文件名和内容(字段名可按需调整) file_name = request_data.get("fileName") content = request_data.get("data") if not file_name or content is None: return web.json_response( {"status": "error", "message": "缺少fileName或data字段"}, status=400 ) save_path = "C:/Users/berto/Desktop/MEGSI - ESI 1/ITI/Servidor/Ficheiros" write_to_json_file(save_path, file_name, content) return web.json_response({"status": "success", "message": "文件创建成功"}) except json.JSONDecodeError: return web.json_response( {"status": "error", "message": "请求体不是合法JSON格式"}, status=400 ) except Exception as e: return web.json_response( {"status": "error", "message": str(e)}, status=500 ) app = web.Application() app.add_routes([ web.get('/', handle), web.post('/', handler) ]) if __name__ == '__main__': web.run_app(app)
关键改进说明
- 请求数据读取:通过
await request.json()异步获取Postman发送的JSON内容,这是aiohttp处理POST JSON请求的标准方式 - 路径优化:用
os.path.join拼接文件路径,避免手动拼接导致的分隔符错误(适配不同操作系统) - 文件写入修正:
- 移除错误的
fp.write(data):json.dump已完成数据序列化写入,重复写入会导致文件内容错乱 - 添加
ensure_ascii=False和indent=4,让生成的JSON支持中文且格式美观 - 使用
'w'模式创建新文件(若文件已存在则覆盖,需追加可改回'a')
- 移除错误的
- 错误处理:捕获JSON解析失败、字段缺失、未知异常等场景,返回明确的错误响应
- 响应规范:统一返回JSON格式响应,方便Postman或前端判断请求结果
Postman测试方法
- 选择POST请求,URL填
http://localhost:8080/(默认端口,若修改需对应) - 切换到
Body选项卡,选择raw格式并设置为JSON - 输入示例JSON(可按需修改):
{ "fileName": "python_book", "data": { "title": "异步HTTP服务器实战", "author": "test", "pages": 200 } }
- 发送请求,成功后指定目录会生成
python_book.json文件
内容的提问来源于stack exchange,提问作者Berto Santos
相关产品推荐
相关产品推荐

