Skip to content

config.py

This file defines application settings, environment variables, and configuration parameters. It centralizes critical operational values, ensuring consistent behavior across different environments and modules. It also handles CORS origin parsing.

Scope

  • Defines application-wide configuration parameters.

  • Loads settings from environment variables and .env files.

  • Manages security-related keys and authentication parameters.

  • Provides email server connection details.

  • Parses and provides Cross-Origin Resource Sharing (CORS) origins.

File diagram - "config.py" /app/core/config.pyFile diagram - "config.py"  GlobalImportsBaseSettingsListos/app/core/config.pysettingsSettingsConfigSettings()SettingsDATABASE_URLSECRET_KEYALGORITHMACCESS_TOKEN_EXPIRE_MINUTESSMTP_HOSTSMTP_PORTSMTP_USERSMTP_PASSWORDSMTP_FROM_EMAILSMTP_FROM_NAMEAPP_NAMEAPP_VERSIONDEBUGCORS_ORIGINSRATE_LIMIT_ENABLEDRATE_LIMIT_REQUESTSRATE_LIMIT_PERIODLOG_LEVELLOG_FILEget_cors_origins() {property}Configenv_filecase_sensitive   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.
File diagram - "config.py" /app/core/config.pyFile diagram - "config.py"  GlobalImportsBaseSettingsListos/app/core/config.pysettingsSettingsConfigSettings()SettingsDATABASE_URLSECRET_KEYALGORITHMACCESS_TOKEN_EXPIRE_MINUTESSMTP_HOSTSMTP_PORTSMTP_USERSMTP_PASSWORDSMTP_FROM_EMAILSMTP_FROM_NAMEAPP_NAMEAPP_VERSIONDEBUGCORS_ORIGINSRATE_LIMIT_ENABLEDRATE_LIMIT_REQUESTSRATE_LIMIT_PERIODLOG_LEVELLOG_FILEget_cors_origins() {property}Configenv_filecase_sensitive   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.

Imports

  • BaseSettings from pydantic_settings

    This import provides the base class for defining application settings, enabling environment variable loading and validation for robust configuration management.

  • List from typing

    This import provides type hinting for lists, ensuring type safety and improving code readability and maintainability within the configuration class.

  • os

    This import provides a way to interact with the operating system, primarily used here for environment variable access, though pydantic_settings handles much of it.

Variables

  • settings

    This global instance of Settings provides a single point of access for all application configuration parameters, ensuring consistent and easily retrievable settings throughout the application.

Global Code

This line instantiates the Settings class, loading all configuration parameters from environment variables or .env file, making them accessible globally for application setup.

Schemas

Settings

This `Settings` schema defines application-wide configuration parameters for a blog platform. It manages database connections, security keys, email server details, and various operational settings. Essential for environment-specific deployments and ensuring consistent application behavior across different stages.

Schema diagram - "Settings" /app/core/config.pySchema diagram - "Settings"  SettingsDATABASE_URLSECRET_KEYALGORITHMACCESS_TOKEN_EXPIRE_MINUTESSMTP_HOSTSMTP_PORTSMTP_USERSMTP_PASSWORDSMTP_FROM_EMAILSMTP_FROM_NAMEAPP_NAMEAPP_VERSIONDEBUGCORS_ORIGINSRATE_LIMIT_ENABLEDRATE_LIMIT_REQUESTSRATE_LIMIT_PERIODLOG_LEVELLOG_FILEget_cors_origins() get_cors_originsorigin.strip()self.CORS_ORIGINS.split()   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.
Schema diagram - "Settings" /app/core/config.pySchema diagram - "Settings"  SettingsDATABASE_URLSECRET_KEYALGORITHMACCESS_TOKEN_EXPIRE_MINUTESSMTP_HOSTSMTP_PORTSMTP_USERSMTP_PASSWORDSMTP_FROM_EMAILSMTP_FROM_NAMEAPP_NAMEAPP_VERSIONDEBUGCORS_ORIGINSRATE_LIMIT_ENABLEDRATE_LIMIT_REQUESTSRATE_LIMIT_PERIODLOG_LEVELLOG_FILEget_cors_origins() get_cors_originsorigin.strip()self.CORS_ORIGINS.split()   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.

Base

BaseSettings

Fields

