运行以下代码:
async def generate_url(self, ding_id):
data = await self.s3.generate_presigned_url(
ClientMethod='get_object',
Params={
'Bucket': '...',
'Key': '{}.mp4'.format(ding_id)
}
)
return data
def convert_to_json(self, data):
loop = asyncio.get_event_loop()
for ding in dings:
tasks.append(self.generate_url(ding))
video_ids = loop.run_until_complete(asyncio.gather(*tasks))
loop.close()
Run Code Online (Sandbox Code Playgroud)
导致错误:
'Key': '{}.mp4'.format(ding_id)
TypeError: object str can't be used in 'await' expression`
Run Code Online (Sandbox Code Playgroud)
我使用异步请求库aiohttp。如何解决这个问题?
我有那个代码
async with aiohttp.ClientSession() as session:
content = 'none'
while content == 'none':
try:
async with session.get(url) as resp:
resp.raise_for_status()
content = await resp.json()
except aiohttp.ClientError:
await asyncio.sleep(1)
except Exception as e:
print(e)
await asyncio.sleep(1)
Run Code Online (Sandbox Code Playgroud)
我想在结果良好时发出请求,但如果我编译它,有时结果是“无”。怎么让它变得更好。
我需要抓取并获取许多(每天 5-10k)新闻文章的正文段落的原始文本。我已经编写了一些线程代码,但考虑到这个项目的高度 I/O 限制性质,我正在涉足asyncio. 下面的代码片段并不比 1 线程版本快,而且比我的线程版本差得多。谁能告诉我我做错了什么?谢谢你!
async def fetch(session,url):
async with session.get(url) as response:
return await response.text()
async def scrape_urls(urls):
results = []
tasks = []
async with aiohttp.ClientSession() as session:
for url in urls:
html = await fetch(session,url)
soup = BeautifulSoup(html,'html.parser')
body = soup.find('div', attrs={'class':'entry-content'})
paras = [normalize('NFKD',para.get_text()) for para in body.find_all('p')]
results.append(paras)
return results
Run Code Online (Sandbox Code Playgroud) 我使用 tor 的 http 代理(使用 aiohttp_socks)通过 aiohttp 发送多个请求
完成一些请求后,我收到以下错误:
Traceback (most recent call last):
File "main.py", line 171, in <module>
loop.run_until_complete(future)
File "/usr/lib/python3.8/asyncio/base_events.py", line 616, in run_until_complete
return future.result()
File "main.py", line 95, in get_market_pages
async with session.get(active_link, headers=headers) as response:
File "/home/mrlalatg/.local/lib/python3.8/site-packages/aiohttp/client.py", line 1012, in __aenter__
self._resp = await self._coro
File "/home/mrlalatg/.local/lib/python3.8/site-packages/aiohttp/client.py", line 504, in _request
await resp.start(conn)
File "/home/mrlalatg/.local/lib/python3.8/site-packages/aiohttp/client_reqrep.py", line 847, in start
message, payload = await self._protocol.read() # type: ignore # noqa
File "/home/mrlalatg/.local/lib/python3.8/site-packages/aiohttp/streams.py", line 591, in …Run Code Online (Sandbox Code Playgroud) 我已添加“cors_middleware”,但仍然收到“已被 CORS 策略阻止:请求的资源上不存在“Access-Control-Allow-Origin”标头。” 错误。
#代码
root_app = web.Application(
middlewares=[
cors_middleware(
allow_all=True,
origins='*',
# urls=[re.compile(r"^\/api")],
allow_credentials=True,
expose_headers="*",
allow_headers='*',
allow_methods=["POST", "PATCH", 'GET','OPTION'],
),
]
)
Run Code Online (Sandbox Code Playgroud)
#错误
从源“http://localhost:63342”访问“http://localhost:8000/api/v1/user/”处的 XMLHttpRequest 已被 CORS 策略阻止:没有“Access-Control-Allow-Origin”标头存在于所请求的资源上。
我想使用 python 并行运行许多 HTTP 请求。我尝试使用 asyncio 这个名为 aiohttp 的模块。
import aiohttp
import asyncio
async def main():
async with aiohttp.ClientSession() as session:
for i in range(10):
async with session.get('https://httpbin.org/get') as response:
html = await response.text()
print('done' + str(i))
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
Run Code Online (Sandbox Code Playgroud)
我期望它并行执行所有请求,但它们是一一执行的。虽然,我后来使用线程解决了这个问题,但我想知道这有什么问题吗?
我相信在使用 aiohttp ClientSession 请求时,我在长期存在的应用程序中发现了内存泄漏。如果按顺序等待每个发出请求的协程,那么一切似乎都很好。然而,并发运行时似乎存在请求上下文管理器对象的泄漏。
请考虑以下示例代码:
import logging
import tracemalloc
import asyncio
import aiohttp
async def log_allocations_coro():
while True:
await asyncio.sleep(120)
snapshot = tracemalloc.take_snapshot()
top_stats = snapshot.statistics('lineno')
str_list = [str(x) for x in top_stats[:5]]
logging.info("\n".join(str_list))
async def do_request():
try:
async with session.request("GET", "http://192.168.1.1") as response:
text = await response.text()
except:
logging.exception("Request failed")
async def main():
tracemalloc.start()
asyncio.ensure_future(log_allocations_coro())
timeout = aiohttp.ClientTimeout(total=1)
global session
session = aiohttp.ClientSession(timeout=timeout)
while True:
tasks = [ do_request(), do_request() ]
await asyncio.gather(*tasks)
await asyncio.sleep(2)
if __name__ == '__main__': …Run Code Online (Sandbox Code Playgroud) 我正在尝试访问具有机器人防护功能的网站。
使用以下脚本使用请求我可以访问该网站。
request = requests.get(url,headers={**HEADERS,'Cookie': cookies})
Run Code Online (Sandbox Code Playgroud)
我得到了所需的 HTML。但是当我使用 aiohttp 时
async def get_data(session: aiohttp.ClientSession,url,cookies):
async with session.get(url,timeout = 5,headers={**HEADERS,'Cookie': cookies}) as response:
text = await response.text()
print(text)
Run Code Online (Sandbox Code Playgroud)
我收到机器人预防页面作为响应。
这是我用于所有请求的标头。
HEADERS = {
'User-Agent': 'PostmanRuntime/7.29.0',
'Host': 'www.dnb.com',
'Connection': 'keep-alive',
'Accept': '/',
'Accept-Encoding': 'gzip, deflate, br'
}
Run Code Online (Sandbox Code Playgroud)
我比较了 requests.get 和 aiohttp 的请求标头,它们是相同的。
结果不同有什么原因吗?如果是这样为什么?
编辑:我检查了 httpx 模块,问题也出现在httpx.Client()那里httpx.AsyncClient()。
response = httpx.request('GET',url,headers={**HEADERS,'Cookie':cookies})
Run Code Online (Sandbox Code Playgroud)
效果不太好。(不是异步的)
我使用 Aiohttp 服务器和 python-socket-io 构建了一个聊天应用程序。当我尝试在 nginx 中托管此应用程序时,我在主管错误日志中发现了此错误(错误日志路径= /var/log/gunicorn/gunicorn.err.log )
[2022-05-27 04:16:31 +0000] [32957] [ERROR] Error handling request
/chatserver Traceback (most recent call last):
File "/home/ubuntu/env/lib/python3.8/site-packages/gunicorn/workers/sync.py", line 136, in handle
self.handle_request(listener, req, client, addr)
File "/home/ubuntu/env/lib/python3.8/site-packages/gunicorn/workers/sync.py", line 184, in handle_request
for item in respiter:
TypeError: 'coroutine' object is not iterable
Run Code Online (Sandbox Code Playgroud)
这是我的 aiohttp 服务器设置。
import socketio
from aiohttp import web
import aiohttp_cors
# create aiohttp application
app = web.Application()
# creates a new Async Socket IO Server
sio = socketio.AsyncServer(
cors_allowed_origins='*',
cors_credentials=True …Run Code Online (Sandbox Code Playgroud) 下面的示例仅将 1 个元素添加到事件循环中,并使用变量asins。
asyncio.exceptions.TimeoutError当asins下面的参数为 180 个元素或更长时,我收到错误。
如果我创建包含这 180 个元素中的任何一个的列表,我会得到成功的响应,这告诉我下面的问题与 API 无关。
谁能告诉我如何解决这个问题?谢谢你!
import asyncio
import aiohttp
import sys
import pandas as pd
def create_params(asins_set):
params = []
for asin in asins_set:
param = {
'api_key': '...',
'type': 'product',
'amazon_domain': 'amazon.com',
'asin': asin,
}
params.append(param)
return params
if sys.version_info[0] == 3 and sys.version_info[1] >= 8 and sys.platform.startswith('win'):
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
# creates a list of tasks to add to the event loop at once
def get_tasks(session, params):
tasks …Run Code Online (Sandbox Code Playgroud) aiohttp ×10
python ×9
async-await ×1
asynchronous ×1
coroutine ×1
httpx ×1
python-3.x ×1
tor ×1