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
.envfiles. -
Manages security-related keys and authentication parameters.
-
Provides email server connection details.
-
Parses and provides Cross-Origin Resource Sharing (CORS) origins.
Imports
-
BaseSettings from pydantic_settingsThis import provides the base class for defining application settings, enabling environment variable loading and validation for robust configuration management.
-
List from typingThis import provides type hinting for lists, ensuring type safety and improving code readability and maintainability within the configuration class.
-
osThis import provides a way to interact with the operating system, primarily used here for environment variable access, though
pydantic_settingshandles much of it.
Variables
settingsThis global instance of
Settingsprovides 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.
BaseSettings
| 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.
def get_cors_origins(self) -> List[str]:
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_ORIGINSconfiguration.
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.
- Access the
CORS_ORIGINSattribute from the class instanceself. - Split the
self.CORS_ORIGINSstring by the comma (,) delimiter, creating a list of raw origin strings. - Iterate through each
originstring in the newly created list. - For each
origin, call thestrip()method to remove any leading or trailing whitespace characters. - Collect all the stripped
originstrings into a newList[str]. - Return the final
List[str]containing the cleaned CORS origins.
Usage Tips
-
Ensure
self.CORS_ORIGINSis 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_originsproperty 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_ORIGINSis already defined and accessible within the class instance. IfCORS_ORIGINSisNoneor not a string,split()might raise anAttributeErrororTypeErrorduring execution.
FAQs
Why use pydantic_settings for configuration?
pydantic_settingsprovides robust type validation and automatic loading from environment variables or.envfiles, 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_ORIGINSenvironment variable, then parsed into a list by theget_cors_originsproperty for easy use.
Why are sensitive credentials defined here?
Sensitive credentials like
SECRET_KEYandSMTP_PASSWORDare 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_NAMEandAPP_VERSIONare hardcoded, which might lead to inconsistencies if not updated across deployments. External configuration is preferable.
Security
High - Hardcoded CORS_ORIGINS default
The
CORS_ORIGINSdefault is hardcoded tohttp://localhost:3000, which is insecure for production environments and should be dynamically configured.
Medium - Hardcoded DEBUG default
The
DEBUGflag defaults toFalse, which is good, but it should be explicitly set via environment variables in all environments.