class YourSpecialServiceResponse(AsyncResponse):
...
chunks = []
async def send(chunk):
chunks.append(chunk)
class Stream:
def __init__(self, data):
self.index = 0
self.data = data
self.data_len = len(data)
async def read(self, chunk_size):
if self.index + chunk_size >= self.data_len:
chunk = self.data[self.index :]
else:
chunk = self.data[self.index : self.index + chunk_size]
self.index += chunk_size
return chunk
content = "1234567890"
stream = Stream(content)
response = AsyncResponse(chunk_size=3)
await response.send_stream_to_client(stream, send)
sent_body = "".join([c["body"] for c in chunks if "body" in c])
assert content == sent_body
response = AsyncResponse(chunk_size=3)
assert len(response.response_headers) > 0
AiofileFileResponse
Serve a file asynchronously using aiofiles.
from fileresponse.http import AiofileFileResponse
async def aget_file(request, num=None):
file_path = Path(__file__).parent.parent / "data" / str(num)
return AiofileFileResponse(file_path, chunk_size=4096)
import os
from pathlib import Path
path = Path("testdata.bin")
with path.open("wb") as f:
f.write(os.urandom(10000))
with path.open("rb") as f:
content = f.read()
chunk_datas = []
async def send(chunk_data):
chunk_datas.append(chunk_data)
response = AiofileFileResponse(path)
await response.stream(send)
received_content = b"".join([cd.get("body", b"") for cd in chunk_datas])
assert content == received_content
response = AiofileFileResponse("foobar")
assert "<AiofileFileResponse status_code=200>" == repr(response)
AiobotocoreFileResponse
Serve a file asynchronously using aiobotocore.
import django
try:
settings.configure()
except RuntimeError:
pass
def configure_settings():
settings.FILERESPONSE_S3_ENDPOINT_URL = "asdf"
settings.FILERESPONSE_S3_REGION = "asdf"
settings.FILERESPONSE_S3_ACCESS_KEY_ID = "asdf"
settings.FILERESPONSE_S3_SECRET_ACCESS_KEY = "asdf"
configure_settings()
response = AiobotocoreFileResponse("bucket", "key")
assert "<AiobotocoreFileResponse status_code=200>" == repr(response)
configure_settings()
expected_endpoint_url = "http://foobar:9000/"
settings.FILERESPONSE_S3_ENDPOINT_URL = "asdf"
response = AiobotocoreFileResponse("bucket", "key", endpoint_url=expected_endpoint_url)
assert expected_endpoint_url == response.client_config["endpoint_url"]