forked from pallets-eco/flask-environments
-
Notifications
You must be signed in to change notification settings - Fork 1
/
flask_environments.py
74 lines (54 loc) · 1.78 KB
/
flask_environments.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
# -*- coding: utf-8 -*-
"""
flask_environments
~~~~~~~~~~~~~~~~~~
Environment tools and configuration for Flask applications
:copyright: (c) 2012 by Matt Wright.
:license: MIT, see LICENSE for more details.
"""
import os
import yaml
from flask import current_app
class Environments(object):
def __init__(self, app=None, var_name=None, default_env=None):
self.app = app
self.var_name = var_name or 'FLASK_ENV'
self.default_env = default_env or 'DEVELOPMENT'
self.env = os.environ.get(self.var_name, self.default_env)
if app is not None:
self.init_app(app)
def init_app(self, app):
app.config['ENVIORNMENT'] = self.env
if app.extensions is None:
app.extensions = {}
app.extensions['environments'] = self
def get_app(self, reference_app=None):
if reference_app is not None:
return reference_app
if self.app is not None:
return self.app
return current_app
def from_object(self, config_obj):
app = self.get_app()
for name in self._possible_names():
try:
obj = '%s.%s' % (config_obj, name)
app.config.from_object(obj)
return
except:
pass
app.config.from_object(config_obj)
def from_yaml(self, path):
with open(path) as f:
c = yaml.load(f)
for name in self._possible_names():
try:
c = c[name]
except:
pass
app = self.get_app()
for key in c.keys():
if key.isupper():
app.config[key] = c[key]
def _possible_names(self):
return (self.env, self.env.capitalize(), self.env.lower())