最新消息:20210816 当前crifan.com域名已被污染,为防止失联,请关注(页面右下角的)公众号

【已解决】Flask中增加不同环境的app的config配置

Flask crifan 5424浏览 0评论

折腾:

【已解决】把Python3的Flask部署到远程CentOS7服务器

期间,已经实现了:

Mac本地:开发和部署Flask,且正常运行了

远程CentOS服务器:开发和部署Flask,且正常运行了

但是有些配置不太一样,比如mongo的host等等

而之前就用过,也看到过帖子介绍,最好根据不同环境,设置不同参数。

所以就去搞清楚,此处Flask中如何实现两套不同环境,加载不同的配置。

之前看到的:

Build a RESTful API with Flask – The TDD Way ― Scotch

的:

# /instance/config.py

看起来就很不错,抽空参考。

flask app different environment config

Configuration Handling — Flask Documentation (0.12)

http://flask.pocoo.org/docs/0.12/config/#development-production

有机会去试试:

Deploying with Fabric — Flask Documentation (0.12)

Flask application configuration using an environment variable and YAML

python – Flask: How to manage different environment databases? – Stack Overflow

Configuration Handling — Flask Documentation (0.12)

“The instance folder is designed to not be under version control and be deployment specific。It’s the perfect place to drop things that either change at runtime or configuration files.”

How to Configure a Flask Application

到底有哪些可以配置的值,参考:

Configuration Handling — Flask Documentation (0.12)

而Flask有这些加载配置的方式:

  • file-based

    • app.config.from_pyfile(‘config_file.cfg’)

    • INI file syntax

    • DEBUG=True

  • object-based

    • class BaseConfig(object):

    •     DEBUG = False

    •     TESTING = False

    • class DevelopmentConfig(BaseConfig):

    •     DEBUG = True

    •     TESTING = True

    • class TestingConfig(BaseConfig):

    •     DEBUG = False

    •     TESTING = True

    • app.config.from_object(‘module_name.DevelopmentConfig’)

  • environment-variable-based

    • app.config.from_envvar(‘FLASK_CONFIG_FILE’)

    • FLASK_CONFIG_FILE environment variable points to the configuration file

  • instance-folders-based

    • The instance folder is designed not to be under source control and could store sensitive information

    • This instance folder should be directly deployed on the production server.

    • 用法:

      • 绝对路径:

        • app = Flask(__name__, instance_path=’/path/to/instance/folder’)

      • 相对路径:

        • app = Flask(__name__, instance_relative_config=True) # (2)

        • app.config.from_pyfile(‘flask.cfg’)

Best Practice:

Good practice is to have a default configuration, which is under source control and to override it with sensitive and specific information kept in instance folders.

【总结】

此处,暂时用:

和app.py同目录下新建一个:

config.py

<code>class BaseConfig(object):
    DEBUG = False

    FLASK_PORT = 12345
    # FLASK_HOST = "127.0.0.1"
    # FLASK_HOST = "localhost"
    # Note:
    # 1. to allow external access this server
    # 2. make sure here gunicorn parameter "bind" is same with here !!!
    FLASK_HOST = "0.0.0.0"


    # default to production sever's local mongodb
    MONGODB_HOST = "localhost"
    MONGODB_PORT = 32018
    MONGODB_USERNAME = "gridfs"
    MONGODB_PASSWORD = “xxx"
    MONGODB_AUTH_SOURCE = "gridfs"

    # Flask app name
    FLASK_APP_NAME = "RobotQA"

    # Log File
    LOG_FILE_FILENAME = "logs/" + FLASK_APP_NAME + ".log"
    LOG_FORMAT = "[%(asctime)s %(levelname)s %(filename)s:%(lineno)d %(funcName)s] %(message)s"
    LOF_FILE_MAX_BYTES = 2*1024*1024
    LOF_FILE_BACKUP_COUNT = 10

    # reuturn file url's host
    # FILE_URL_HOST = FLASK_HOST
    FILE_URL_HOST = "127.0.0.1"


class DevelopmentConfig(BaseConfig):
    DEBUG = True
    # for local dev, need access remote mongodb
    MONGODB_HOST = "x.x.x.x"
    FILE_URL_HOST = "127.0.0.1"


class ProductionConfig(BaseConfig):
    FILE_URL_HOST = "x.x.x.x"
</code>

然后app.py去引用:

<code>app = Flask(__name__)
app.config.from_object('config.DevelopmentConfig')
# app.config.from_object('config.ProductionConfig’)

</code>

logFormatterStr = app.config[“LOG_FORMAT”]

fileHandler = RotatingFileHandler(

    app.config[‘LOG_FILE_FILENAME’],

    maxBytes=app.config[“LOF_FILE_MAX_BYTES”],

    backupCount=app.config[“LOF_FILE_BACKUP_COUNT”],

    encoding=”UTF-8”)

purePymongo = MongoClient(

    host=app.config[“MONGODB_HOST”],

    port=app.config[“MONGODB_PORT”],

    username=app.config[“MONGODB_USERNAME”],

    password=app.config[“MONGODB_PASSWORD”],

    authSource=app.config[“MONGODB_AUTH_SOURCE”]

)

同时,gunicorn中的配置文件:

gunicorn_config.py

<code>import multiprocessing
import os
import sys
sys.path.append(".")
from config import BaseConfig

#currentRootPath = "/Users/crifan/xxx/robotDemo"
currentRootPath = os.getcwd()
print("currentRootPath=%s" % currentRootPath)
flaskHost = BaseConfig.FLASK_HOST
flaskPort = BaseConfig.FLASK_PORT
print("flaskHost=%s, flaskPort=%s" % (flaskHost, flaskPort))


reload = True                                   #当代码改变时自动重启服务
#bind = '127.0.0.1:12345'                        #绑定ip和端口号
# bind = '0.0.0.0:12345'                        #绑定ip和端口号
bind = ("%s:%s" % (flaskHost, flaskPort))
</code>

即可输出:

<code>currentRootPath=/Users/crifan/xxx/robotDemo
flaskHost=0.0.0.0, flaskPort=12345
</code>

后续切换生产环境的话,直接去app.py中修改:

<code>app = Flask(__name__)
# app.config.from_object('config.DevelopmentConfig')
app.config.from_object('config.ProductionConfig’)
</code>

即可。

转载请注明:在路上 » 【已解决】Flask中增加不同环境的app的config配置

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
82 queries in 0.194 seconds, using 22.15MB memory