Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

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