[Python] How do I return a FileResponse (or StreamingResponse) in flet-fastapi?

Discussão em 'Python' iniciado por Stack, Fevereiro 23, 2025.

  1. Stack

    Stack Membro Participativo

    I'm actually trying to create a web-app that would ask a person some info, then edit \*.docx with jinja and return this \*.docx to the person as a download.

    I'm having trouble making flet-fastapi return a FileResponse. My workdir looks like this:

    __pycache__/
    .venv/
    output/
    output/test.docx
    main.py
    requirements.txt


    requirements.txt:

    flet-fastapi
    flet
    uvicorn
    pydantic
    fastapi


    main.py:

    from contextlib import asynccontextmanager
    import flet as ft
    import flet_fastapi
    from fastapi import FastAPI
    from fastapi.responses import FileResponse

    @asynccontextmanager
    async def lifespan(app=FastAPI):
    await flet_fastapi.app_manager.start()
    yield
    await flet_fastapi.app_manager.shutdown()

    app = FastAPI(lifespan=lifespan)

    # I believe that it doesn't matter which endpoint we choose here, since later we mount
    # our flet on the root-path. Decorator is here because without it "return FileResponse()"
    # does nothing at all.
    @app.get("/")
    async def dl_test(page: ft.Page):
    async def download(e):
    return FileResponse(f"output/test.docx", media_type="application/vnd.openxmlformats-officedocument.wordprocessingml.document", filename="test.docx")
    await page.add_async(ft.OutlinedButton(text="Get file", on_click=download))
    await page.update_async()

    app.mount("/", flet_fastapi.app(dl_test))


    This code is the minimal reproducible example. To reproduce it, we can prepare our virtual environment:

    python -m venv .venv
    source .venv/bin/activate
    pip install -r requirements.txt


    And then run it:

    uvicorn --reload main:app


    As we run it, we can see an exception:


    fastapi.exceptions.FastAPIError: Invalid args for response field! Hint: check that <class 'flet_core.page.Page'> is a valid Pydantic field type. If you are using a return type annotation that is not a valid Pydantic field (e.g. Union[Response, dict, None]) you can disable generating the response model from the type annotation with the path operation decorator parameter response_model=None.
    ​

    How can we make return FileResponse() working?

    Continue reading...

Compartilhe esta Página