限制HTTP POST上传带宽
在我的应用程序中,我正在将价值几十兆的视频连续上传到云中的服务器。
[上传部分已使用python aiohttp编写,而云中的接收部分使用node.js和“请求”库。
我想将HTTP上传的带宽限制为1Mbps或更小。
这在HTTP协议中甚至可能吗?我应该在客户端(上载者)还是服务器(接收者)端执行此操作?
[曾经做过很多谷歌搜索,但结果大多涉及“速率限制”,这完全是另一回事。
感谢帮助。
回答如下:针对我的评论。您正在对上载POST或GET请求进行分块并对其进行限制,这是在服务器端完成的。aiohttp Python示例:https://github/aio-libs/aiohttp/issues/2638
import aiohttp
import asyncio
async def read(self, n: int=-1) -> bytes:
"""Read up to 'n' bytes of the response payload.
If 'n' is -1 (default), read the entire payload.
"""
if self._body is None:
try:
if n is -1:
self._body = await self.content.read()
else:
chunks = []
i = 0
while i < n:
chunk = await self.content.read(n=n - i)
if not chunk:
break
chunks.append(chunk)
i += len(chunk)
self._body = b''.join(chunks)
for trace in self._traces:
await trace.send_response_chunk_received(self._body)
except BaseException:
self.close()
raise
elif self._released:
raise aiohttp.ClientConnectionError('Connection closed')
return self._body
async def f(url, n=-1):
async with aiohttp.ClientSession() as session:
async with session.get(url) as response:
content = await read(response, n=n)
print(len(content))
URL = 'https://upload.wikimedia/wikipedia/commons/thumb/7/71/2010-kodiak-bear-1.jpg/320px-2010-kodiak-bear-1.jpg'
asyncio.run(f(URL, 10_000_000)) # 10 MB
asyncio.run(f(URL, 100))
asyncio.run(f(URL))
限制HTTP POST上传带宽
在我的应用程序中,我正在将价值几十兆的视频连续上传到云中的服务器。
[上传部分已使用python aiohttp编写,而云中的接收部分使用node.js和“请求”库。
我想将HTTP上传的带宽限制为1Mbps或更小。
这在HTTP协议中甚至可能吗?我应该在客户端(上载者)还是服务器(接收者)端执行此操作?
[曾经做过很多谷歌搜索,但结果大多涉及“速率限制”,这完全是另一回事。
感谢帮助。
回答如下:针对我的评论。您正在对上载POST或GET请求进行分块并对其进行限制,这是在服务器端完成的。aiohttp Python示例:https://github/aio-libs/aiohttp/issues/2638
import aiohttp
import asyncio
async def read(self, n: int=-1) -> bytes:
"""Read up to 'n' bytes of the response payload.
If 'n' is -1 (default), read the entire payload.
"""
if self._body is None:
try:
if n is -1:
self._body = await self.content.read()
else:
chunks = []
i = 0
while i < n:
chunk = await self.content.read(n=n - i)
if not chunk:
break
chunks.append(chunk)
i += len(chunk)
self._body = b''.join(chunks)
for trace in self._traces:
await trace.send_response_chunk_received(self._body)
except BaseException:
self.close()
raise
elif self._released:
raise aiohttp.ClientConnectionError('Connection closed')
return self._body
async def f(url, n=-1):
async with aiohttp.ClientSession() as session:
async with session.get(url) as response:
content = await read(response, n=n)
print(len(content))
URL = 'https://upload.wikimedia/wikipedia/commons/thumb/7/71/2010-kodiak-bear-1.jpg/320px-2010-kodiak-bear-1.jpg'
asyncio.run(f(URL, 10_000_000)) # 10 MB
asyncio.run(f(URL, 100))
asyncio.run(f(URL))