我正在使用aiohttp创建一个异步/IO 网络服务器。但是,据我了解,Async/IO 意味着服务器只能在一个处理核心上运行。uwsgi另一方面,像 一样的常规同步服务器可以通过真正并行的线程和进程充分利用计算机的计算资源。那么,为什么是异步/ IO新时尚,如果它少比多处理器并行?异步服务器aiohttp可以多处理吗?
python python-asyncio aiohttp python-multiprocessing python-3.5
我想将 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 向我建议这些库。
这是一个奇怪的错误,因为当我尝试/捕获它时,它什么也不打印。
我正在使用 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 的具有 …
我正在尝试从多个域中获取标题。所以我写了这段代码:
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) 我正在尝试aiohttp和asyncio第一次出现错误
[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 函数,它向 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) 在我的 Django 应用程序中,我需要将来自用户的请求代理到其他服务器。我使用asyncio/aiohttp client.
#user->request
.....
loop = asyncio.get_event_loop()
future = asyncio.ensure_future(self.run(t1, t2, t3))
loop.run_until_complete(future)
......
# response
Run Code Online (Sandbox Code Playgroud)
当我的 django 服务器以 启动时python manager.py runserver,当用户请求时出现以下错误。
运行时错误:线程“Thread-1”中没有当前事件循环。
但是当我开始时Gunicorn,一切都很好。
也许我应该使用new_event_loop?
为什么没有问题Gunicorn?
想象一下,我有一个基于 Aiohttp 的 Web 应用程序:
from aiohttp import web
import asyncio
import logging
logger = logging.getLogger(__name__)
async def hello(request):
logger.info('Started processing request')
await asyncio.sleep(1)
logger.info('Doing something')
await asyncio.sleep(1)
return web.Response(text="Hello, world!\n")
logging.basicConfig(
level=logging.DEBUG,
format='%(asctime)s %(name)-14s %(levelname)s: %(message)s')
app = web.Application()
app.add_routes([web.get('/', hello)])
web.run_app(app)
Run Code Online (Sandbox Code Playgroud)
它的输出是(例如):
2019-11-11 13:37:14,757 __main__ INFO: Started processing request
2019-11-11 13:37:14,757 __main__ INFO: Started processing request
2019-11-11 13:37:15,761 __main__ INFO: Doing something
2019-11-11 13:37:15,761 __main__ INFO: Doing something
2019-11-11 13:37:16,765 aiohttp.access INFO: 127.0.0.1 [11/Nov/2019:12:37:14 +0000] "GET / HTTP/1.1" …Run Code Online (Sandbox Code Playgroud) 我正在使用 asyncio 和 aiohttp 来发出并发请求。我最近将 Python 升级到了 3.8.0 版,并且RuntimeError: Event loop is closed在程序运行后得到了一个。
import asyncio
import aiohttp
async def do_call(name, session):
async with session.get('https://www.google.be') as response:
await response.text()
return 'ok - {}'.format(name)
async def main():
async with aiohttp.ClientSession() as session:
tasks = [do_call(str(i), session) for i in range(0,4)]
results = await asyncio.gather(*tasks)
print(results)
asyncio.run(main())
Run Code Online (Sandbox Code Playgroud)
我确实从 asyncio.gather() 得到了一个有效的结果,但是在退出时会引发异常。我想更改代码,以免遇到异常。
回溯如下:
Exception ignored in: <function _ProactorBasePipeTransport.__del__ at 0x000001E9A92079D0>
Traceback (most recent call last):
File "C:\Users\Jonas\AppData\Local\Programs\Python\Python38\lib\asyncio\proactor_events.py", line 116, in __del__
self.close()
File …Run Code Online (Sandbox Code Playgroud) 场景:我需要从 Web 应用程序的 API 收集分页数据,该 API 的调用限制为每分钟 100 次。我需要返回的 API 对象每页包含 100 个项目,总共有 105 个页面,而且还在不断增加(总共约 10,500 个项目)。同步代码需要大约 15 分钟来检索所有页面,因此那时不必担心达到调用限制。但是,我想加快数据检索速度,因此我使用asyncio和实现了异步调用aiohttp。数据现在在 15 秒内下载 - 很好。
问题:我现在达到了呼叫限制,因此在最近 5 次左右的呼叫中收到 403 错误。
建议的解决方案我实现了try/except在get_data()函数中找到的。我拨打电话,然后当由于403: Exceeded call limit我退后back_off几秒钟而未成功拨打电话并重试retries多次时:
async def get_data(session, url):
retries = 3
back_off = 60 # seconds to try again
for _ in range(retries):
try:
async with session.get(url, headers=headers) as response:
if response.status != 200:
response.raise_for_status() …Run Code Online (Sandbox Code Playgroud) aiohttp ×10
python ×10
python-asyncio ×10
asynchronous ×2
django ×2
python-3.x ×2
async-await ×1
coroutine ×1
logging ×1
python-3.5 ×1
rest ×1
sanic ×1