zoukankan      html  css  js  c++  java
  • flask学习:如何从config里载入配置

    代码如下:

    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()函数就好了。

    dir()函数操作方法很简单,只需要把你想要查询和对像添写到( )括号中就可以使用了。

  • 相关阅读:
    2月3日
    照片测试
    家属签证计时
    我来了
    090204 阴天
    重要提醒to 小爱
    小毛小毛
    C++Primer学习日程
    资料库字段存储文件记录的方式
    本日有点忙
  • 原文地址:https://www.cnblogs.com/aomi/p/7238468.html
Copyright © 2011-2022 走看看