Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

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