标签: aiohttp

Python aiohttp请求已停止,但没有异常

aiohttp用来请求网址.大部分时间它正常运行,但有时它会停止而不会引发任何异常.

正如您在代码中看到的,我捕获了所有异常,但是当它停止时,不会打印异常日志.

日志看起来像:

get_live_league_games: while True
try
yield from aiohttp.request
Run Code Online (Sandbox Code Playgroud)

但' res = yield from r.json()'不打印,它停止并且不会抛出任何异常.

while True:
    print('get_live_league_games: while True')
    start = time.clock()
    try:
        print('try')
        r = yield from aiohttp.request('GET',url)
        print('yield from aiohttp.request')
        res = yield from r.json()
        print('res = yield from r.json()')
    except aiohttp.errors.DisconnectedError as e:
        logging.warning('get_live_league_games:',e)
        yield from asyncio.sleep(10)
        continue
    except aiohttp.errors.ClientError as e:
        logging.warning('get_live_league_games:',e)
        yield from asyncio.sleep(10)
        continue
    except aiohttp.errors.HttpProcessingError as e:
         logging.warning('get_live_league_games:',e)
         yield from asyncio.sleep(10)
         continue
    except Exception as e:
         logging.warning('get_live_league_games,Exception:',e)
         yield …
Run Code Online (Sandbox Code Playgroud)

python python-3.x python-asyncio aiohttp

6
推荐指数
1
解决办法
1269
查看次数

使用gunicorn运行aiohttp服务器

我正在尝试使用Gunicorn运行基于aiohttp的服务器.

这是命令:

gunicorn aiohttpdemo_polls:app --bind 127.0.0.1:8080
Run Code Online (Sandbox Code Playgroud)

它返回:

Failed to find application: 'aiohttpdemo_polls' 
Run Code Online (Sandbox Code Playgroud)

但是当我使用python -m运行它时,如下所示:

python -m aiohttpdemo_polls
Run Code Online (Sandbox Code Playgroud)

它工作正常.代码可以在这里找到,这是aiohttp repo中的一个演示应用程序.也尝试过如下:

gunicorn aiohttpdemo_polls.main:app --bind 127.0.0.1:8080
Run Code Online (Sandbox Code Playgroud)

但它也没有运行服务器.它回来了

Failed to find application: 'aiohttpdemo_polls.main'
Run Code Online (Sandbox Code Playgroud)

知道在哪里进一步寻找解决问题的方法吗?

python python-3.x gunicorn aiohttp

6
推荐指数
2
解决办法
1119
查看次数

异步/IO 和并行

我正在使用aiohttp创建一个异步/IO 网络服务器。但是,据我了解,Async/IO 意味着服务器只能在一个处理核心上运行。uwsgi另一方面,像 一样的常规同步服务器可以通过真正并行的线程和进程充分利用计算机的计算资源。那么,为什么是异步/ IO新时尚,如果它比多处理器并行?异步服务器aiohttp可以多处理吗?

python python-asyncio aiohttp python-multiprocessing python-3.5

6
推荐指数
2
解决办法
3425
查看次数

将 django 与 aiohttp/asyncio 集成

我想将 django 与 aiohttp/asyncio 集成以进行异步编程和 websockets 处理。我知道 django 有 celery 和 django-channels 来分别执行异步任务和 websocket 服务器,但是 aiohttp 预先内置了异步和 websocket 服务器,我发现该框架在创建功能时比 celery/django 通道更具可扩展性和简单性到 webscraping(我不知道是否可以在 celery I 中进行 webscraping,还没有尝试过)。
并且它也完美支持异步和等待。

但我的问题是:我们如何在一个项目中同时实现 django 和 aiohttp?我们可以使用 aiohttp 服务器来代替使用 django 的开发服务器来为站点提供服务。

