Utils / Load Request File

Documentation

On this page

    #Overview

    The LoadRequestFile class was developed to make the process of loading and validating files sent in requests through FastAPI easier. It ensures that the received file has an allowed extension and MIME type, and checks that its size is within a configured limit, avoiding problems such as improper uploads or very large files that could compromise the system.

    In practice, this class can be used to safely control which files an application accepts for processing, protecting the backend against unexpected or malicious input. For example, it can be used in APIs where users upload images, documents or other files, ensuring compliance with the defined rules.

    #Execution Flow

    1. An instance of the class is created by passing the request's UploadFile object and, optionally, lists of allowed extensions and MIME types, plus the maximum allowed size.
    2. The load() method is called asynchronously to read the content of the request's file.
    3. During loading, the class calculates the file size in bytes and megabytes and keeps a copy of the content in a BytesIO object, making future access easier.
    4. Next, the file is validated against the lists of allowed extensions and MIME types, and its size is checked to make sure it does not exceed the configured limit.
    5. If any validation fails, an HTTP 400 exception is raised with a clear message about the reason.
    6. If all validations pass, the instance with the file's information and content is returned, ready for later use in the application flow.

    #Class Methods Table

    MethodDescription
    __init__Initializes the instance with the file, settings and basic data.
    loadLoads the file content, calculates metadata and performs validations.
    to_dictReturns a dictionary with information about the loaded file.

    #Important Architecture Points and Insights

    • The class fully encapsulates the loading and validation logic, promoting reuse and a clear separation of responsibilities.
    • Using the BytesIO module makes it possible to work with the file content in memory without needing to save it to disk, increasing efficiency.
    • The design uses specific validations and raises HTTP exceptions directly, integrating easily with FastAPI's error handling flow.
    • It depends on external settings for the allowed extensions and MIME types, giving flexibility for adjustments without changing the source code.
    • The modular architecture allows simple extension, for example by adding other validations without changing the public interface.

    #Class and Methods Description

    #LoadRequestFile Class

    #Description

    LoadRequestFile is a utility for handling files sent via an HTTP request with FastAPI. It is responsible for loading the received file, extracting information such as extension, MIME type and size, and validating that the file is within the allowed standards configured for the system.

    #Constructor Arguments

    ArgumentTypeDescriptionDefault Value
    fileUploadFileFile sent in the request to be loaded and validated.None (required)
    allowed_extensionslist[str]List of extensions allowed for validation.ALLOWED_EXTENSIONS
    allowed_mimetypeslist[str]List of MIME types allowed for validation.ALL_MIMETYPES
    max_size_mbfloatMaximum size allowed for the file in megabytes.10

    #Methods

    #1. __init__

    #Description

    Initializes an instance of the class with the received file and the validation settings, preparing attributes for loading and future validations.

    #Arguments

    • file (UploadFile): File sent in the request.
    • allowed_extensions (list[str]): Allowed extensions. Default: ALLOWED_EXTENSIONS.
    • allowed_mimetypes (list[str]): Allowed MIME types. Default: ALL_MIMETYPES.
    • max_size_mb (float): Maximum size allowed (in MB). Default: 10.

    #Returns

    • Does not return a value.

    #Raises

    • None.

    #Examples

    # Criar uma instância para validar arquivo recebido e configurar limites
    loader = LoadRequestFile(file, max_size_mb=5)

    #2. load

    #Description

    Asynchronous method that loads the entire content of the file, calculates its size in bytes and megabytes, stores the data in memory and performs all the established validations (extension, MIME type and size).

    #Arguments

    • None.

    #Returns

    • LoadRequestFile: returns the instance itself with loaded and validated data.

    #Raises

    • HTTPException: if any validation fails, with status 400 and an informative message.

    #Examples

    # Uso assíncrono: carregar e validar arquivo recebido na requisição
    loader = await LoadRequestFile(file).load()
    print(loader.to_dict())
    # Exemplo de saída:
    # {
    #   "filename": "photo.jpg",
    #   "extension": "jpg",
    #   "mimetype": "image/jpeg",
    #   "size_bytes": 152000,
    #   "size_mb": 0.15
    # }

    #3. to_dict

    #Description

    Generates a dictionary with the main metadata of the loaded file, making inspection and eventual logging or API response easier.

    #Arguments

    • None.

    #Returns

    • dict: containing filename, extension, mimetype, size_bytes and rounded size_mb.

    #Raises

    • None.

    #Examples

    # Obter informações resumidas sobre o arquivo carregado
    info = loader.to_dict()
    print(info["filename"])  # ex: "document.pdf"
    print(info["size_mb"])   # ex: 2.45

    Source: src/utils/load_file/load_request_file.py

    Esc
    ↑↓navigate Enteropen