运行Python 3.8.3代码时出现405: Method Not Allowed错误求助
解决aiohttp API的405 Method Not Allowed错误
首先咱们拆解下405错误的本质:这个错误说明服务器收到了你的请求,但当前路由不支持你使用的HTTP请求方法,更常见的情况是——你没把处理函数正确绑定到路由上!
看你的代码,只定义了handle和new_user两个处理函数,但缺少了aiohttp应用最核心的两步:注册路由和启动应用实例。另外,aiohttp路由默认只绑定GET方法,如果你的new_user接口是用来创建用户的(通常用POST请求),没指定允许的方法的话,用POST访问就会直接报405。
修正后的完整代码
我把缺失的部分补全,同时给new_user指定支持POST和GET方法(你可以根据需求调整):
from aiohttp import web import json async def handle(request): response_obj = { 'status' : 'success' } return web.Response(text=json.dumps(response_obj)) async def new_user(request): try: print("AT Epoint" ) # 根据请求方法适配参数获取逻辑 if request.method == 'POST': data = await request.json() user = data['name'] else: user = request.query['name'] print("Creating new user with name: ", user) response_obj = { 'status' : 'success' } return web.Response(text=json.dumps(response_obj), status=200) except Exception as e: print("AT EXCEPTION" ) response_obj = { 'status' : 'failed', 'reason': str(e) } return web.Response(text=json.dumps(response_obj), status=500) # 核心:创建应用并注册路由 app = web.Application() # 给handle绑定根路径,默认支持GET请求 app.add_routes([web.get('/', handle)]) # 给new_user绑定/user路径,同时支持GET和POST请求 app.add_routes([web.get('/user', new_user), web.post('/user', new_user)]) if __name__ == '__main__': # 启动应用服务器(默认运行在localhost:8080) web.run_app(app)
关键修正点说明
- 路由注册:通过
app.add_routes把处理函数和URL路径、HTTP方法绑定。比如web.post('/user', new_user)明确告诉服务器/user路径接受POST请求,避免方法不匹配的错误。 - 参数适配:POST请求的参数通常在请求体里,用
await request.json()获取;GET请求用request.query,这样两种请求方法都能正常解析参数。 - 应用启动:最后通过
web.run_app(app)启动服务器,这是之前代码完全缺失的环节。
测试方法
你可以用curl验证:
- 测试GET请求:
curl http://localhost:8080/user?name=Alice
- 测试POST请求:
curl -X POST -H "Content-Type: application/json" -d '{"name":"Bob"}' http://localhost:8080/user
这样就不会再出现405错误啦!
内容的提问来源于stack exchange,提问作者Wilbur
相关产品推荐
相关产品推荐

