Refactoring

This commit is contained in:
2022-05-01 21:14:35 +03:00
parent d625d7926b
commit 124ad5e533

View File

@@ -37,26 +37,27 @@ async def convert(
temp_filename = str(temp_uuid) + ".fb2" temp_filename = str(temp_uuid) + ".fb2"
converted_temp_filename = str(temp_uuid) + "." + format_lower converted_temp_filename = str(temp_uuid) + "." + format_lower
async with aiofiles.open(temp_filename, "wb") as f: try:
while content := await file.read(1024): async with aiofiles.open(temp_filename, "wb") as f:
if isinstance(content, str): while content := await file.read(1024):
content = content.encode() if isinstance(content, str):
content = content.encode()
await f.write(content) await f.write(content)
proc = await asyncio.create_subprocess_exec( proc = await asyncio.create_subprocess_exec(
"./bin/fb2c", "./bin/fb2c",
"convert", "convert",
"--to", "--to",
format, format,
temp_filename, temp_filename,
stdout=asyncio.subprocess.PIPE, stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE,
) )
_, stderr = await proc.communicate() _, stderr = await proc.communicate()
finally:
await aiofiles.os.remove(temp_filename) await aiofiles.os.remove(temp_filename)
if proc.returncode != 0 or len(stderr) != 0: if proc.returncode != 0 or len(stderr) != 0:
try: try:
@@ -69,11 +70,12 @@ async def convert(
) )
async def result_iterator() -> AsyncIterator[bytes]: async def result_iterator() -> AsyncIterator[bytes]:
async with aiofiles.open(converted_temp_filename, "rb") as f: try:
while data := await f.read(2048): async with aiofiles.open(converted_temp_filename, "rb") as f:
yield data while data := await f.read(2048):
yield data
await aiofiles.os.remove(converted_temp_filename) finally:
await aiofiles.os.remove(converted_temp_filename)
return StreamingResponse(result_iterator()) return StreamingResponse(result_iterator())