代码之家  ›  专栏  ›  技术社区  ›  amol rane

无法使用aiohttp发出异步请求

  •  0
  • amol rane  · 技术社区  · 6 年前

    我有以下pythonapi函数,它需要一些时间来给出输出。它的api端点是abc/abcd。当我从多个ip同时命中那个api端点时,它不会给出下一个输出,直到上一个请求没有完成。我用的是aiohttp。我应该同时回答许多请求

    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 回复  |  直到 6 年前
        1
  •  1
  •   Andrew Svetlov    6 年前

    请移动所有数据库访问代码( 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':'*'})