[Python] Sending real-time upload progress over websocket FastAPI

Discussão em 'Python' iniciado por Stack, Dezembro 6, 2024.

  1. Stack

    Stack Membro Participativo

    I am building a backend with FastAPI in which i am planning to recieve large files from client on the server and then send it to discord.

    I want something like when user is uploading the data i want to show a real-time progress to but i am having hard time doing so i can achive something like

    When user uploads the file it updates user after each chunk is sent to discord but not real-time

    This progress could be any.

    1. from user to server
    2. from server to discord

    If one any of this 2 can be achived. It would work

    while True:
    try:
    chunk = await file.read(CHUNK_SIZE)
    if not chunk:
    break
    chunk_id += 1
    total_size += len(chunk)
    message_id = await bot.upload_chunk(chunk, file.filename, chunk_id)
    try:
    await manager.send_message(f"Uploaded {total_size} bytes")
    except Exception as e:
    # logging.error(f"Failed to send WebSocket message: {e}")
    print(f"Failed to send WebSocket message: {e}")

    chunk_entry = FileChunk(
    file_name=file.filename,
    chunk_id=chunk_id,
    discord_message_id=message_id,
    folder_id=folder_id
    )
    db.add(chunk_entry)
    uploaded_chunks.append(chunk_entry)
    except Exception as e:
    raise HTTPException(status_code=500, detail=f"Error uploading chunk {chunk_id}: {str(e)}")

    await db.commit()
    try:
    await manager.send_message("Upload complete")
    except Exception as e:
    # logging.error(f"Failed to send WebSocket completion message: {e}")
    print(f"Failed to send WebSocket completion message: {e}")
    return {
    "message": "File uploaded successfully",
    "filename": file.filename,
    "chunks": chunk_id
    }


    Here is the code snippet that could help you.

    Continue reading...

Compartilhe esta Página