Skip to content

Source Utils

Utility functions for downloading files from various sources.

encode_file_to_base64(file_binary)

Convert binary file data to base64 string.

Parameters:

Name Type Description Default
file_binary bytes

Binary data of the file.

required

Returns:

Name Type Description
str str

Base64 encoded string.

get_file_from_file_path(source)

Read image file and return its binary data if valid.

Parameters:

Name Type Description Default
source str

Path to the image file.

required

Returns:

Type Description
bytes | None

bytes | None: Binary data of the image file if valid, None otherwise.

get_file_from_url(file_source, timeout=30, session=None) async

Asynchronously download and validate an image from a URL.

This function performs the following steps: 1. Attempts to download the content from the provided URL. 2. Validates that the downloaded content is a valid image. 3. Returns the binary data if both steps succeed.

Parameters:

Name Type Description Default
file_source str

The URL of the file to download. Supports HTTP and HTTPS protocols.

required
timeout int

The timeout for the HTTP request in seconds. Defaults to 30 seconds.

30
session Optional[ClientSession]

An existing aiohttp session to use. If None, a new session will be created. Defaults to None.

None

Returns:

Type Description
bytes | None

bytes | None: The downloaded image binary data if successful and valid, None if the download fails or the content is not a valid image.