Я пытаюсь передать клиенту ответ с процентом выполнения после обработки каждого файла в приведенном ниже коде, однако вижу ошибку ввода-вывода в закрытом файле для каждого из файлов.< /p>
Ответ, полученный от сервера:
data: {"progress": 0}
data: {"error": "Error processing file: I/O operation on closed file."}
data: {"error": "Error processing file: I/O operation on closed file."}
data: {"progress": 100}
Мой пример
@app.post("/test-streaming")
async def upload_file_streaming(files: list[UploadFile]):
return StreamingResponse(
stream_response(files),
media_type="text/event-stream"
)
async def extract(files) -> AsyncGenerator[str, None]:
total_files = len(files)
for index, file in enumerate(files):
try:
with pdfplumber.open(file.file) as pdf:
# Simulate processing each page of the PDF
for page in pdf.pages:
text = page.extract_text() # Replace with actual processing logic
await asyncio.sleep(0.5) # Simulate processing delay
# Calculate and yield progress
progress = int(((index + 1) / total_files) * 100)
yield f"data: {{\"progress\": {progress}}}\n\n"
except Exception as e:
yield f"data: {{\"error\": \"Error processing file: {str(e)}\"}}\n\n"
async def stream_response(files: list[UploadFile]) -> AsyncGenerator[str, None]:
yield "data: {\"progress\": 0}\n\n" # Initial progress
async for update in extract(files):
yield update
yield "data: {\"progress\": 100}\n\n"
Я даже пытался прочитать весь файл в памяти, выполнив указанные ниже действия, однако вижу ту же ошибку
pdf_bytes = await file.read()
with pdfplumber.open(io.BytesIO(pdf_bytes)) as pdf:..
Подробнее здесь: https://stackoverflow.com/questions/793 ... om-fastapi
Операция ввода-вывода в закрытом файле при потоковой передаче ответа от Fastapi ⇐ Python
Программы на Python
1734986824
Anonymous
Я пытаюсь передать клиенту ответ с процентом выполнения после обработки каждого файла в приведенном ниже коде, однако вижу ошибку ввода-вывода в закрытом файле для каждого из файлов.< /p>
Ответ, полученный от сервера:
data: {"progress": 0}
data: {"error": "Error processing file: I/O operation on closed file."}
data: {"error": "Error processing file: I/O operation on closed file."}
data: {"progress": 100}
Мой пример
@app.post("/test-streaming")
async def upload_file_streaming(files: list[UploadFile]):
return StreamingResponse(
stream_response(files),
media_type="text/event-stream"
)
async def extract(files) -> AsyncGenerator[str, None]:
total_files = len(files)
for index, file in enumerate(files):
try:
with pdfplumber.open(file.file) as pdf:
# Simulate processing each page of the PDF
for page in pdf.pages:
text = page.extract_text() # Replace with actual processing logic
await asyncio.sleep(0.5) # Simulate processing delay
# Calculate and yield progress
progress = int(((index + 1) / total_files) * 100)
yield f"data: {{\"progress\": {progress}}}\n\n"
except Exception as e:
yield f"data: {{\"error\": \"Error processing file: {str(e)}\"}}\n\n"
async def stream_response(files: list[UploadFile]) -> AsyncGenerator[str, None]:
yield "data: {\"progress\": 0}\n\n" # Initial progress
async for update in extract(files):
yield update
yield "data: {\"progress\": 100}\n\n"
Я даже пытался прочитать весь файл в памяти, выполнив указанные ниже действия, однако вижу ту же ошибку
pdf_bytes = await file.read()
with pdfplumber.open(io.BytesIO(pdf_bytes)) as pdf:..
Подробнее здесь: [url]https://stackoverflow.com/questions/79304181/i-o-operation-on-closed-file-while-streaming-a-response-from-fastapi[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия