RuntimeError: this event loop is already running

∥☆過路亽.° 提交于 2019-11-27 07:25:46

问题


I am trying to run an asynchronous 3rd party file upload using the following code in sanic

def up(self,request):
    import asyncio

    import aiohttp

    header = {
        'Authorization': 'Client-ID {}'.format(self.client_id)
    }

    data = {
        'image': open("/home/jibin/Downloads/test.jpg", "rb")
    }

    async def upload(data):

        async with aiohttp.ClientSession() as session:
            async with  session.post(self.url, headers=header,data=data) as resp:
                data = await resp.text()
                print(data)


    futures = []

    futures.append(upload(data))

    loop = asyncio.get_event_loop()
    loop.run_until_complete(asyncio.wait(futures))
    loop.close()

    return response.json("done",status=200)

this is how I call the request from the route.

@app.route('/upload', methods=['POST'])
async def upload(request):
    return up(request)

However, it returns RuntimeError: this event loop is already running. error


回答1:


Here is the code that worked for me in sanic

@app.route('/upload')
async def get_ressource(request):
    asyncio.ensure_future(blocking_function())
    return await resp()

async def blocking_function():
    async with aiohttp.ClientSession() as session:
        async with session.post("your_url", data={
            'image': open("file_path", "rb"),
        }, headers={
            'Authorization': 'Client-ID {}'.format("your_client_id")
        }) as resp:
            result = await resp.text()
    print(result)


async def resp():
    return response.json("OK", status=202)


来源:https://stackoverflow.com/questions/53663219/runtimeerror-this-event-loop-is-already-running

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!