我认为它ayncio的使用coroutine与线程无关,因为coroutine它是在程序调度程序下运行的一种“线程”,所以每个进程应该只有1个线程运行。但是当我运行使用 python-aiohttp 发出 100 万个请求中的示例时,代码如下所示:
# modified fetch function with semaphore
import random
import asyncio
from aiohttp import ClientSession
async def fetch(url, session):
async with session.get(url) as response:
delay = response.headers.get("DELAY")
date = response.headers.get("DATE")
print("{}:{} with delay {}".format(date, response.url, delay))
return await response.read()
async def bound_fetch(sem, url, session):
# Getter function with semaphore.
async with sem:
await fetch(url, session)
async def run(r):
url = "http://localhost:8080/{}"
tasks = []
# create instance of …Run Code Online (Sandbox Code Playgroud) 我在 nginx 后面使用 aiohttp ( http://aiohttp.readthedocs.io/en/stable/ ) 和 https:
我尝试在aiohttp中间件中获取IP:
peername = request.transport.get_extra_info('peername')
host, port, = (peername if peername is not None else ('',''))
Run Code Online (Sandbox Code Playgroud)
我期望真实的 IP,但它总是返回 127.0.0.1 这个问题的原因是什么以及如何解决?
我的 nginx 配置:
upstream site_python {
ip_hash;
server 127.0.0.1:8080;
server 127.0.0.1:8081;
server 127.0.0.1:8082;
server 127.0.0.1:8083;
}
server {
listen 11.111.11.111:80;
server_name www.example.com example.com;
rewrite ^ https://$server_name$request_uri? permanent;
}
server {
listen 11.111.11.111:443 ssl;
ssl_certificate /home/site/ssl/www_site_ru.crt;
ssl_certificate_key /home/site/ssl/561457962.key;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_ciphers HIGH:!aNULL:!MD5;
server_name www.example.com;
# rewrite ^ http://www.example.com$request_uri permanent;
if ($host …Run Code Online (Sandbox Code Playgroud) 我有一个简单的命令和控制服务器server.py(完全不安全 - 不要使用),一个被动客户端update_client.py和另一个可以发送命令的客户端update_commander.py。http://0.0.0.0:8080/处有一个 http 端点,其中列出了已连接的客户端。当update_commander.py脚本退出时,其客户端会被正确清理。当 update_client.py断开连接时,服务器不会注意到断开连接,并且在发送进一步的消息后,我update_commander.py会收到每个幽灵客户端连接的错误socket.send() raised exception.。清理代码标记为### CLEANUP CODE ###
我觉得我应该做的是,当我尝试发送到套接字但没有引发异常,只是向标准输出发送一条消息时捕获错误。
服务器.py
import uuid
import asyncio
import aiohttp
from aiohttp import web
class Client(object):
def __init__(self):
self.websocket = None
self.name = None
class ClientList(web.View):
async def get(self):
clients = self.request.app['clients']
client_list = [client.name for name, client in clients.items()]
txt = ", ".join(client_list)
return web.Response(text=txt)
class WebSocket(web.View):
async def get(self):
ws = web.WebSocketResponse()
await …Run Code Online (Sandbox Code Playgroud) 我试图同时请求一堆 URL,但 URL 是从列表构建的。目前,我正在循环列表并(我认为)将它们添加到队列中。它肯定比 requests.get 快 10 倍,但是我不确定我是否正确执行,因此可以对其进行优化。我对其进行了分析,发现在并发请求完成后,90% 的时间它仍然处于锁定状态,即开始 -> 10+ 并发请求 -> 锁定 5 秒左右 -> 完成
Unclosed client session此外,此代码最后会生成一条消息。知道为什么吗?很确定这是正确使用上下文管理器。
我已经搜索过但没有找到这个确切的问题
import signal
import sys
import asyncio
import aiohttp
import json
import requests
lists = ['eth', 'btc', 'xmr', 'req', 'xlm', 'etc', 'omg', 'neo', 'btc', 'xmr', 'req', 'xlm', 'etc', 'omg', 'neo']
loop = asyncio.get_event_loop()
client = aiohttp.ClientSession(loop=loop)
async def fetch(client, url):
async with client.get(url) as resp:
assert resp.status == 200
return await resp.text()
async def main(loop=loop, url=None):
async with …Run Code Online (Sandbox Code Playgroud) 当我阅读aiohttp服务器文档时,我遇到了这个
警告 仅将 add_static() 用于开发。在生产中,静态内容应该由 nginx 或 apache 等 Web 服务器处理。
为什么我们不能用来aiohttp提供静态文件?
我有一个脚本可以检查数十万个提供的网站的状态代码,并且我试图将信号量集成到流程中以加快处理速度。问题是,每当我集成信号量时,我只会得到一个填充有 None 对象的列表,而且我不完全确定为什么。
我主要是从其他来源复制代码,因为我还没有完全理解异步编程,但似乎当我调试时我应该从函数中获取结果,但当我收集结果时出现了问题。我尝试过在循环、收集、确保未来等方面进行杂耍,但似乎没有什么能返回有效的事情列表。
async def fetch(session, url):
try:
async with session.head(url, allow_redirects=True) as resp:
return url, resp.real_url, resp.status, resp.reason
except Exception as e:
return url, None, e, 'Error'
async def bound_fetch(sem, session, url):
async with sem:
await fetch(session, url)
async def run(urls):
timeout = 15
tasks = []
sem = asyncio.Semaphore(100)
conn = aiohttp.TCPConnector(limit=64, ssl=False)
async with aiohttp.ClientSession(connector=conn) as session:
for url in urls:
task = asyncio.wait_for(bound_fetch(sem, session, url), timeout)
tasks.append(task)
responses = await asyncio.gather(*tasks)
# responses = [await …Run Code Online (Sandbox Code Playgroud) 我正在尝试从我使用包装器的 api 获得一些响应。
我寻找了更多错误,但他们没有解决我的问题。我不太了解 await 函数或协程。我关闭了 is_asnyc,它起作用了,但我需要那个选项。所以我不能关闭它。
import clashroyale, asyncio
token = "my token"
cr = clashroyale.official_api.Client(token=token, is_async=True)
async def top():
p = await cr.get_top_players()
return p
topplayers = asyncio.run(top())
Run Code Online (Sandbox Code Playgroud)
我排除了它只是从api获取信息但出现错误-
RuntimeError: Timeout context manager should be used inside a task
Unclosed client session
client_session: <aiohttp.client.ClientSession object at 0x000001774361A3C8>
Run Code Online (Sandbox Code Playgroud) 我目前正在开发一个 django 项目,我使用 aiohttp 在后端和前端之间进行通信。我想在前端发出请求时获取客户端的 IP 地址。查看了不同的文档,但似乎没有一个文档明确指出如何使用 aiohttp 获取 IP 地址。有人帮忙!
from aiohttp import web
async def handler(request):
ws = web.WebSocketResponse()
await ws.prepare(request)
try:
async for msg in ws:
# handle incoming messages
# use ws.send_str() to send data back
...
finally:
task.cancel()
Run Code Online (Sandbox Code Playgroud) 我正在尝试使用 asyncio 从数千个 url 中获取一些数据。以下是该设计的简要概述:
Queue一次性填写一堆网址ProducerConsumersConsumer保持异步从请求中提取 urlQueue并发送GET请求问题: asyncio几乎从不显示是否有任何问题,它只是默默地挂起而没有错误。我在print各处放置语句来自己检测问题,但这并没有多大帮助。
根据输入网址的数量和消费者的数量或限制,我可能会收到以下错误:
Task was destroyed but it is pending!task exception was never retrieved future: <Task finished coro=<consumer()aiohttp.client_exceptions.ServerDisconnectedErroraiohttp.client_exceptions.ClientOSError: [WinError 10053] An established connection was aborted by the software in your host machine问题:如何检测和处理中的异常asyncio?如何在不中断的情况下重试Queue?
Bellow 是我在查看异步代码的各种示例时编译的代码。目前,def get_video_title函数末尾存在故意错误。运行时,什么都不显示。
import asyncio
import aiohttp
import json
import re
import nest_asyncio
nest_asyncio.apply() …Run Code Online (Sandbox Code Playgroud) 我的项目使用 socket.io 发送/接收数据。
我添加了 aiohttp 来帮助在浏览器上显示结果。
import asyncio
from aiohttp import web
sio = socketio.AsyncServer(async_mode='`aiohttp`')
app = web.Application()
sio.attach(app)
Run Code Online (Sandbox Code Playgroud)
我按照 https://us-pycon-2019-tutorial.readthedocs.io/aiohttp_file_uploading.html 上传图片,但无法上传视频。
def gen1():
# while True:
# if len(pm.list_image_display) > 1 :
image = cv2.imread("/home/duong/Pictures/Chess_Board.svg")
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
# img = PIL.Image.new("RGB", (64, 64), color=(255,255,0))
image_pil = PIL.Image.fromarray(image)
fp = io.BytesIO()
image_pil.save(fp, format="JPEG")
content = fp.getvalue()
return content
async def send1():
print("11")
return web.Response(body=gen1(), content_type='image/jpeg')
Run Code Online (Sandbox Code Playgroud)
如何在浏览器上通过 aiohttp 显示视频?
aiohttp ×10
python ×8
python-3.x ×3
asynchronous ×2
async-await ×1
django ×1
exception ×1
nginx ×1
queue ×1
websocket ×1