#!/usr/bin/env python # encoding: utf-8 # @author: 原凯峰 # @contact: 2894340009@qq.com # @software: pycharm # @file: aiohttpserver.py # @time: 2024/6/19 23:11 # @desc: import asyncio import aiohttp from aiohttp import web async def process_data(data): # 这里模拟异步数据处理,例如通过网络请求或数据库操作 await asyncio.sleep(1) # 模拟异步操作的延时 return f"Processed: {data}" # 定义CORS中间件 async def add_cors_headers(request, handler): # 设置CORS相关的响应头 response = handler(request) # 先调用handler处理请求,获取response response.headers['Access-Control-Allow-Origin'] = '*' response.headers['Access-Control-Allow-Methods'] = 'GET, POST, OPTIONS' response.headers['Access-Control-Allow-Headers'] = 'Content-Type' # 检查请求方法是否为OPTIONS if request.method == 'OPTIONS': # OPTIONS请求,返回204状态码,不返回body return web.Response(status=204, headers=response.headers) return response # 创建应用 app = web.Application(middlewares=[add_cors_headers]) # 定义路由和视图函数 async def handle_options(request): return web.Response(status=204) async def handle_post(request): data = await request.post() post_data = await data.text() # 异步读取POST数据 processed_data = await process_data(post_data) return web.json_response({ "POST": "request received", "processed_data": processed_data }) async def process_data(data): await asyncio.sleep(1) # 模拟异步操作的延时 return f"Processed: {data}" # 添加路由 app.add_routes([web.route('OPTIONS', '/', handle_options), web.route('POST', '/', handle_post)]) if __name__ == '__main__': web.run_app(app, host='127.0.0.1', port=8080)