Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
520 views
in Technique[技术] by (71.8m points)

python 3.x - RuntimeError: this event loop is already running

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...