Utils

Loader Files

Here is the didactic documentation of the FilesPayloadBuilder class, structured to make it easier for developers and integrators to understand.

On this page

    #1. Overview

    The FilesPayloadBuilder class acts as a security filter and data transformer at the input layer of your API. When a user sends files through FastAPI, they arrive as UploadFile objects.

    This class ensures that those files do not "break" the server by being too large or by having malicious or unsupported formats. After validation, it turns the raw data into a Python dictionary (payload) that is easy to handle by other parts of the system, such as image processing services or databases.

    #2. Execution Flow

    The processing flow of a file follows this logical path:

    1. Receiving: The API receives a list of files via form (Multipart).
    2. Asynchronous Reading: The file content is read from memory or temporary disk in a non-blocking way (await f.read()).
    3. Type Check: The system checks whether the content_type (e.g. image/png) is in the list of allowed types.
    4. Weight Check: The total size of the bytes read is compared with the configured limit (e.g. 10MB).
    5. Structuring: If everything is correct, the data is organized into a dictionary. If something fails, an HTTP exception is raised immediately, interrupting the process to protect the server.

    #3. Methods Summary

    MethodTypeShort Description
    __init__ConstructorSets up the business rules (maximum size and accepted types).
    build_images_payloadCoroutine (async)Validates the list of files and generates the final data structure.

    #4. Architecture and Insights

    • Reactive Security: By validating the size and MIME type right at the entrance, you avoid "Denial of Service" (DoS) attacks through the upload of giant files.
    • Using a Set for Performance: The allowed_types variable is converted to a set. In Python, checking whether an item exists in a set is much faster than in a list or tuple, especially if the list of formats grows.
    • FastAPI Integration: Using HTTPException allows validation errors to be returned directly to the end user with appropriate status codes (400 Bad Request), without the need for extra try/except blocks in the API route.

    #5. Class Details

    #FilesPayloadBuilder Class

    Description
    Responsible for validating the integrity of files sent via upload and preparing them for internal processing. It centralizes the rules of "what can come in" to the system in terms of media files.

    Arguments

    • max_mb (int): The maximum size allowed for each individual file in Megabytes.
    • allowed_types (Iterable[str]): A collection of strings representing the accepted MIME types (e.g. ["image/jpeg", "application/pdf"]).

    #Methods

    #1. build_images_payload

    Description
    This is the heart of the class. It goes through each uploaded file, reads its binary content and checks whether it meets the security requirements defined in the constructor.

    Arguments

    • files (List[UploadFile]): A list of file objects coming from a FastAPI endpoint.

    Returns

    • list[dict]: A list of dictionaries, where each dictionary contains:
      • filename: Original name of the file.
      • content_type: Format of the file.
      • size_bytes: Real size in bytes.
      • bytes: The raw binary content.

    Raises

    • HTTPException (400): Raised if the file format is not allowed.
    • HTTPException (400): Raised if the file exceeds the configured Megabyte limit.

    Examples

    builder = FilesPayloadBuilder(max_mb=2, allowed_types=["image/png"])
    
    # Em uma rota FastAPI
    @app.post("/upload")
    async def upload_image(files: List[UploadFile]):
        payload = await builder.build_images_payload(files)
        return {"status": "sucesso", "arquivos_processados": len(payload)}

    Source: src/utils/loader_files.py

    Esc
    ↑↓navigate Enteropen