2016-11-23 46 views
0

我想,只要我收到请求响应用户,然后继续将数据保存到数据库响应用户并继续运行异步功能

async def index(request): 
    data = await request.post() 
    response.write("done") 
    async with request.app.mysqlpool.acquire() as conn: 
     async with conn.cursor() as cur: 
      await cur.execute("INSERT INTO ...") 

如果我尝试换请求后的部分。写入单独的函数,而不是使用run_in_executor调用它 - 它不允许在内部使用可用的函数(TypeError:协同程序不能与run_in_executor()一起使用)

有没有办法在aiohttp中执行?

回答

1

await response.drain()就在response.write(...)之后致电。

它并不完全保证数据通过电线发送,但它是最接近的解决方案。

+0

最后我是这样做的:body = json.dumps({“status”:“success”})。encode(“utf8”) resp = web.StreamResponse(headers = { “content-type “:”application/json“, ”content-length“:str(len(body)), }) await resp.prepare(self.request) resp.write(body) await resp.drain await resp.write_eof() – offline15