RuntimeError:此事件循环已在运行 [英] RuntimeError: this event loop is already running

查看:135
本文介绍了RuntimeError:此事件循环已在运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用sanic中的以下代码运行异步的第三方文件上传

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)

但是,它返回RuntimeError:此事件循环已在运行.错误

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

推荐答案

以下是在sanic中对我有用的代码

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)

这篇关于RuntimeError:此事件循环已在运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