无法在Flask中使用环境变量

时间:2019-12-16 23:21:25

标签: python flask

我要使用CLIENT_IDinstances/application.cfg进行current_app的设置。

错误:

  

KeyError:'CLIENT_ID'

from flask import current_app

# Authentication
@app.route('/auth/redirect', methods=['GET'])
def authorize():
    client_id = current_app.config['CLIENT_ID']

app / instance / application.cfg

CLIENT_ID='XXXXXXXXXXXXXXXXXXXXXX'
CLIENT_SECRET='XXXXXXXXXXXXXXXXXX'

app / config.py

import os

class BaseConfig(object):
    SQLALCHEMY_TRACK_MODIFICATIONS = False  

class DevelopmentConfig(BaseConfig):
    DEBUG = True
    TESTING = True
    SQLALCHEMY_DATABASE_URI = 'sqlite:///app.db'

class ProductionConfig(BaseConfig):
    DEBUG = True
    TESTING = True
    SQLALCHEMY_DATABASE_URI=os.environ.get('DATABASE_URL')

config = {
    "default": "main.config.BaseConfig",
    "development": "main.config.DevelopmentConfig",
    "production": "main.config.ProductionConfig",
}

def configure_app(app):
    config_name= os.getenv('FLASK_ENV')
    app.config.from_object(config[config_name])
    app.config.from_pyfile('application.cfg', silent=True)

app / __ init __。py

# Initialized app
app = Flask(__name__, instance_relative_config=True)
configure_app(app)

1 个答案:

答案 0 :(得分:1)

from flask import Flask
from config import DevelopmentConfig

app = Flask(__name__)
app.config.from_object(DevelopmentConfig)

@app.route('/auth/redirect', methods=['GET'])
def authorize():
    client_id = current_app.config['CLIENT_ID']

app / config.py

class BaseConfig:
    SQLALCHEMY_TRACK_MODIFICATIONS = False
    CLIENT_ID='XXXXXXXXXXXXXXXXXXXXXX'
    CLIENT_SECRET='XXXXXXXXXXXXXXXXXX'

class DevelopmentConfig(BaseConfig):
    DEBUG = True
    TESTING = True
    SQLALCHEMY_DATABASE_URI = 'sqlite:///app.db'

class ProductionConfig(BaseConfig):
    DEBUG = True
    TESTING = True
    SQLALCHEMY_DATABASE_URI=os.environ.get('DATABASE_URL')

希望对您有帮助