我们是否能够将 django 与 aiohttp 功能集成(例如让我们举个例子:如果我想将用户提交的输入的网站抓取到我的数据库中。我可以在获取网站并将以下网站发布到我的函数中时使用 await 调用吗?我的 django 数据库?或者将函数结果发布到另一个 django 函数?)

我想知道集成的缺点,如果有的话?

在发布您的答案时,请您发布一个示例实际集成示例,而不是通过 github 向我建议这些库。

python django asynchronous python-asyncio aiohttp

6
推荐指数
1
解决办法
1060
查看次数

aiohttp asyncio.TimeoutError from None 使用 ClientSession

这是一个奇怪的错误,因为当我尝试/捕获它时,它什么也不打印。

我正在使用 sanic 服务器 asyncio.gather 同时收集一堆图像,超过 3000 张图像。

在处理较小的样本量时,我没有遇到此错误。

简化示例:

from sanic import Sanic
from sanic import response
from aiohttp import ClientSession

from asyncio import gather

app = Sanic()

@app.listener('before_server_start')
async def init(app, loop):
    app.session = ClientSession(loop=loop)

@app.route('/test')
async def test(request):
    data_tasks = []
    #The error only happened when a large amount of images were used
    for imageURL in request.json['images']:
        data_tasks.append(getRaw(imageURL))
    await gather(*data_tasks)
    return response.text('done')

async def getRaw(url):
    async with app.session.get(url) as resp:
        return await resp.read()
Run Code Online (Sandbox Code Playgroud)

这个错误可能是什么?如果这是我的主机/互联网的某种限制,我该如何避免?

如果有帮助,我正在使用来自 DigitalOcean 的具有 …

python python-3.x python-asyncio aiohttp sanic

6
推荐指数
1
解决办法
2158
查看次数

使用 aiohttp 时的 socket.gaierror

我正在尝试从多个域中获取标题。所以我写了这段代码:

import aiohttp
import asyncio
from bs4 import BeautifulSoup

headers = {
    'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.70 Safari/537.36',
    'Accept-Encoding': ', '.join(('gzip', 'deflate', 'br')),
    'Accept': '*/*',
    'Connection': 'keep-alive'
}


async def fetch(url, session):
    async with session.get(f'http://{url}') as response:
        text = await response.text()
        return url, BeautifulSoup(text, 'lxml').title.string


async def main():
    async with asyncio.Semaphore(50):
        async with aiohttp.ClientSession(connector=aiohttp.TCPConnector(ssl=False), timeout=aiohttp.ClientTimeout(10),
                                         headers=headers) as session:
            titles = await asyncio.gather(*[fetch(domain, session) for domain in domains[0:500]],
                                          return_exceptions=True)
            for title in titles: …
Run Code Online (Sandbox Code Playgroud)

python python-3.x python-asyncio aiohttp

6
推荐指数
1
解决办法
303
查看次数

aiohttp.client_exceptions.ClientOSError: [WinError 10054] 现有连接被远程主机强行关闭

我正在尝试aiohttpasyncio第一次出现错误

[WinError 10054] 现有连接被远程主机强行关闭

但是当我获取requests它正常工作时相同的 url.so这个错误意味着什么以及如何解决它?

我的代码

import aiohttp 
import asyncio

url = 'https://nseindia.com/api/historical/fo/derivatives?&from=24-01-2020&to=24-01-2020&expiryDate=06-FEB-2020&instrumentType=OPTIDX&symbol=NIFTY&csv=true'

headers = {"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36"}
async def get_data():
    async with aiohttp.ClientSession(headers=headers) as session:
        async with session.get(url) as resp:
            result = await resp.text()
            return result


async def main():
    result = await get_data()
    return result

asyncio.run(main())

Run Code Online (Sandbox Code Playgroud)

python python-asyncio aiohttp

6
推荐指数
1
解决办法
910
查看次数

在 aiohttp 中执行请求时 await 和 async-with 之间有本质区别吗?

我的问题是关于做出回应的正确方式 aiohttp

