Photo by Seemi Samuel / Unsplash

Background

一直在思考我自己想要的Flask架構. 所以最近想把之前學的Flask(總覺得沒學得很好)在重新整理一遍. 希望能夠加速之後開發一個新的服務的流程. 所以這篇主要先記錄一下一般在網路上常見的主流架構.

Structure

基本上我的需求 Template 是完全用不到的. Route管理也交給前端. 我只負責開API(Json Based). 所以我希望的架構會長的如下:

.
├── app
│   ├── auth
│   ├── __init__.py
│   └── static
├── config.py
├── docs
├── README.md
├── requirements.txt
├── run.py
└── tests

Configuration

參考了一下, 以下的config檔大概會比較符合我的想法.

config.py

import logging
class Config(object):
    DEVELOPMENT = False
    CSRF_ENABLED = True
    SECRET_KEY = '952121ff349e98433908001eccb901288be3616cc470b93e'
    LOGGING_FORMAT = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
    LOGGING_LOCATION = 'YOURAPP.log'
    LOGGING_LEVEL = logging.DEBUG

class ProductionConfig(Config):
    DEBUG = False
    DOMAIN = 'http://127.0.0.1:5000'
    SQLALCHEMY_DATABASE_URI = 'sqlite:///' + sqlite_path

class DevelopmentConfig(Config):
    DEVELOPMENT = True
    DEBUG = True
    DOMAIN = 'http://127.0.0.1:5000'
    SQLALCHEMY_DATABASE_URI = 'sqlite:///' + sqlite_path

class TestingConfig(Config):
    TESTING = True
    DEBUG = True
    DOMAIN = 'http://127.0.0.1:5000'
    SQLALCHEMY_DATABASE_URI = 'sqlite:///' + sqlite_path


config = {
    'development': DevelopmentConfig,
    'testing': TestingConfig,
    'production': ProductionConfig,

    'default': DevelopmentConfig
}

Main

import os
from config import config
from flask import Flask

app = Flask(__name__)
app.config.from_object(config['development'])


@app.route('/')
def hello():
    return "Hello World!"


if __name__ == '__main__':
    app.run()
    print(config['development'])

執行完會得到以下結果. 那整個config設定就告一個段落.

$ python3 run.py
<class 'config.DevelopmentConfig'>
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
 * Restarting with stat
<class 'config.DevelopmentConfig'>
 * Debugger is active!
 * Debugger PIN: 832-525-933

Reference