Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Newer
Older
100644 170 lines (131 sloc) 6.148 kB
4f8ee8f @mitsuhiko Added missing comments, fixed setup.py and made tests pass
authored
1 # -*- coding: utf-8 -*-
2 """
3 flask.config
4 ~~~~~~~~~~~~
5
6 Implements the configuration related objects.
7
ee8417d @mitsuhiko Late but 2010 -> 2011 in some files
authored
8 :copyright: (c) 2011 by Armin Ronacher.
4f8ee8f @mitsuhiko Added missing comments, fixed setup.py and made tests pass
authored
9 :license: BSD, see LICENSE for more details.
10 """
11
b551f15 @mitsuhiko Restored 2.5 compatibility{
authored
12 from __future__ import with_statement
13
405c299 @jbweber Updated from_pyfile so its dynamic module creation uses the imp modul…
jbweber authored
14 import imp
c4f64c1 @justquick working import layout for module
justquick authored
15 import os
fa98177 @akavlie Test passes.
akavlie authored
16 import errno
c4f64c1 @justquick working import layout for module
justquick authored
17
2866ccd @mitsuhiko Switch to explicit Werkzeug imports
authored
18 from werkzeug.utils import import_string
d0dc89e @justquick in with the new. i have the bits in places where i think they should …
justquick authored
19
20
21 class ConfigAttribute(object):
22 """Makes an attribute forward to the config"""
23
8da8a21 @mitsuhiko Moved the conversion thing into the ConfigAttribute.
authored
24 def __init__(self, name, get_converter=None):
d0dc89e @justquick in with the new. i have the bits in places where i think they should …
justquick authored
25 self.__name__ = name
8da8a21 @mitsuhiko Moved the conversion thing into the ConfigAttribute.
authored
26 self.get_converter = get_converter
d0dc89e @justquick in with the new. i have the bits in places where i think they should …
justquick authored
27
28 def __get__(self, obj, type=None):
29 if obj is None:
30 return self
8da8a21 @mitsuhiko Moved the conversion thing into the ConfigAttribute.
authored
31 rv = obj.config[self.__name__]
32 if self.get_converter is not None:
33 rv = self.get_converter(rv)
34 return rv
d0dc89e @justquick in with the new. i have the bits in places where i think they should …
justquick authored
35
36 def __set__(self, obj, value):
37 obj.config[self.__name__] = value
38
39
40 class Config(dict):
41 """Works exactly like a dict but provides ways to fill it from files
42 or special dictionaries. There are two common patterns to populate the
43 config.
44
45 Either you can fill the config from a config file::
46
47 app.config.from_pyfile('yourconfig.cfg')
48
49 Or alternatively you can define the configuration options in the
50 module that calls :meth:`from_object` or provide an import path to
51 a module that should be loaded. It is also possible to tell it to
52 use the same module and with that provide the configuration values
53 just before the call::
54
55 DEBUG = True
56 SECRET_KEY = 'development key'
57 app.config.from_object(__name__)
58
59 In both cases (loading from any Python file or loading from modules),
60 only uppercase keys are added to the config. This makes it possible to use
61 lowercase values in the config file for temporary values that are not added
62 to the config or to define the config keys in the same file that implements
63 the application.
64
65 Probably the most interesting way to load configurations is from an
66 environment variable pointing to a file::
67
68 app.config.from_envvar('YOURAPPLICATION_SETTINGS')
69
70 In this case before launching the application you have to set this
71 environment variable to the file you want to use. On Linux and OS X
72 use the export statement::
73
74 export YOURAPPLICATION_SETTINGS='/path/to/config/file'
75
76 On windows use `set` instead.
77
78 :param root_path: path to which files are read relative from. When the
79 config object is created by the application, this is
80 the application's :attr:`~flask.Flask.root_path`.
81 :param defaults: an optional dictionary of default values
82 """
83
84 def __init__(self, root_path, defaults=None):
85 dict.__init__(self, defaults or {})
86 self.root_path = root_path
87
88 def from_envvar(self, variable_name, silent=False):
89 """Loads a configuration from an environment variable pointing to
5cc40f4 @akavlie silent option added to 'from_pyfile' to mirror 'from_envvar'.
akavlie authored
90 a configuration file. This is basically just a shortcut with nicer
d0dc89e @justquick in with the new. i have the bits in places where i think they should …
justquick authored
91 error messages for this line of code::
92
93 app.config.from_pyfile(os.environ['YOURAPPLICATION_SETTINGS'])
94
95 :param variable_name: name of the environment variable
6758179 @akavlie Improved botched docstring wording for silent failure.
akavlie authored
96 :param silent: set to `True` if you want silent failure for missing
d0dc89e @justquick in with the new. i have the bits in places where i think they should …
justquick authored
97 files.
98 :return: bool. `True` if able to load config, `False` otherwise.
99 """
100 rv = os.environ.get(variable_name)
101 if not rv:
102 if silent:
103 return False
104 raise RuntimeError('The environment variable %r is not set '
105 'and as such configuration could not be '
106 'loaded. Set this variable and make it '
107 'point to a configuration file' %
108 variable_name)
109 self.from_pyfile(rv)
110 return True
111
5cc40f4 @akavlie silent option added to 'from_pyfile' to mirror 'from_envvar'.
akavlie authored
112 def from_pyfile(self, filename, silent=False):
d0dc89e @justquick in with the new. i have the bits in places where i think they should …
justquick authored
113 """Updates the values in the config from a Python file. This function
114 behaves as if the file was imported as module with the
115 :meth:`from_object` function.
116
117 :param filename: the filename of the config. This can either be an
118 absolute filename or a filename relative to the
119 root path.
6758179 @akavlie Improved botched docstring wording for silent failure.
akavlie authored
120 :param silent: set to `True` if you want silent failure for missing
5cc40f4 @akavlie silent option added to 'from_pyfile' to mirror 'from_envvar'.
akavlie authored
121 files.
34a4947 @mitsuhiko Documented some changes in config handling.
authored
122
123 .. versionadded:: 0.7
124 `silent` parameter.
d0dc89e @justquick in with the new. i have the bits in places where i think they should …
justquick authored
125 """
126 filename = os.path.join(self.root_path, filename)
405c299 @jbweber Updated from_pyfile so its dynamic module creation uses the imp modul…
jbweber authored
127 d = imp.new_module('config')
d0dc89e @justquick in with the new. i have the bits in places where i think they should …
justquick authored
128 d.__file__ = filename
778e44e @mitsuhiko Improved error message for configuration files
authored
129 try:
130 execfile(filename, d.__dict__)
131 except IOError, e:
5cc40f4 @akavlie silent option added to 'from_pyfile' to mirror 'from_envvar'.
akavlie authored
132 if silent and e.errno in (errno.ENOENT, errno.EISDIR):
133 return False
778e44e @mitsuhiko Improved error message for configuration files
authored
134 e.strerror = 'Unable to load configuration file (%s)' % e.strerror
135 raise
d0dc89e @justquick in with the new. i have the bits in places where i think they should …
justquick authored
136 self.from_object(d)
5cc40f4 @akavlie silent option added to 'from_pyfile' to mirror 'from_envvar'.
akavlie authored
137 return True
d0dc89e @justquick in with the new. i have the bits in places where i think they should …
justquick authored
138
139 def from_object(self, obj):
140 """Updates the values from the given object. An object can be of one
141 of the following two types:
142
143 - a string: in this case the object with that name will be imported
144 - an actual object reference: that object is used directly
145
146 Objects are usually either modules or classes.
147
ea77d5e @rduplain Touch up docs according to user feedback.
rduplain authored
148 Just the uppercase variables in that object are stored in the config.
149 Example usage::
d0dc89e @justquick in with the new. i have the bits in places where i think they should …
justquick authored
150
151 app.config.from_object('yourapplication.default_config')
152 from yourapplication import default_config
153 app.config.from_object(default_config)
154
155 You should not use this function to load the actual configuration but
156 rather configuration defaults. The actual config should be loaded
157 with :meth:`from_pyfile` and ideally from a location not within the
158 package because the package might be installed system wide.
159
160 :param obj: an import name or object
161 """
162 if isinstance(obj, basestring):
163 obj = import_string(obj)
164 for key in dir(obj):
165 if key.isupper():
166 self[key] = getattr(obj, key)
167
168 def __repr__(self):
169 return '<%s %s>' % (self.__class__.__name__, dict.__repr__(self))
Something went wrong with that request. Please try again.