有一个相对较新的Python 3 aiohttp库包含客户端/服务器.它是否包含ORM?如果没有 - 是否可以将它与第三方ORM一起使用?如果不可能 - 为什么可以使用它?我并不是说没有ORM就不能编写应用程序,但Python框架的主要浪费支持它,开发人员习惯于这种编程风格.
所以我有一个与我一起学习Python的不和谐机器人.我有一个下载图像,编辑/合并它们的命令,然后将编辑后的图像发送到聊天室.之前我曾经requests这样做过,但我被其中一个图书馆开发者告知discord.py,我应该使用aiohttp而不是requests.我找不到如何下载图片aiohttp,我尝试了很多东西,但没有一个有效.
if message.content.startswith("!async"):
import aiohttp
import random
import time
import shutil
start = time.time()
notr = 0
imagemake = Image.new("RGBA",(2048,2160))
imgsave = "H:\Documents\PyCharmProjects\ChatBot\Images"
imagesend = os.path.join(imgsave,"merged.png")
imgmergedsend =os.path.join(imgsave,"merged2.png")
with aiohttp.ClientSession() as session:
async with session.get("http://schoolido.lu/api/cards/788/") as resp:
data = await resp.json()
cardsave = session.get(data["card_image"])
with open((os.path.join(imgsave, "card.png")),"wb") as out_file:
shutil.copyfileobj(cardsave, out_file)
Run Code Online (Sandbox Code Playgroud)
是我现在所拥有的,但仍然无效.
那么,有没有办法下载图像?
在aiohttp的doc中写道:
- loop - 用于处理HTTP请求的事件循环.如果loop为None,则构造函数如果指定则从连接器借用它.asyncio.get_event_loop()用于获取默认事件循环.
自2.0版以来已弃用.
我用谷歌搜索,但没有得到任何关于为什么loop参数被弃用的描述.
我经常创建这样的ClientSession对象:
loop = asyncio.get_event_loop()
session = aiohttp.ClientSession(loop=loop)
Run Code Online (Sandbox Code Playgroud)
现在loop参数被删除了,但只是在aiohttp.ClientSession()没有循环的情况下调用会得到一个警告:
在协同程序之外创建客户端会话
那么为什么不推荐使用该参数以及如何正确使用会话?
API通常具有用户必须遵循的速率限制。例如,让我们接受50个请求/秒。顺序请求需要0.5-1秒,因此太慢了,无法接近该限制。但是,使用aiohttp的并行请求超出了速率限制。
为了尽可能快地轮询API,需要对并行调用进行速率限制。
到目前为止,我发现的示例装饰了session.get,大致像这样:
session.get = rate_limited(max_calls_per_second)(session.get)
Run Code Online (Sandbox Code Playgroud)
这对于顺序调用非常有效。尝试在并行调用中实现此功能无法按预期进行。
这是一些示例代码:
async with aiohttp.ClientSession() as session:
session.get = rate_limited(max_calls_per_second)(session.get)
tasks = (asyncio.ensure_future(download_coroutine(
timeout, session, url)) for url in urls)
process_responses_function(await asyncio.gather(*tasks))
Run Code Online (Sandbox Code Playgroud)
问题在于它将限制任务的排队速度。与的执行gather将或多或少地同时发生。两全其美;-)。
是的,我在aiohttp处发现了一个类似的问题:设置每秒的最大请求数,但没有答复回答限制请求速率的实际问题。同样,来自Quentin Pradet的博客文章仅在限制队列速率上起作用。
总结一下:如何限制并行请求的每秒aiohttp请求数?
我在模拟aiohttp.client.ClientSession.get上下文管理器时遇到了一些麻烦.我找到了一些文章,这里有一个似乎正在起作用的例子:第1条
所以我要测试的代码:
async_app.py
import random
from aiohttp.client import ClientSession
async def get_random_photo_url():
while True:
async with ClientSession() as session:
async with session.get('random.photos') as resp:
json = await resp.json()
photos = json['photos']
if not photos:
continue
return random.choice(photos)['img_src']
Run Code Online (Sandbox Code Playgroud)
并测试:
test_async_app.py
from asynctest import CoroutineMock, MagicMock, patch
from asynctest import TestCase as TestCaseAsync
from async_app import get_random_photo_url
class AsyncContextManagerMock(MagicMock):
async def __aenter__(self):
return self.aenter
async def __aexit__(self, *args):
pass
class TestAsyncExample(TestCaseAsync):
@patch('aiohttp.client.ClientSession.get', new_callable=AsyncContextManagerMock)
async def test_call_api_again_if_photos_not_found(self, mock_get):
mock_get.return_value.aenter.json = CoroutineMock(side_effect=[{'photos': []}, …Run Code Online (Sandbox Code Playgroud) 我遵循此步骤,但不知何故这会引发错误..
默认配置是
http {
upstream alert {
# fail_timeout=0 means we always retry an upstream even if it failed
# to return a good HTTP response
# Unix domain servers
server unix:/tmp/alert_1.sock fail_timeout=0;
server unix:/tmp/alert_2.sock fail_timeout=0;
server unix:/tmp/alert_3.sock fail_timeout=0;
server unix:/tmp/alert_4.sock fail_timeout=0;
# Unix domain sockets are used in this example due to their high performance,
# but TCP/IP sockets could be used instead:
# server 127.0.0.1:8081 fail_timeout=0;
# server 127.0.0.1:8082 fail_timeout=0;
# server 127.0.0.1:8083 fail_timeout=0;
# server …Run Code Online (Sandbox Code Playgroud) 我正在使用 aiohttp 进行长时间运行的进程。一开始,我使用 API 进行授权,取回访问令牌。响应还包括一个refresh_token值(我认为它正在使用oauth2)。
我正在运行的进程需要一个多小时,访问令牌将在 60 分钟后过期(如expires_in身份验证响应中的值 3600 所示)。我想我可以使用刷新授权,refresh_token但最好将客户端会话配置为根据需要自动刷新。
我认为它应该:
是否有推荐的方法来子类ClientSession化aiohttp. 我发现了这个例子,但不太遵循它。
我想从网站下载/抓取 5000 万条日志记录。我没有一次性下载 5000 万个,而是尝试使用以下代码一次下载 1000 万个,但它一次只能处理 20,000 个(超过这个数量会引发错误),因此它变得非常耗时下载那么多数据。目前下载20000条记录的速度需要3-4分钟,100%|\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88| 20000/20000 [03:48<00:00, 87.41it/s]那么如何加速呢?
import asyncio\nimport aiohttp\nimport time\nimport tqdm\nimport nest_asyncio\n\nnest_asyncio.apply()\n\n\nasync def make_numbers(numbers, _numbers):\n for i in range(numbers, _numbers):\n yield i\n\n\nn = 0\nq = 10000000\n\n\nasync def fetch():\n # example\n url = "https://httpbin.org/anything/log?id="\n\n async with aiohttp.ClientSession() as session:\n post_tasks = []\n # prepare the coroutines that poat\n async for x in make_numbers(n, q):\n post_tasks.append(do_get(session, url, x))\n # now execute them all at once\n\n responses = [await f for f in tqdm.tqdm(asyncio.as_completed(post_tasks), …Run Code Online (Sandbox Code Playgroud) 这里是新手。
我一直在尝试将 openai 库安装到 python 中,但我一直遇到问题。我已经安装了 C++ 库。
aio http 似乎存在特定问题,我收到以下错误。我运行的是 Windows 11 笔记本电脑,没有管理员限制。
错误
"C:\Program Files (x86)\Microsoft Visual Studio\2022\BuildTools\VC\Tools\MSVC\14.37.32822\bin\HostX86\x64\cl.exe" /c /nologo /O2 /W3 /GL /DNDEBUG /MD -IC:\Users\sande\AppData\Local\Programs\Python\Python312\include -IC:\Users\sande\AppData\Local\Programs\Python\Python312\Include "-IC:\Program Files (x86)\Microsoft Visual Studio\2022\BuildTools\VC\Tools\MSVC\14.37.32822\include" "-IC:\Program Files (x86)\Microsoft Visual Studio\2022\BuildTools\VC\Auxiliary\VS\include" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.22621.0\ucrt" "-IC:\Program Files (x86)\Windows Kits\10\\include\10.0.22621.0\\um" "-IC:\Program Files (x86)\Windows Kits\10\\include\10.0.22621.0\\shared" "-IC:\Program Files (x86)\Windows Kits\10\\include\10.0.22621.0\\winrt" "-IC:\Program Files (x86)\Windows Kits\10\\include\10.0.22621.0\\cppwinrt" /Tcaiohttp/_websocket.c /Fobuild\temp.win-amd64-cpython-312\Release\aiohttp/_websocket.obj
_websocket.c
aiohttp/_websocket.c(1475): warning C4996: 'Py_OptimizeFlag': deprecated in 3.12
aiohttp/_websocket.c(3042): error C2039: 'ob_digit': is not a member of '_longobject'
[end …Run Code Online (Sandbox Code Playgroud) 看起来aiohttp.ProxyConnector 不支持socks代理.这有什么解决方法吗?我会很感激任何建议.
aiohttp ×10
python ×8
python-3.x ×3
asynchronous ×2
asynctest ×1
nginx ×1
oauth-2.0 ×1
openai-api ×1
orm ×1
pip ×1