Skip to content

How do I pass environment variables to my route files? #8191

Closed Answered by dmontagu
unography asked this question in Questions
Discussion options

You must be logged in to vote

@unography I would recommend the use of the BaseSettings class in pydantic. Here's a basic example:

from functools import lru_cache
import os
from typing import Optional

from pydantic import BaseSettings


class AppSettings(BaseSettings):
    project_name: str = "My API"
    debug: bool = False

    # Server
    server_name: Optional[str]
    server_host: Optional[str]
    sentry_dsn: Optional[str]
    secret_key: bytes = os.urandom(32)

    ...

    class Config:
        env_prefix = ""  # defaults to 'APP_'; see description in pydantic docs
        allow_mutation = False


@lru_cache()
def get_settings() -> AppSettings:
    return AppSettings()

This way you can basically treat the sett…

Replies: 8 comments

Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Answer selected by Kludex
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
question Question or problem question-migrate
6 participants
Converted from issue

This discussion was converted from issue #399 on February 28, 2023 12:25.