官方 aiohttp 文档为我们提供了进行异步查询的示例:

session = aiohttp.ClientSession()

async with session.get('http://httpbin.org/get') as resp:
    print(resp.status)
    print(await resp.text())

await session.close()
Run Code Online (Sandbox Code Playgroud)

我不明白,为什么这里的上下文管理器。我发现的只是__aexit__()方法等待resp.release()方法。但是文档还告诉我们resp.release()一般不需要等待。

这一切真的让我很困惑。

如果我发现下面的代码更具可读性并且不是那么嵌套,为什么要这样做?

session = aiohttp.ClientSession()

resp = await session.get('http://httpbin.org/get')
print(resp.status)
print(await resp.text())

# I finally have not get the essence of this method.
# I've tried both using and not using this method in my code,
# I've not found any difference in behaviour.
# await resp.release()

await session.close()
Run Code Online (Sandbox Code Playgroud)

我已经深入研究了aiohttp.ClientSession它的上下文管理器来源,但我没有发现任何可以澄清情况的东西。

最后,我的问题是:有什么区别?

python asynchronous async-await python-asyncio aiohttp

6
推荐指数
1
解决办法
193
查看次数

连接到 FastAPI 端点后 Websocket 立即关闭

我正在尝试将 websocket aiohttp 客户端连接到 fastapi websocket 端点,但我无法发送或接收任何数据,因为似乎 websocket 在连接到端点后立即关闭。


服务器

import uvicorn
from fastapi import FastAPI, WebSocket

app = FastAPI()

@app.websocket('/ws')
async def websocket_endpoint(websocket: WebSocket):
    await websocket.accept()
    ...


if __name__ == '__main__':
    uvicorn.run('test:app', debug=True, reload=True)

Run Code Online (Sandbox Code Playgroud)

客户

import aiohttp
import asyncio

async def main():
    s = aiohttp.ClientSession()
    ws = await s.ws_connect('ws://localhost:8000/ws')
    while True:
        ...

asyncio.run(main())
Run Code Online (Sandbox Code Playgroud)

当我尝试在建立连接时将数据从服务器发送到客户端时

服务器

@app.websocket('/ws')
async def websocket_endpoint(websocket: WebSocket):
    await websocket.accept()
    await websocket.send_text('yo')
Run Code Online (Sandbox Code Playgroud)

客户

while True:
   print(await ws.receive())

Run Code Online (Sandbox Code Playgroud)

我总是在客户的控制台中打印

WSMessage(type=<WSMsgType.CLOSED: 257>, data=None, extra=None)
Run Code Online (Sandbox Code Playgroud)

在服务器的调试控制台中它说

INFO:     ('127.0.0.1', 59792) - …
Run Code Online (Sandbox Code Playgroud)

python websocket python-3.x aiohttp fastapi

6
推荐指数
1
解决办法
8512
查看次数

在 for 循环中运行异步函数时 Asyncio + Aiohttp 内存泄漏 (python)

我正在制作一个 python 函数,它向 api 发出很多请求。该函数的工作原理如下:

async def get_one(session, url):
    try:
        with session.get(url) as resp:
            resp = await resp.json()
    except:
        resp = None
    return resp, url

async def get_all(session, urls):
    tasks = [asyncio.create_task(get_one(session, url)) for url in urls]
    results = await asyncio.gather(*tasks)
    return results

async def make_requests(urls):
    timeout = aiohttp.ClientTimeout(sock_read=10, sock_connect=10, total=0.1*len(urls))
    connector = aiohttp.TCPConnector(limit=125)
    async with aiohttp.ClientSession(connector=connector, skip_auto_headers=['User-Agent'], timeout=timeout) as session:
        data = await get_all(session, ids)
        return data

def main(urls):
    results = []

    while urls:
        retry = []
        response = …
Run Code Online (Sandbox Code Playgroud)

python python-asyncio aiohttp

6
推荐指数
0
解决办法
1099
查看次数