python flaskフレームワークの構築と基本構成
13834 ワード
Flaskフレームワーク基本構成
プロファイル:
appの作成
プロジェクト開始エントリ:
プロファイル:
import logging
from redis import StrictRedis
class Config(object):
""" """
SECRET_KEY = "iECgbYWReMNxkRprrzMo5KAQYnb2UeZ3bwvReTSt+VSESW0OB8zbglT+6rEcDW9X"
#
SQLALCHEMY_DATABASE_URI = "mysql://root:[email protected]:3306/information27"
SQLALCHEMY_TRACK_MODIFICATIONS = False
# Redis
REDIS_HOST = "127.0.0.1"
REDIS_PORT = 6379
# Session
SESSION_TYPE = "redis"
# session
SESSION_USE_SIGNER = True
# Session redis
SESSION_REDIS = StrictRedis(host=REDIS_HOST, port=REDIS_PORT)
#
SESSION_PERMANENT = False
#
PERMANENT_SESSION_LIFETIME = 86400 * 2
#
LOG_LEVEL = logging.DEBUG
class DevelopmentConfig(Config):
""" """
DEBUG = True
class ProductionConfig(Config):
""" """
DEBUG = False
LOG_LEVEL = logging.WARNING
class TestingConfig(Config):
""" """
DEBUG = True
TESTING = True
config = {
"development": DevelopmentConfig,
"production": ProductionConfig,
"testing": TestingConfig
}
appの作成
import logging
from logging.handlers import RotatingFileHandler
from flask import Flask
# session
from flask.ext.session import Session
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.wtf import CSRFProtect
from redis import StrictRedis
from config import config
#
# Flask , init_app
db = SQLAlchemy()
# https://www.cnblogs.com/xieqiankun/p/type_hints_in_python3.html
redis_store = None # type: StrictRedis
# redis_store: StrictRedis = None
def setup_log(config_name):
#
logging.basicConfig(level=config[config_name].LOG_LEVEL) # debug
# , 、 、
file_log_handler = RotatingFileHandler("logs/log", maxBytes=1024 * 1024 * 100, backupCount=10)
#
formatter = logging.Formatter('%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s')
#
file_log_handler.setFormatter(formatter)
# (flask app )
logging.getLogger().addHandler(file_log_handler)
def create_app(config_name):
# , ,
setup_log(config_name)
# Flask
app = Flask(__name__)
#
app.config.from_object(config[config_name])
# app
db.init_app(app)
# redis
global redis_store
redis_store = StrictRedis(host=config[config_name].REDIS_HOST, port=config[config_name].REDIS_PORT)
# CSRF ,
CSRFProtect(app)
# session
Session(app)
# csrf cookie
@app.after_request
def after_request(response):
# csrf_token
csrf_token = generate_csrf()
# cookie
response.set_cookie("csrf_token", csrf_token)
return response
#
from info.modules.index import index_blu
app.register_blueprint(index_blu)
return app
プロジェクト開始エントリ:
from flask_script import Manager
from flask_migrate import Migrate, MigrateCommand
from info import create_app, db, models
# manage.py , ,
# app
# app
# create_app
app = create_app('development')
manager = Manager(app)
# app db
Migrate(app, db)
# manager
manager.add_command('db', MigrateCommand)
if __name__ == '__main__':
manager.run()