无法使用aiohttp发出异步请求

时间:2018-10-07 13:03:16

标签: python-3.x aiohttp

我有以下python api函数,需要一些时间才能给出输出。它的api端点是abc / abcd。当我同时从多个IP命中该api端点时,它不会给出下一个输出,直到上一个请求未完成为止。我正在使用aiohttp。我的api应该同时回答许多请求

async def Logistic(request):
    container_id = request.query['container_id']
    company = request.query['company']
    data = mysqlcon("SELECT date,moves,location,vessel,voyage,current_status FROM container_status WHERE date_current in (SELECT max(date_current) FROM container_status) and company_id={0}".format(container_id),"rpa")
    a = {"Result":[]}
    if data == ():
        pass
    else:
        for i in data:
            a["Result"].append(i)
    return web.Response(text=json.dumps(a),headers={'ACCESS-CONTROL-ALLOW-ORIGIN':'*'})

1 个答案:

答案 0 :(得分:1)

请将所有数据库访问代码(SELECT ...执行和对返回结果的迭代)移到一个单独的函数中,然后在线程池中运行它:

def sync_db_request(container_id):
    data = mysqlcon("SELECT date,moves,location,vessel,voyage,current_status FROM container_status WHERE date_current in (SELECT max(date_current) FROM container_status) and company_id={0}".format(container_id),"rpa")
    a = {"Result":[]}
    if data == ():
        pass
    else:
        for i in data:
            a["Result"].append(i)
    return a

async def Logistic(request):
    container_id = request.query['container_id']
    company = request.query['company']
    a = await request.loop.run_in_executor(None, sync_db_request, container_id)
    return web.Response(text=json.dumps(a),headers={'ACCESS-CONTROL-ALLOW-ORIGIN':'*'})