RuntimeError: this event loop is already running
RuntimeError: this event loop is already running
我正尝试在 sanic
中使用以下代码 运行 异步第 3 方文件上传
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)
这就是我从路由中调用请求的方式。
@app.route('/upload', methods=['POST'])
async def upload(request):
return up(request)
但是,它 returns RuntimeError: 这个事件循环已经 运行ning。错误
这是在 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)
我正尝试在 sanic
中使用以下代码 运行 异步第 3 方文件上传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)
这就是我从路由中调用请求的方式。
@app.route('/upload', methods=['POST'])
async def upload(request):
return up(request)
但是,它 returns RuntimeError: 这个事件循环已经 运行ning。错误
这是在 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)