代码如下:
1.main.py
from flask import Flask from config import DevConfig app=Flask(__name__) app.config.from_object(DevConfig) @app.route('/') def home(): return "<h1>Hello Wcf!</h1>" if __name__=='__main__': app.run()
2.config.py
class Config(object):
pass
class ProdConfig(Config):
pass
class DevConfig(Config):
DEBUG=True
想了解一下,app.config.from_boject...是如何运作的,跟踪到源代码中:
在flask的config.py中,有一个方法,是:
def from_object(self, obj):
"""Updates the values from the given object. An object can be of one
of the following two types:
- a string: in this case the object with that name will be imported
- an actual object reference: that object is used directly
Objects are usually either modules or classes. :meth:`from_object`
loads only the uppercase attributes of the module/class. A ``dict``
object will not work with :meth:`from_object` because the keys of a
``dict`` are not attributes of the ``dict`` class.
Example of module-based configuration::
app.config.from_object('yourapplication.default_config')
from yourapplication import default_config
app.config.from_object(default_config)
You should not use this function to load the actual configuration but
rather configuration defaults. The actual config should be loaded
with :meth:`from_pyfile` and ideally from a location not within the
package because the package might be installed system wide.
See :ref:`config-dev-prod` for an example of class-based configuration
using :meth:`from_object`.
:param obj: an import name or object
"""
if isinstance(obj, string_types):
obj = import_string(obj)
for key in dir(obj):
if key.isupper():
self[key] = getattr(obj, key)
这里,用到了一个dir的python自带的函数,是其代码的关键,那么,dir是干嘛用的么?
在python中任何东西都是对像,一种数据类型,一个模块等,都有自己的属性和方法,除了常用方法外,其它的你不需要全部记住它,交给dir()函数就好了。