zoukankan      html  css  js  c++  java
  • flask config 环境变量配置

    https://zhuanlan.zhihu.com/p/24055329

    从环境变量中读取配置

    对于不适合写在程序里的配置,比如密码等,需要把配置写入系统环境变量,然后使用os模块的getenv()方法获取,第二个参数作为默认值

    set MAIL_USERNAME=me@greyli.com  # windows
    export MAIL_USERNAME=me@greyli.com  # *unix
    import os
    from flask import Flask
    
    app = Flask(__name__)
    app.config['MAIL_USERNAME'] = os.getenv('MAIL_USERNAME', 'me@greyli.com')

    直接写入主脚本

    当你的程序很小的时候,可以直接把配置写在主脚本里

    from flask import Flask
    
    app = Flask(__name__)
    app.config['SECRET_KEY'] = 'some secret words'
    app.config['DEBUG'] = True
    app.config['ITEMS_PER_PAGE'] = 10

    使用字典的update方法可以简化代码

    from flask import Flask
    
    app = Flask(__name__)
    app.config.update(
        DEBUG=True,
        SECRET_KEY='some secret words',
        ITEMS_PER_PAGE=10
    )

    单独的配置文件

    程序逐渐变大时,配置也逐渐增多,写在主脚本里太占地方,不够优雅。我们可以创建一个单独的配置文件。和上面同样的配置,现在可以改写为

    config.py

    import os
    basedir = os.path.abspath(os.path.dirname(__file__))
    
    
    class BaseConfig:  # 基本配置类
        SECRET_KEY = os.getenv('SECRET_KEY', 'some secret words')
        ITEMS_PER_PAGE = 10
    
    
    class DevelopmentConfig(BaseConfig):
        DEBUG = True
        SQLALCHEMY_DATABASE_URI = os.getenv('DEV_DATABASE_URL', 'sqlite:///' + os.path.join(basedir, 'data-dev.sqlite')
    
    
    class TestingConfig(BaseConfig):
        TESTING = True
        SQLALCHEMY_DATABASE_URI = os.getenv('TEST_DATABASE_URL', 'sqlite:///' + os.path.join(basedir, 'data-test.sqlite')
        WTF_CSRF_ENABLED = False
    
    
    config = {
        'development': DevelopmentConfig,
        'testing': TestingConfig,
        'default': DevelopmentConfig
    }

    通过from_object()方法导入配置

    from config import config  # 导入存储配置的字典
    
    ...
    app = Flask(__name__)
    app.config.from_object(config['development'])  # 获取相应的配置类
    ...


    # 通过此方法得到配置文件的值
    current_app.config['SQLALCHEMY_DATABASE_URI']
  • 相关阅读:
    CopyOnWriteArrayList与ConcurrentHashMap
    Latch、Barrier、ThreadLocal
    Future和FutureTask
    SingleThreadExecutor、FixedThreadExecutor、CachedThreadPool、ScheduledThreadPoolExecutor
    ThreadPoolExecutor
    ConcurrentLinkedQueue
    PriorityBlockingQueue
    pom activeByDefault 不生效
    配置log4j2日志报错 Cannot find the declaration of element 'Configuration'
    顶级技术盛会KubeCon 2020,网易轻舟布道多云环境云原生应用交付
  • 原文地址:https://www.cnblogs.com/mlllily/p/12188142.html
Copyright © 2011-2022 走看看