Name | environs JSON |
Version |
11.2.1
JSON |
| download |
home_page | None |
Summary | simplified environment variable parsing |
upload_time | 2024-11-20 17:38:40 |
maintainer | None |
docs_url | None |
author | None |
requires_python | >=3.8 |
license | None |
keywords |
|
VCS |
|
bugtrack_url |
|
requirements |
No requirements were recorded.
|
Travis-CI |
No Travis.
|
coveralls test coverage |
No coveralls.
|
# environs: simplified environment variable parsing
[![Latest version](https://badgen.net/pypi/v/environs)](https://pypi.org/project/environs/)
[![Build Status](https://github.com/sloria/environs/actions/workflows/build-release.yml/badge.svg)](https://github.com/sloria/environs/actions/workflows/build-release.yml)
[![marshmallow 3 compatible](https://badgen.net/badge/marshmallow/3)](https://marshmallow.readthedocs.io/en/latest/upgrading.html)
**environs** is a Python library for parsing environment variables.
It allows you to store configuration separate from your code, as per
[The Twelve-Factor App](https://12factor.net/config) methodology.
## Contents
<!-- START doctoc generated TOC please keep comment here to allow auto update -->
<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->
- [Features](#features)
- [Install](#install)
- [Basic usage](#basic-usage)
- [Supported types](#supported-types)
- [Reading `.env` files](#reading-env-files)
- [Reading a specific file](#reading-a-specific-file)
- [Handling prefixes](#handling-prefixes)
- [Variable expansion](#variable-expansion)
- [Validation](#validation)
- [Deferred validation](#deferred-validation)
- [URL schemes](#url-schemes)
- [Serialization](#serialization)
- [Defining custom parser behavior](#defining-custom-parser-behavior)
- [Usage with Flask](#usage-with-flask)
- [Usage with Django](#usage-with-django)
- [Why\...?](#why%5C)
- [Why envvars?](#why-envvars)
- [Why not `os.environ`?](#why-not-osenviron)
- [Why another library?](#why-another-library)
- [License](#license)
<!-- END doctoc generated TOC please keep comment here to allow auto update -->
## Features
- Type-casting
- Read `.env` files into `os.environ` (useful for local development)
- Validation
- Define custom parser behavior
- Framework-agnostic, but integrates well with [Flask](#usage-with-flask) and [Django](#usage-with-django)
## Install
pip install environs
## Basic usage
With some environment variables set...
```bash
export GITHUB_USER=sloria
export MAX_CONNECTIONS=100
export SHIP_DATE='1984-06-25'
export TTL=42
export ENABLE_LOGIN=true
export GITHUB_REPOS=webargs,konch,ped
export GITHUB_REPO_PRIORITY="webargs=2,konch=3"
export COORDINATES=23.3,50.0
export LOG_LEVEL=DEBUG
```
Parse them with environs...
```python
from environs import Env
env = Env()
env.read_env() # read .env file, if it exists
# required variables
gh_user = env("GITHUB_USER") # => 'sloria'
secret = env("SECRET") # => raises error if not set
# casting
max_connections = env.int("MAX_CONNECTIONS") # => 100
ship_date = env.date("SHIP_DATE") # => datetime.date(1984, 6, 25)
ttl = env.timedelta("TTL") # => datetime.timedelta(seconds=42)
log_level = env.log_level("LOG_LEVEL") # => logging.DEBUG
# providing a default value
enable_login = env.bool("ENABLE_LOGIN", False) # => True
enable_feature_x = env.bool("ENABLE_FEATURE_X", False) # => False
# parsing lists
gh_repos = env.list("GITHUB_REPOS") # => ['webargs', 'konch', 'ped']
coords = env.list("COORDINATES", subcast=float) # => [23.3, 50.0]
# parsing dicts
gh_repos_priorities = env.dict(
"GITHUB_REPO_PRIORITY", subcast_values=int
) # => {'webargs': 2, 'konch': 3}
```
## Supported types
The following are all type-casting methods of `Env`:
- `env.str`
- `env.bool`
- `env.int`
- `env.float`
- `env.decimal`
- `env.list` (accepts optional `subcast` and `delimiter` keyword arguments)
- `env.dict` (accepts optional `subcast_keys`, `subcast_values` and `delimiter` keyword arguments)
- `env.json`
- `env.datetime`
- `env.date`
- `env.time`
- `env.timedelta` (assumes value is an integer in seconds, or an ordered duration string like `7h7s` or `7w 7d 7h 7m 7s 7ms 7us`)
- `env.url`
- `env.uuid`
- `env.log_level`
- `env.path` (casts to a [`pathlib.Path`](https://docs.python.org/3/library/pathlib.html))
- `env.enum` (casts to any given enum type specified in `type` keyword argument, accepts optional `ignore_case` keyword argument)
## Reading `.env` files
```bash
# .env
DEBUG=true
PORT=4567
```
Call `Env.read_env` before parsing variables.
```python
from environs import Env
env = Env()
# Read .env into os.environ
env.read_env()
env.bool("DEBUG") # => True
env.int("PORT") # => 4567
```
### Reading a specific file
By default, `Env.read_env` will look for a `.env` file in current
directory and (if no .env exists in the CWD) recurse
upwards until a `.env` file is found.
You can also read a specific file:
```python
from environs import Env
with open(".env.test", "w") as fobj:
fobj.write("A=foo\n")
fobj.write("B=123\n")
env = Env()
env.read_env(".env.test", recurse=False)
assert env("A") == "foo"
assert env.int("B") == 123
```
## Handling prefixes
```python
# export MYAPP_HOST=lolcathost
# export MYAPP_PORT=3000
with env.prefixed("MYAPP_"):
host = env("HOST", "localhost") # => 'lolcathost'
port = env.int("PORT", 5000) # => 3000
# nested prefixes are also supported:
# export MYAPP_DB_HOST=lolcathost
# export MYAPP_DB_PORT=10101
with env.prefixed("MYAPP_"):
with env.prefixed("DB_"):
db_host = env("HOST", "lolcathost")
db_port = env.int("PORT", 10101)
```
## Variable expansion
```python
# export CONNECTION_URL=https://${USER:-sloria}:${PASSWORD}@${HOST:-localhost}/
# export PASSWORD=secret
# export YEAR=${CURRENT_YEAR:-2020}
from environs import Env
env = Env(expand_vars=True)
connection_url = env("CONNECTION_URL") # =>'https://sloria:secret@localhost'
year = env.int("YEAR") # =>2020
```
## Validation
```python
# export TTL=-2
# export NODE_ENV='invalid'
# export EMAIL='^_^'
from environs import Env
from marshmallow.validate import OneOf, Length, Email
env = Env()
# simple validator
env.int("TTL", validate=lambda n: n > 0)
# => Environment variable "TTL" invalid: ['Invalid value.']
# using marshmallow validators
env.str(
"NODE_ENV",
validate=OneOf(
["production", "development"], error="NODE_ENV must be one of: {choices}"
),
)
# => Environment variable "NODE_ENV" invalid: ['NODE_ENV must be one of: production, development']
# multiple validators
env.str("EMAIL", validate=[Length(min=4), Email()])
# => Environment variable "EMAIL" invalid: ['Shorter than minimum length 4.', 'Not a valid email address.']
```
## Deferred validation
By default, a validation error is raised immediately upon calling a parser method for an invalid environment variable.
To defer validation and raise an exception with the combined error messages for all invalid variables, pass `eager=False` to `Env`.
Call `env.seal()` after all variables have been parsed.
```python
# export TTL=-2
# export NODE_ENV='invalid'
# export EMAIL='^_^'
from environs import Env
from marshmallow.validate import OneOf, Email, Length, Range
env = Env(eager=False)
TTL = env.int("TTL", validate=Range(min=0, max=100))
NODE_ENV = env.str(
"NODE_ENV",
validate=OneOf(
["production", "development"], error="NODE_ENV must be one of: {choices}"
),
)
EMAIL = env.str("EMAIL", validate=[Length(min=4), Email()])
env.seal()
# environs.EnvValidationError: Environment variables invalid: {'TTL': ['Must be greater than or equal to 0 and less than or equal to 100.'], 'NODE_ENV': ['NODE_ENV must be one of: production, development'], 'EMAIL': ['Shorter than minimum length 4.', 'Not a valid email address.']}
```
`env.seal()` validates all parsed variables and prevents further parsing (calling a parser method will raise an error).
## URL schemes
`env.url()` supports non-standard URL schemes via the `schemes` argument.
```python
REDIS_URL = env.url(
"REDIS_URL", "redis://redis:6379", schemes=["redis"], require_tld=False
)
```
## Serialization
```python
# serialize to a dictionary of simple types (numbers and strings)
env.dump()
# {'COORDINATES': [23.3, 50.0],
# 'ENABLE_FEATURE_X': False,
# 'ENABLE_LOGIN': True,
# 'GITHUB_REPOS': ['webargs', 'konch', 'ped'],
# 'GITHUB_USER': 'sloria',
# 'MAX_CONNECTIONS': 100,
# 'MYAPP_HOST': 'lolcathost',
# 'MYAPP_PORT': 3000,
# 'SHIP_DATE': '1984-06-25',
# 'TTL': 42}
```
## Defining custom parser behavior
```python
# export DOMAIN='http://myapp.com'
# export COLOR=invalid
from furl import furl
# Register a new parser method for paths
@env.parser_for("furl")
def furl_parser(value):
return furl(value)
domain = env.furl("DOMAIN") # => furl('https://myapp.com')
# Custom parsers can take extra keyword arguments
@env.parser_for("choice")
def choice_parser(value, choices):
if value not in choices:
raise environs.EnvError("Invalid!")
return value
color = env.choice("COLOR", choices=["black"]) # => raises EnvError
```
## Usage with Flask
```python
# myapp/settings.py
from environs import Env
env = Env()
env.read_env()
# Override in .env for local development
DEBUG = env.bool("FLASK_DEBUG", default=False)
# SECRET_KEY is required
SECRET_KEY = env.str("SECRET_KEY")
```
Load the configuration after you initialize your app.
```python
# myapp/app.py
from flask import Flask
app = Flask(__name__)
app.config.from_object("myapp.settings")
```
For local development, use a `.env` file to override the default
configuration.
```bash
# .env
DEBUG=true
SECRET_KEY="not so secret"
```
Note: Because environs depends on [python-dotenv](https://github.com/theskumar/python-dotenv),
the `flask` CLI will automatically read .env and .flaskenv files.
## Usage with Django
environs includes a number of helpers for parsing connection URLs. To
install environs with django support:
pip install environs[django]
Use `env.dj_db_url`, `env.dj_cache_url` and `env.dj_email_url` to parse the `DATABASE_URL`, `CACHE_URL`
and `EMAIL_URL` environment variables, respectively.
For more details on URL patterns, see the following projects that environs is using for converting URLs.
- [dj-database-url](https://github.com/jacobian/dj-database-url)
- [django-cache-url](https://github.com/epicserve/django-cache-url)
- [dj-email-url](https://github.com/migonzalvar/dj-email-url)
Basic example:
```python
# myproject/settings.py
from environs import Env
env = Env()
env.read_env()
# Override in .env for local development
DEBUG = env.bool("DEBUG", default=False)
# SECRET_KEY is required
SECRET_KEY = env.str("SECRET_KEY")
# Parse database URLs, e.g. "postgres://localhost:5432/mydb"
DATABASES = {"default": env.dj_db_url("DATABASE_URL")}
# Parse email URLs, e.g. "smtp://"
email = env.dj_email_url("EMAIL_URL", default="smtp://")
EMAIL_HOST = email["EMAIL_HOST"]
EMAIL_PORT = email["EMAIL_PORT"]
EMAIL_HOST_PASSWORD = email["EMAIL_HOST_PASSWORD"]
EMAIL_HOST_USER = email["EMAIL_HOST_USER"]
EMAIL_USE_TLS = email["EMAIL_USE_TLS"]
# Parse cache URLS, e.g "redis://localhost:6379/0"
CACHES = {"default": env.dj_cache_url("CACHE_URL")}
```
For local development, use a `.env` file to override the default
configuration.
```bash
# .env
DEBUG=true
SECRET_KEY="not so secret"
```
For a more complete example, see
[django_example.py](https://github.com/sloria/environs/blob/master/examples/django_example.py)
in the `examples/` directory.
## Why\...?
### Why envvars?
See [The 12-factor App](http://12factor.net/config) section on
[configuration](http://12factor.net/config).
### Why not `os.environ`?
While `os.environ` is enough for simple use cases, a typical application
will need a way to manipulate and validate raw environment variables.
environs abstracts common tasks for handling environment variables.
environs will help you
- cast envvars to the correct type
- specify required envvars
- define default values
- validate envvars
- parse list and dict values
- parse dates, datetimes, and timedeltas
- parse expanded variables
- serialize your configuration to JSON, YAML, etc.
### Why another library?
There are many great Python libraries for parsing environment variables.
In fact, most of the credit for environs\' public API goes to the
authors of [envparse](https://github.com/rconradharris/envparse) and
[django-environ](https://github.com/joke2k/django-environ).
environs aims to meet three additional goals:
1. Make it easy to extend parsing behavior and develop plugins.
2. Leverage the deserialization and validation functionality provided
by a separate library (marshmallow).
3. Clean up redundant API.
See [this GitHub
issue](https://github.com/rconradharris/envparse/issues/12#issue-151036722)
which details specific differences with envparse.
## License
MIT licensed. See the
[LICENSE](https://github.com/sloria/environs/blob/master/LICENSE) file
for more details.
Raw data
{
"_id": null,
"home_page": null,
"name": "environs",
"maintainer": null,
"docs_url": null,
"requires_python": ">=3.8",
"maintainer_email": null,
"keywords": null,
"author": null,
"author_email": "Steven Loria <sloria1@gmail.com>",
"download_url": "https://files.pythonhosted.org/packages/77/08/2b7d9cacf2b27482c9218ee6762336aa47bdb9d07ee26a136d072a328297/environs-11.2.1.tar.gz",
"platform": null,
"description": "# environs: simplified environment variable parsing\n\n[![Latest version](https://badgen.net/pypi/v/environs)](https://pypi.org/project/environs/)\n[![Build Status](https://github.com/sloria/environs/actions/workflows/build-release.yml/badge.svg)](https://github.com/sloria/environs/actions/workflows/build-release.yml)\n[![marshmallow 3 compatible](https://badgen.net/badge/marshmallow/3)](https://marshmallow.readthedocs.io/en/latest/upgrading.html)\n\n**environs** is a Python library for parsing environment variables.\nIt allows you to store configuration separate from your code, as per\n[The Twelve-Factor App](https://12factor.net/config) methodology.\n\n## Contents\n\n<!-- START doctoc generated TOC please keep comment here to allow auto update -->\n<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->\n\n- [Features](#features)\n- [Install](#install)\n- [Basic usage](#basic-usage)\n- [Supported types](#supported-types)\n- [Reading `.env` files](#reading-env-files)\n - [Reading a specific file](#reading-a-specific-file)\n- [Handling prefixes](#handling-prefixes)\n- [Variable expansion](#variable-expansion)\n- [Validation](#validation)\n- [Deferred validation](#deferred-validation)\n- [URL schemes](#url-schemes)\n- [Serialization](#serialization)\n- [Defining custom parser behavior](#defining-custom-parser-behavior)\n- [Usage with Flask](#usage-with-flask)\n- [Usage with Django](#usage-with-django)\n- [Why\\...?](#why%5C)\n - [Why envvars?](#why-envvars)\n - [Why not `os.environ`?](#why-not-osenviron)\n - [Why another library?](#why-another-library)\n- [License](#license)\n\n<!-- END doctoc generated TOC please keep comment here to allow auto update -->\n\n## Features\n\n- Type-casting\n- Read `.env` files into `os.environ` (useful for local development)\n- Validation\n- Define custom parser behavior\n- Framework-agnostic, but integrates well with [Flask](#usage-with-flask) and [Django](#usage-with-django)\n\n## Install\n\n pip install environs\n\n## Basic usage\n\nWith some environment variables set...\n\n```bash\nexport GITHUB_USER=sloria\nexport MAX_CONNECTIONS=100\nexport SHIP_DATE='1984-06-25'\nexport TTL=42\nexport ENABLE_LOGIN=true\nexport GITHUB_REPOS=webargs,konch,ped\nexport GITHUB_REPO_PRIORITY=\"webargs=2,konch=3\"\nexport COORDINATES=23.3,50.0\nexport LOG_LEVEL=DEBUG\n```\n\nParse them with environs...\n\n```python\nfrom environs import Env\n\nenv = Env()\nenv.read_env() # read .env file, if it exists\n# required variables\ngh_user = env(\"GITHUB_USER\") # => 'sloria'\nsecret = env(\"SECRET\") # => raises error if not set\n\n# casting\nmax_connections = env.int(\"MAX_CONNECTIONS\") # => 100\nship_date = env.date(\"SHIP_DATE\") # => datetime.date(1984, 6, 25)\nttl = env.timedelta(\"TTL\") # => datetime.timedelta(seconds=42)\nlog_level = env.log_level(\"LOG_LEVEL\") # => logging.DEBUG\n\n# providing a default value\nenable_login = env.bool(\"ENABLE_LOGIN\", False) # => True\nenable_feature_x = env.bool(\"ENABLE_FEATURE_X\", False) # => False\n\n# parsing lists\ngh_repos = env.list(\"GITHUB_REPOS\") # => ['webargs', 'konch', 'ped']\ncoords = env.list(\"COORDINATES\", subcast=float) # => [23.3, 50.0]\n\n# parsing dicts\ngh_repos_priorities = env.dict(\n \"GITHUB_REPO_PRIORITY\", subcast_values=int\n) # => {'webargs': 2, 'konch': 3}\n```\n\n## Supported types\n\nThe following are all type-casting methods of `Env`:\n\n- `env.str`\n- `env.bool`\n- `env.int`\n- `env.float`\n- `env.decimal`\n- `env.list` (accepts optional `subcast` and `delimiter` keyword arguments)\n- `env.dict` (accepts optional `subcast_keys`, `subcast_values` and `delimiter` keyword arguments)\n- `env.json`\n- `env.datetime`\n- `env.date`\n- `env.time`\n- `env.timedelta` (assumes value is an integer in seconds, or an ordered duration string like `7h7s` or `7w 7d 7h 7m 7s 7ms 7us`)\n- `env.url`\n- `env.uuid`\n- `env.log_level`\n- `env.path` (casts to a [`pathlib.Path`](https://docs.python.org/3/library/pathlib.html))\n- `env.enum` (casts to any given enum type specified in `type` keyword argument, accepts optional `ignore_case` keyword argument)\n\n## Reading `.env` files\n\n```bash\n# .env\nDEBUG=true\nPORT=4567\n```\n\nCall `Env.read_env` before parsing variables.\n\n```python\nfrom environs import Env\n\nenv = Env()\n# Read .env into os.environ\nenv.read_env()\n\nenv.bool(\"DEBUG\") # => True\nenv.int(\"PORT\") # => 4567\n```\n\n### Reading a specific file\n\nBy default, `Env.read_env` will look for a `.env` file in current\ndirectory and (if no .env exists in the CWD) recurse\nupwards until a `.env` file is found.\n\nYou can also read a specific file:\n\n```python\nfrom environs import Env\n\nwith open(\".env.test\", \"w\") as fobj:\n fobj.write(\"A=foo\\n\")\n fobj.write(\"B=123\\n\")\n\nenv = Env()\nenv.read_env(\".env.test\", recurse=False)\n\nassert env(\"A\") == \"foo\"\nassert env.int(\"B\") == 123\n```\n\n## Handling prefixes\n\n```python\n# export MYAPP_HOST=lolcathost\n# export MYAPP_PORT=3000\n\nwith env.prefixed(\"MYAPP_\"):\n host = env(\"HOST\", \"localhost\") # => 'lolcathost'\n port = env.int(\"PORT\", 5000) # => 3000\n\n# nested prefixes are also supported:\n\n# export MYAPP_DB_HOST=lolcathost\n# export MYAPP_DB_PORT=10101\n\nwith env.prefixed(\"MYAPP_\"):\n with env.prefixed(\"DB_\"):\n db_host = env(\"HOST\", \"lolcathost\")\n db_port = env.int(\"PORT\", 10101)\n```\n\n## Variable expansion\n\n```python\n# export CONNECTION_URL=https://${USER:-sloria}:${PASSWORD}@${HOST:-localhost}/\n# export PASSWORD=secret\n# export YEAR=${CURRENT_YEAR:-2020}\n\nfrom environs import Env\n\nenv = Env(expand_vars=True)\n\nconnection_url = env(\"CONNECTION_URL\") # =>'https://sloria:secret@localhost'\nyear = env.int(\"YEAR\") # =>2020\n```\n\n## Validation\n\n```python\n# export TTL=-2\n# export NODE_ENV='invalid'\n# export EMAIL='^_^'\n\nfrom environs import Env\nfrom marshmallow.validate import OneOf, Length, Email\n\nenv = Env()\n\n# simple validator\nenv.int(\"TTL\", validate=lambda n: n > 0)\n# => Environment variable \"TTL\" invalid: ['Invalid value.']\n\n\n# using marshmallow validators\nenv.str(\n \"NODE_ENV\",\n validate=OneOf(\n [\"production\", \"development\"], error=\"NODE_ENV must be one of: {choices}\"\n ),\n)\n# => Environment variable \"NODE_ENV\" invalid: ['NODE_ENV must be one of: production, development']\n\n# multiple validators\nenv.str(\"EMAIL\", validate=[Length(min=4), Email()])\n# => Environment variable \"EMAIL\" invalid: ['Shorter than minimum length 4.', 'Not a valid email address.']\n```\n\n## Deferred validation\n\nBy default, a validation error is raised immediately upon calling a parser method for an invalid environment variable.\nTo defer validation and raise an exception with the combined error messages for all invalid variables, pass `eager=False` to `Env`.\nCall `env.seal()` after all variables have been parsed.\n\n```python\n# export TTL=-2\n# export NODE_ENV='invalid'\n# export EMAIL='^_^'\n\nfrom environs import Env\nfrom marshmallow.validate import OneOf, Email, Length, Range\n\nenv = Env(eager=False)\n\nTTL = env.int(\"TTL\", validate=Range(min=0, max=100))\nNODE_ENV = env.str(\n \"NODE_ENV\",\n validate=OneOf(\n [\"production\", \"development\"], error=\"NODE_ENV must be one of: {choices}\"\n ),\n)\nEMAIL = env.str(\"EMAIL\", validate=[Length(min=4), Email()])\n\nenv.seal()\n# environs.EnvValidationError: Environment variables invalid: {'TTL': ['Must be greater than or equal to 0 and less than or equal to 100.'], 'NODE_ENV': ['NODE_ENV must be one of: production, development'], 'EMAIL': ['Shorter than minimum length 4.', 'Not a valid email address.']}\n```\n\n`env.seal()` validates all parsed variables and prevents further parsing (calling a parser method will raise an error).\n\n## URL schemes\n\n`env.url()` supports non-standard URL schemes via the `schemes` argument.\n\n```python\nREDIS_URL = env.url(\n \"REDIS_URL\", \"redis://redis:6379\", schemes=[\"redis\"], require_tld=False\n)\n```\n\n## Serialization\n\n```python\n# serialize to a dictionary of simple types (numbers and strings)\nenv.dump()\n# {'COORDINATES': [23.3, 50.0],\n# 'ENABLE_FEATURE_X': False,\n# 'ENABLE_LOGIN': True,\n# 'GITHUB_REPOS': ['webargs', 'konch', 'ped'],\n# 'GITHUB_USER': 'sloria',\n# 'MAX_CONNECTIONS': 100,\n# 'MYAPP_HOST': 'lolcathost',\n# 'MYAPP_PORT': 3000,\n# 'SHIP_DATE': '1984-06-25',\n# 'TTL': 42}\n```\n\n## Defining custom parser behavior\n\n```python\n# export DOMAIN='http://myapp.com'\n# export COLOR=invalid\n\nfrom furl import furl\n\n\n# Register a new parser method for paths\n@env.parser_for(\"furl\")\ndef furl_parser(value):\n return furl(value)\n\n\ndomain = env.furl(\"DOMAIN\") # => furl('https://myapp.com')\n\n\n# Custom parsers can take extra keyword arguments\n@env.parser_for(\"choice\")\ndef choice_parser(value, choices):\n if value not in choices:\n raise environs.EnvError(\"Invalid!\")\n return value\n\n\ncolor = env.choice(\"COLOR\", choices=[\"black\"]) # => raises EnvError\n```\n\n## Usage with Flask\n\n```python\n# myapp/settings.py\n\nfrom environs import Env\n\nenv = Env()\nenv.read_env()\n\n# Override in .env for local development\nDEBUG = env.bool(\"FLASK_DEBUG\", default=False)\n# SECRET_KEY is required\nSECRET_KEY = env.str(\"SECRET_KEY\")\n```\n\nLoad the configuration after you initialize your app.\n\n```python\n# myapp/app.py\n\nfrom flask import Flask\n\napp = Flask(__name__)\napp.config.from_object(\"myapp.settings\")\n```\n\nFor local development, use a `.env` file to override the default\nconfiguration.\n\n```bash\n# .env\nDEBUG=true\nSECRET_KEY=\"not so secret\"\n```\n\nNote: Because environs depends on [python-dotenv](https://github.com/theskumar/python-dotenv),\nthe `flask` CLI will automatically read .env and .flaskenv files.\n\n## Usage with Django\n\nenvirons includes a number of helpers for parsing connection URLs. To\ninstall environs with django support:\n\n pip install environs[django]\n\nUse `env.dj_db_url`, `env.dj_cache_url` and `env.dj_email_url` to parse the `DATABASE_URL`, `CACHE_URL`\nand `EMAIL_URL` environment variables, respectively.\n\nFor more details on URL patterns, see the following projects that environs is using for converting URLs.\n\n- [dj-database-url](https://github.com/jacobian/dj-database-url)\n- [django-cache-url](https://github.com/epicserve/django-cache-url)\n- [dj-email-url](https://github.com/migonzalvar/dj-email-url)\n\nBasic example:\n\n```python\n# myproject/settings.py\nfrom environs import Env\n\nenv = Env()\nenv.read_env()\n\n# Override in .env for local development\nDEBUG = env.bool(\"DEBUG\", default=False)\n# SECRET_KEY is required\nSECRET_KEY = env.str(\"SECRET_KEY\")\n\n# Parse database URLs, e.g. \"postgres://localhost:5432/mydb\"\nDATABASES = {\"default\": env.dj_db_url(\"DATABASE_URL\")}\n\n# Parse email URLs, e.g. \"smtp://\"\nemail = env.dj_email_url(\"EMAIL_URL\", default=\"smtp://\")\nEMAIL_HOST = email[\"EMAIL_HOST\"]\nEMAIL_PORT = email[\"EMAIL_PORT\"]\nEMAIL_HOST_PASSWORD = email[\"EMAIL_HOST_PASSWORD\"]\nEMAIL_HOST_USER = email[\"EMAIL_HOST_USER\"]\nEMAIL_USE_TLS = email[\"EMAIL_USE_TLS\"]\n\n# Parse cache URLS, e.g \"redis://localhost:6379/0\"\nCACHES = {\"default\": env.dj_cache_url(\"CACHE_URL\")}\n```\n\nFor local development, use a `.env` file to override the default\nconfiguration.\n\n```bash\n# .env\nDEBUG=true\nSECRET_KEY=\"not so secret\"\n```\n\nFor a more complete example, see\n[django_example.py](https://github.com/sloria/environs/blob/master/examples/django_example.py)\nin the `examples/` directory.\n\n## Why\\...?\n\n### Why envvars?\n\nSee [The 12-factor App](http://12factor.net/config) section on\n[configuration](http://12factor.net/config).\n\n### Why not `os.environ`?\n\nWhile `os.environ` is enough for simple use cases, a typical application\nwill need a way to manipulate and validate raw environment variables.\nenvirons abstracts common tasks for handling environment variables.\n\nenvirons will help you\n\n- cast envvars to the correct type\n- specify required envvars\n- define default values\n- validate envvars\n- parse list and dict values\n- parse dates, datetimes, and timedeltas\n- parse expanded variables\n- serialize your configuration to JSON, YAML, etc.\n\n### Why another library?\n\nThere are many great Python libraries for parsing environment variables.\nIn fact, most of the credit for environs\\' public API goes to the\nauthors of [envparse](https://github.com/rconradharris/envparse) and\n[django-environ](https://github.com/joke2k/django-environ).\n\nenvirons aims to meet three additional goals:\n\n1. Make it easy to extend parsing behavior and develop plugins.\n2. Leverage the deserialization and validation functionality provided\n by a separate library (marshmallow).\n3. Clean up redundant API.\n\nSee [this GitHub\nissue](https://github.com/rconradharris/envparse/issues/12#issue-151036722)\nwhich details specific differences with envparse.\n\n## License\n\nMIT licensed. See the\n[LICENSE](https://github.com/sloria/environs/blob/master/LICENSE) file\nfor more details.\n\n",
"bugtrack_url": null,
"license": null,
"summary": "simplified environment variable parsing",
"version": "11.2.1",
"project_urls": {
"Changelog": "https://github.com/sloria/environs/blob/master/CHANGELOG.md",
"Issues": "https://github.com/sloria/environs/issues",
"Source": "https://github.com/sloria/environs"
},
"split_keywords": [],
"urls": [
{
"comment_text": "",
"digests": {
"blake2b_256": "1a211e0d8de234e9d0c675ea8fd50f9e7ad66fae32c207bc982f1d14f7c0835b",
"md5": "82e4d46bc9e4676691d97a6dbd145318",
"sha256": "9d2080cf25807a26fc0d4301e2d7b62c64fbf547540f21e3a30cc02bc5fbe948"
},
"downloads": -1,
"filename": "environs-11.2.1-py3-none-any.whl",
"has_sig": false,
"md5_digest": "82e4d46bc9e4676691d97a6dbd145318",
"packagetype": "bdist_wheel",
"python_version": "py3",
"requires_python": ">=3.8",
"size": 12923,
"upload_time": "2024-11-20T17:38:39",
"upload_time_iso_8601": "2024-11-20T17:38:39.013456Z",
"url": "https://files.pythonhosted.org/packages/1a/21/1e0d8de234e9d0c675ea8fd50f9e7ad66fae32c207bc982f1d14f7c0835b/environs-11.2.1-py3-none-any.whl",
"yanked": false,
"yanked_reason": null
},
{
"comment_text": "",
"digests": {
"blake2b_256": "77082b7d9cacf2b27482c9218ee6762336aa47bdb9d07ee26a136d072a328297",
"md5": "20e34be5e1457be0a4839ad5a2e2440a",
"sha256": "e068ae3174cef52ba4b95ead22e639056a02465f616e62323e04ae08e86a75a4"
},
"downloads": -1,
"filename": "environs-11.2.1.tar.gz",
"has_sig": false,
"md5_digest": "20e34be5e1457be0a4839ad5a2e2440a",
"packagetype": "sdist",
"python_version": "source",
"requires_python": ">=3.8",
"size": 27485,
"upload_time": "2024-11-20T17:38:40",
"upload_time_iso_8601": "2024-11-20T17:38:40.795933Z",
"url": "https://files.pythonhosted.org/packages/77/08/2b7d9cacf2b27482c9218ee6762336aa47bdb9d07ee26a136d072a328297/environs-11.2.1.tar.gz",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2024-11-20 17:38:40",
"github": true,
"gitlab": false,
"bitbucket": false,
"codeberg": false,
"github_user": "sloria",
"github_project": "environs",
"travis_ci": false,
"coveralls": false,
"github_actions": true,
"tox": true,
"lcname": "environs"
}