Name Type Optional Default Description
DATABASE_URL str false - Specifies the connection string for the application's primary database. This critical setting ensures proper data persistence and retrieval. It is a required configuration for the system to function correctly.
SECRET_KEY str false - A cryptographic key used for signing tokens and other security-sensitive operations. This vital secret must be kept confidential. It is absolutely essential for maintaining application security and integrity.
ALGORITHM str true "HS256" Defines the cryptographic algorithm used for signing JSON Web Tokens (JWTs). Defaults to `HS256`. This setting ensures consistent token generation and validation across the system, enhancing security.
ACCESS_TOKEN_EXPIRE_MINUTES int true 30 Sets the duration, in minutes, for which access tokens remain valid. Defaults to `30`. This controls session longevity, balancing security with user convenience for authentication.
SMTP_HOST str false - The hostname or IP address of the SMTP server used for sending email notifications. This is a crucial setting for enabling email functionalities like password resets.
SMTP_PORT int true 587 The port number for connecting to the SMTP server. Defaults to `587`, a common port for secure email submission. This ensures correct communication with the mail server.
SMTP_USER str false - The username required for authenticating with the SMTP server. This credential is vital for sending emails successfully. It must be configured for email features to work.
SMTP_PASSWORD str false - The password associated with the `SMTP_USER` for SMTP server authentication. This sensitive credential is required for secure email sending. It must be kept confidential.
SMTP_FROM_EMAIL str false - The email address that will appear as the sender for all outgoing application emails. This ensures consistent branding and proper email delivery.
SMTP_FROM_NAME str true "Blog Platform" The display name associated with the `SMTP_FROM_EMAIL` for outgoing messages. Defaults to `"Blog Platform"`. This enhances email professionalism and helps recipients identify the sender.
APP_NAME str true "Blog Platform API" The official name of the application, used in various user-facing contexts. Defaults to `"Blog Platform API"`. This provides consistent branding and identification throughout the system.
APP_VERSION str true "1.0.0" The current version string of the application. Defaults to `"1.0.0"`. This helps in tracking deployments, managing updates, and debugging specific application releases effectively.
DEBUG bool true False A boolean flag indicating whether the application is running in debug mode. Defaults to `False`. When `True`, it enables detailed logging and development features, but should be `False` in production.
CORS_ORIGINS str true "http://localhost:3000" A comma-separated string of allowed origins for Cross-Origin Resource Sharing (CORS). Defaults to `"http://localhost:3000"`. This controls which web domains can interact with the API securely.
RATE_LIMIT_ENABLED bool true True A boolean flag to enable or disable API rate limiting. Defaults to `True`. This helps protect the application from abuse and ensures fair usage by controlling request volume.
RATE_LIMIT_REQUESTS int true 100 The maximum number of requests allowed within a specified `RATE_LIMIT_PERIOD`. Defaults to `100`. This works with `RATE_LIMIT_PERIOD` to enforce API usage policies.
RATE_LIMIT_PERIOD int true 60 The time window, in seconds, during which `RATE_LIMIT_REQUESTS` applies. Defaults to `60`. This defines the duration for rate limiting, preventing excessive API calls.
LOG_LEVEL str true "INFO" Specifies the minimum severity level for logging messages. Defaults to `"INFO"`. This controls the verbosity of application logs, aiding in monitoring and debugging efforts.
LOG_FILE str true "logs/app.log" The file path where application logs will be written. Defaults to `"logs/app.log"`. This ensures persistent storage of log data for later analysis and troubleshooting purposes.

Methods

get_cors_origins

public

This property method retrieves and processes configured CORS origins from `self.CORS_ORIGINS`. It splits the comma-separated string into a list of individual origins, ensuring each entry is trimmed. This facilitates secure cross-origin resource sharing for web applications.
=== " "

Activity Diagram - "get_cors_origins" /app/core/config.pyActivity Diagram - "get_cors_origins"  Access self.CORS_ORIGINSSplit CORS_ORIGINS string by commaInitialize empty list for processed originsRemove leading and trailing whitespace from originAdd processed origin to the new listFor each origin string in the split listmore origin strings to process?return List of stripped origin strings   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.
Activity Diagram - "get_cors_origins" /app/core/config.pyActivity Diagram - "get_cors_origins"  Access self.CORS_ORIGINSSplit CORS_ORIGINS string by commaInitialize empty list for processed originsRemove leading and trailing whitespace from originAdd processed origin to the new listFor each origin string in the split listmore origin strings to process?return List of stripped origin strings   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.

