【问题标题】:python3.5 aiohttp, request post, json format and 405 errorspython3.5 aiohttp,请求post,json格式和405错误
【发布时间】:2015-12-15 08:50:57
【问题描述】:

我终于注册了,因为我对自己的问题一无所知。 我的后端部分使用 asyncio 和 aiohttp,前端部分使用 javascript。但我遇到了 405 错误。 (我准确地说我是这些库的初学者)

我希望从 post 请求中检索 json。这里是javascript函数:

function postJson (data){

    $.ajax({

           url : 'http://localhost:8080/postJson',
           type : 'POST',
           dataType : 'json',
           contentType : 'application/json',
           data  : data, //data are ready at json format, I do not think I need to use JSON.stringify ? I does not change anything to the error anywhere
           success : function(code_html, statut){ 
             console.log("success POST");
           },

           error : function(resultat, statut, erreur){
             console.log("error POST");
           }

        });
  }

和python代码:

async def postJson(request): 
   data = await request.post()
   #some code
   return Response()


@asyncio.coroutine
def init(loop):
    app = Application(loop=loop)
    app.router.add_route('POST', '/postJson', postJson)

    handler = app.make_handler()
    srv = yield from loop.create_server(handler, '127.0.0.1', 8080)
    print("Server started at http://127.0.0.1:8080")
    return srv, handler

loop = asyncio.get_event_loop()
srv, handler = loop.run_until_complete(init(loop))

try:
    loop.run_forever()
except KeyboardInterrupt:
    loop.run_until_complete(handler.finish_connections())

使用此代码,我收到 405 错误。这里有一点关于请求的萤火虫说:

Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 // so json is not in the list.

但是,如果我在我的 javascript 文件中取回 contentType : 'application/json' 行,它可以工作(但是请求发送一个名为 MultiDictProxy 的对象,我不明白如何使用来自 aiohttp.web 的函数 json()包(here)。

我真的需要一个 json 对象。有人可以帮助我吗?

【问题讨论】:

    标签: javascript python json aiohttp


    【解决方案1】:

    我找到了解决方案。我在这里为可能感兴趣的人发布结论:

    python 端:

    app.router.add_route('POST', '/postJson', postConf) 行替换为

    app.router.add_route('POST', '/postJson', postConf, expect_handler = aiohttp.web.Request.json)
    

    在 postJson 方法中:

    data = await request.post() 替换为data = await request.json()

    在 javascript 方面:

    data  : JSON.stringify(data)
    

    有了这个,我的方法有效。

    【讨论】:

    • 请去掉expect_handler参数——你使用不当。希望客户端不发送 EXPECT 标头
    【解决方案2】:

    您的示例运行良好,除了两件事:

    1. @asyncio.coroutineasync with 互斥
    2. postJson() 必须返回响应实例,而不是 None

    【讨论】:

    • 谢谢,我编辑了我的信息。但它不会改变错误。我一直在寻找有关路由语法的信息,它可能使用期望处理程序,但我不确定如何......(参见 aiohttp 服务器文档:add_route(method, path, handler, *, name=None, expect_handler=None) ) expect_handler 参数接受一个协程,并且有一个名为 json 的协程。但它需要一个参数,我看不出它是什么。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-11-07
    • 1970-01-01
    • 2017-09-09
    • 2019-05-08
    • 2018-04-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多