I finally sign up because I have no more idea for my problem. I use asyncio and aiohttp for my back-end part and javascript for the front-end part. But I stuck with a 405 error. (I precise I am a beginner with theses libraries)
I wish retrieve a json from a post request. Here the javascript function:
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");
}
});
}
and the python code:
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())
With this code I get a 405 error. Here a bite of what says firebug about the request:
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 // so json is not in the list.
however, if I take back the line contentType : 'application/json'
in my javascript file, it works (but the request send a object called MultiDictProxy
and I don't understand how to use the function json()
from aiohttp.web
package (here).
I really need to get a json object. Someone could help me?
I find the solution. I post the conclusion here for people who could be interested:
python side:
replace the line app.router.add_route('POST', '/postJson', postConf)
by
app.router.add_route('POST', '/postJson', postConf, expect_handler = aiohttp.web.Request.json)
in the postJson method:
replace data = await request.post()
by data = await request.json()
and on javascript side:
data : JSON.stringify(data)
with this, my method works.