-
Hi,
from starlette.requests import Request
from starlette.responses import Response
async def create_file(background_tasks: BackgroundTasks, request: Request):
async for chunk in request.stream():
print(chunk)
with open(wav_filename, mode='bx') as f:
f.write(chunk)
This is the output of the print command
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 3 replies
-
A couple issues I'm seeing at first glance You're receiving multipart dataWhen you receive data from the client it's always a stream of bytes (think of it like a list/array where each element is a character, except binary so it's really just a number, hence the hexadecimal numbers you're seeing in your stream). But in this case it is a from starlette.requests import Request
from starlette.responses import Response
async def create_file( request: Request):
form = await request.form()
file = form["file"]
print(await file.read()) You are overwriting the file you createWhen you do this: async for chunk in request.stream():
print(chunk)
with open(wav_filename, mode='bx') as f:
f.write(chunk) You are re-opening with open(wav_filename, mode='bx') as f:
async for chunk in request.stream():
f.write(chunk) Putting it all togetherfrom starlette.requests import Request
from starlette.responses import Response
async def create_file( request: Request):
form = await request.form()
file = form["file"]
chunk_size = 1024*1024
try:
with open(wav_filename, mode='bx') as f:
chunk = await file.read(chunk_size)
if not chunk:
return
f.write(chunk)
finally:
await file.aclose() |
Beta Was this translation helpful? Give feedback.
A couple issues I'm seeing at first glance
You're receiving multipart data
When you receive data from the client it's always a stream of bytes (think of it like a list/array where each element is a character, except binary so it's really just a number, hence the hexadecimal numbers you're seeing in your stream).
But in this case it is a
multipart/form-data
request. This is special encoding that allows multiple files to be sent in a single list. The basic idea is to insert a delimiter in between the files, which in your case is the--------------------------e4462b3dae0007d5
at the beginning of the file. It looks like your actual file is the form field calledfile
. You can extract it like t…