Giter Site home page Giter Site logo

br3ndonland / fastenv Goto Github PK

View Code? Open in Web Editor NEW
25.0 2.0 0.0 523 KB

โš™๏ธ Unified environment variable and settings management for FastAPI and beyond ๐Ÿš€

Home Page: https://fastenv.bws.bio

License: MIT License

Python 100.00%
python dotenv environment-variables settings configuration-management fastapi starlette uvicorn pydantic asgi

fastenv's Introduction

โš™๏ธ fastenv ๐Ÿš€

Unified environment variable and settings management for FastAPI and beyond

PyPI coverage ci Ruff

Description

Environment variables are key-value pairs provided to the operating system with syntax like VARIABLE_NAME=value. Collections of environment variables are stored in files commonly named .env and called "dotenv" files. The Python standard library os module provides tools for reading environment variables, such as os.getenv("VARIABLE_NAME"), but only handles strings, and doesn't include tools for file I/O. Additional logic is therefore needed to load environment variables from files before they can be read by Python, and to convert variables from strings to other Python types.

This project aims to:

  • Replace the aging python-dotenv project with a similar, but more intuitive API, and modern syntax and tooling.
  • Implement asynchronous file I/O. Reading and writing files can be done asynchronously with packages like AnyIO.
  • Implement asynchronous object storage integration. Dotenv files are commonly kept in cloud object storage, but environment variable management packages typically don't integrate with object storage clients. Additional logic is therefore required to download .env files from object storage prior to loading environment variables. This project aims to integrate with S3-compatible object storage, with a focus on downloading and uploading file objects.
  • Read settings from TOML. It's all about pyproject.toml now. The Python community has pushed PEP 517 build tooling and PEP 518 build requirements forward, and even setuptools has come around. PEP 621 defined how to store package metadata and dependencies in pyproject.toml. Why don't we use the metadata from our pyproject.toml files in our Python applications?
  • Unify settings management for FastAPI. Uvicorn, Starlette, and pydantic each have their own ways of loading environment variables and configuring application settings. This means that, when configuring a FastAPI application, there are at least three different settings management tools available, each with their own pros and cons. It would be helpful to address the limitations of each of these options, potentially providing a similar, improved API for each one.

The source code is 100% type-annotated and unit-tested.

Quickstart

Install fastenv into a virtual environment:

python3 -m venv .venv
. .venv/bin/activate
python -m pip install fastenv

Then start a REPL session and try it out:

.venv โฏ python
# instantiate a DotEnv with a variable
import fastenv
dotenv = fastenv.DotEnv("EXAMPLE_VARIABLE=example_value")
# add a variable with dictionary syntax
dotenv["ANOTHER_VARIABLE"] = "another_value"
# delete a variable
del dotenv["ANOTHER_VARIABLE"]
# add a variable by calling the instance
dotenv("I_THINK_FASTENV_IS=awesome")
# {'I_THINK_FASTENV_IS': 'awesome'}
# return a dict of the variables in the DotEnv instance
dict(dotenv)
# {'EXAMPLE_VARIABLE': 'example_value', 'I_THINK_FASTENV_IS': 'awesome'}
# save the DotEnv instance to a file
import anyio
anyio.run(fastenv.dump_dotenv, dotenv)
# Path('/path/to/this/dir/.env')

Use fastenv in your FastAPI app:

from contextlib import asynccontextmanager
from typing import AsyncIterator, TypedDict

import fastenv
from fastapi import FastAPI, Request


class LifespanState(TypedDict):
    settings: fastenv.DotEnv


@asynccontextmanager
async def lifespan(_: FastAPI) -> AsyncIterator[LifespanState]:
    """Configure app lifespan.

    https://fastapi.tiangolo.com/advanced/events/
    https://www.starlette.io/lifespan/
    """
    settings = await fastenv.load_dotenv(".env")
    lifespan_state: LifespanState = {"settings": settings}
    yield lifespan_state


app = FastAPI(lifespan=lifespan)


@app.get("/settings")
async def get_settings(request: Request) -> dict[str, str]:
    settings = request.state.settings
    return dict(settings)

Documentation

Documentation is built with Material for MkDocs, deployed on Vercel, and available at fastenv.bws.bio and fastenv.vercel.app.

Vercel build configuration:

  • Build command: python3 -m pip install mkdocs-material && mkdocs build --site-dir public
  • Output directory: public (default)

Vercel site configuration is specified in vercel.json.

fastenv's People

Contributors

br3ndonland avatar github-actions[bot] avatar sourcery-ai[bot] avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.