[Python] How do I post multipart form data with pytest TestClient?

Discussão em 'Python' iniciado por Stack, Março 28, 2025.

  1. Stack

    Stack Membro Participativo

    I struggled with this problem for 3 hours, and the only working solution I found was as follows:

    from main.app import app
    client = TestClient(app)
    with open(file_to_open, 'rb') as openfile:
    response = await client.post(
    "/somesite",
    files={
    file_content" : (open_file.name, open_file,
    application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'),
    some_field" : str(45),
    another_field" : "ICT",
    another_other_field": str(54),
    }
    )


    The complication around this issue was specifically around the pydantic schema on my fastapi not being able to understand the multipart form data prior to this solution.

    This solution made me realize that the function doesn't accept any integer values in the 'files' dict. Hope this helps someone out!

    Continue reading...

Compartilhe esta Página