Giter Club home page Giter Club logo

flask-dotenv's Introduction

Flask-DotEnv

https://travis-ci.org/grauwoelfchen/flask-dotenv.svg?branch=master
Adds support for the .env file to flask style config class for applications.
Version 0.0.3 and above support setting config variables without using os.environ.

Flask-DotEnv will directly set (add, update, map as alias and eval as literal) variables from .env file, and cast them to Python native types as appropriate.

(optional)

  • alias() makes alias vars
  • eval() evaluate var to literal (via ast)

Repositories

My main repository is on GitLab (.com).
But pull requests on GitHub are also welcome. :-D

Install

$ pip install Flask-DotEnv

Usage

DotEnv

from flask import Flask
from flask_dotenv import DotEnv

app = Flask(__name__)
env = DotEnv(app)

As a factory pattern.

env = DotEnv()
env.init_app(app)
This env module may be useful in your Config class.
e.g.
class Config:
    SECRET_KEY = ":'("
    ...

    @classmethod
    def init_app(self, app)
        env = DotEnv()
        env.init_app(app)

Then in your app:

from config import Config

app = Flask(__name__)
app.config.from_object(config[config_name])

See also:

flask.Config.from_object (Flask's API documentation)

Arguments

You can pass the .env file path as a second argument of init_app().

env.init_app(app, env_file="/path/to/.env", verbose_mode=True)
The second argument (env_file) is optional, and the default is os.path.join(os.getcwd(), '.env').
The third argument (verbose_mode) is also optional, and defaults to False.
If verbose_mode is True, then server outputs nice log message showing which vars will be set,
like this:
* Overwriting an existing config var: SECRET_KEY
* Setting an entirely new config var: DEVELOPMENT_DATABASE_URL
* Casting a denoted var as a literal: MAIL_PORT => <class 'int'>
* Making a specified var as an alias: DEVELOPMENT_DATABASE_URL -> SQLALCHEMY_DATABASE_URI
...

Alias

The alias() method takes a dict argument. Each key is the existing config var, while each value is the new alias.

env.alias(maps={
  'TEST_DATABASE_URL': 'SQLALCHEMY_DATABASE_URI',
  'TEST_HOST': 'HOST'
})

Here's an example of its use:

class Config:
    SECRET_KEY = ":'("
    ...

    @classmethod
    def init_app(self, app)
        env = DotEnv()
        env.init_app(app)

        # The following will store in `SQLALCHEMY_DATABASE_URI` the value
        # in, for example, `DEVELOPMENT_DATABASE_URL`
        prefix = self.__name__.replace('Config', '').upper()
        env.alias(maps={
            prefix + '_DATABASE_URL': 'SQLALCHEMY_DATABASE_URI'
        })


class DevelopmentConfig(Config):
    DEBUG = True
    SQLALCHEMY_DATABASE_URI = None


config = {
    'development': DevelopmentConfig
}

Eval

eval() also takes a dict argument. These keys are also the existing config var, while the values are the type they should evaluate to. If the type is something else, the config var is skipped with a log message shown.

env.eval(keys={
  'MAIL_PORT': int,
  'SETTINGS': dict
})

And here's an example of its use:

class Config:
    SECRET_KEY = ":'("
    ...

    @classmethod
    def init_app(self, app)
        env = DotEnv()
        env.init_app(app)

        # `MAIL_PORT` will be set the the integer verson of the value found there
        # using `ast.literal_eval`.
        env.eval(keys={
            MAIL_PORT: int
        })

.env File

The following lines are all valid.

SECRET_KEY="123"
USERNAME=john
DATABASE_URL='postgresql://user:password@localhost/production?sslmode=require'
FEATURES={'DotEnv': True}
# comment and blank lines are also supported

export ENV="production"
export env="staging"

Development

Run the unit tests with:

$ python setup.py test

Link

Inspired by:

Other packages that also set configuration variables:

License

BSD 2-Clause License

flask-dotenv's People

Contributors

chivalry avatar diegoponciano avatar grauwoelfchen avatar lozadaomr avatar mawuli avatar nihonjinrxs avatar oriontvv avatar spankie 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  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  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

flask-dotenv's Issues

Support appropriate type conversions

It would be really nice to be able to support appropriate type conversions to standard Python types.

For example, this BitBucket project doesn't support DotEnv, only OS Environment variables, but does appropriate type conversions via the ast module. The relevant code looks something like this:

from __future__ import absolute_import
import ast
from os import environ

class EnvConfig(object):
    def __init__(self, app): ...
    def init_app(self, app):
        for key, value in environ.iteritems():
            try:
                value = ast.literal_eval(value)
            except (ValueError, SyntaxError):
                pass
            app.config[key] = value

Is this something you're willing to add to this project? I'm happy to implement and submit a PR.

Spaces between equal sign on environment file

Hi!
I found a issue when you put spaces between the var and the asigned value.
Example:

SQLALCHEMY_DATABASE_URI = mysql+my...

And when you load the var SQLALCHEMY_DATABASE_URI, the printed value is:

Space between equal sign

Maybe a trim o something like that... Because when the key value doesnt have spaces before and after the equal sign, like this:
SQLALCHEMY_DATABASE_URI=mysql+my...

The printed value is:

Space between equal sign OK

And the SQLALCHEMY_DATABASE_URI value works as expected (no spaces in the string)

Anyway, thanks for your work!

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.