Method diagram - "get_cors_origins" /app/core/config.pyMethod diagram - "get_cors_origins"  get_cors_originsorigin.strip()self.CORS_ORIGINS.split()   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.
Method diagram - "get_cors_origins" /app/core/config.pyMethod diagram - "get_cors_origins"  get_cors_originsorigin.strip()self.CORS_ORIGINS.split()   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.

Sequence Diagram - "get_cors_origins" Sequence Diagram - "get_cors_origins"  get_cors_originsCallerget_cors_originsCallerCallerget_cors_originsget_cors_originsget_cors_originsFunction Callget_cors_origins()Internal ProcessingAccess self.CORS_ORIGINS attributeSplit CORS_ORIGINS string by comma (",")loop[For each origin in the split list]Strip leading/trailing whitespace from originCollect stripped origins into a new listFunction ReturnReturn list of stripped origins/app/core/config.py   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.
Sequence Diagram - "get_cors_origins" Sequence Diagram - "get_cors_origins"  get_cors_originsCallerget_cors_originsCallerCallerget_cors_originsget_cors_originsget_cors_originsFunction Callget_cors_origins()Internal ProcessingAccess self.CORS_ORIGINS attributeSplit CORS_ORIGINS string by comma (",")loop[For each origin in the split list]Strip leading/trailing whitespace from originCollect stripped origins into a new listFunction ReturnReturn list of stripped origins/app/core/config.py   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.

Syntax

def get_cors_origins(self) -> List[str]:

Input Parameters

  • self (Any)

    Represents the instance of the class, providing access to its attributes and methods. It is implicitly passed when the method is called on an object, enabling interaction with the object's state and CORS_ORIGINS configuration.

Output / Return Values

  • origins_list (List[str])

    A List[str] containing individual CORS origin URLs, with leading/trailing whitespace removed. This list is used by web servers to determine which external domains are permitted to access resources, ensuring proper security configurations.

Logic / Execution Flow

  • Access the CORS_ORIGINS attribute from the class instance self.
  • Split the self.CORS_ORIGINS string by the comma (,) delimiter, creating a list of raw origin strings.
  • Iterate through each origin string in the newly created list.
  • For each origin, call the strip() method to remove any leading or trailing whitespace characters.
  • Collect all the stripped origin strings into a new List[str].
  • Return the final List[str] containing the cleaned CORS origins.

Usage Tips

  • Ensure self.CORS_ORIGINS is consistently formatted as a comma-separated string of URLs. This method relies on that specific format for correct parsing, preventing unexpected behavior or security misconfigurations in your application.

  • Utilize this property to dynamically configure your application's CORS middleware, allowing flexible and secure access control. Always verify the origins list against your deployment environment to prevent unauthorized access or legitimate access denials.

Additional Notes

  • The get_cors_origins property provides a convenient, read-only way to access processed CORS settings. It avoids direct string manipulation elsewhere, centralizing origin list generation for consistency across the application's security configurations.

  • This method assumes self.CORS_ORIGINS is already defined and accessible within the class instance. If CORS_ORIGINS is None or not a string, split() might raise an AttributeError or TypeError during execution.

FAQs

Why use pydantic_settings for configuration?

pydantic_settings provides robust type validation and automatic loading from environment variables or .env files, ensuring configuration integrity and simplifying deployment across different environments.

How are CORS origins handled?

CORS origins are provided as a comma-separated string in CORS_ORIGINS environment variable, then parsed into a list by the get_cors_origins property for easy use.

Why are sensitive credentials defined here?

Sensitive credentials like SECRET_KEY and SMTP_PASSWORD are defined here to centralize all environment-dependent settings, ensuring they are loaded securely from environment variables.

Insights

Metric Score Level
Complexity 0.20 Simple
Security 0.80 Secure
Performance 0.90 Optimised

Complexity

Low - Hardcoded APP_NAME and APP_VERSION

APP_NAME and APP_VERSION are hardcoded, which might lead to inconsistencies if not updated across deployments. External configuration is preferable.

Security

High - Hardcoded CORS_ORIGINS default

The CORS_ORIGINS default is hardcoded to http://localhost:3000, which is insecure for production environments and should be dynamically configured.

Medium - Hardcoded DEBUG default

The DEBUG flag defaults to False, which is good, but it should be explicitly set via environment variables in all environments.