Flask project database configuration, redis configuration, session configuration, csrf configuration, log configuration

1. In the app.py file
from datetime import timedelta
from flask_wtf.csrf import CSRFProtect
from flask import Flask, session
from flask_sqlalchemy import SQLAlchemy
from redis import StrictRedis
from flask_session import Session

app = Flask(__name__)


classConfig():
    #Debug information
    DEBUG = True
    SECRET_KEY = 'fjsiogkgnmdinging'

    # Database information
    SQLALCHEMY_DATABASE_URI = 'mysql + pymysql://root:123456@localhost:3306/info36'
    SQLALCHEMY_TRACK_MODIFICATIONS = False

    # redis configuration
    REDIS_HOST = '127.0.0.1'
    REDIS_PORT = 6379

    # session configuration
    SESSION_TYPE = 'redis' #Set the storage type of session
    SESSION_REDIS = StrictRedis(host=REDIS_HOST, port=REDIS_PORT) # Specify the server where the session is stored
    # SESSION_USE_SIGNER = True # Set signature storage
    PERMANENT_SESSION_LIFETIME = timedelta(days=1) #Set signature expiration time


app.config.from_object(Config)

#Create a database association object and associate it with the app
db = SQLAlchemy(app)

#Create redis object
# When decode_responses is set to True, the string data returned by Redis will be decoded into the Python string type. This makes it easy to process text data stored in Redis.
# When decode_responses is set to False (default value), the string data returned by Redis will be returned in the form of byte strings (bytes).
# This may be more appropriate when working with binary data or needing to interact with other Redis clients
redis_store = StrictRedis(host=Config.REDIS_HOST, port=Config.REDIS_PORT, decode_responses=True)

#Create session object
Session(app)

# Use CSRFProtect to protect app
CSRFProtect(app)


@app.route('/', methods=['GET', 'POST'])
def hello_world():
    # Test redis access data
    redis_store.set("name", "laowang")
    print(redis_store.get("name"))

    # Test session access
    session["name"] = "zhangsan"
    print(session.get("name"))
    return "helloworld"


if __name__ == '__main__':
    app.run()
2. Writing them together in this way is inconvenient for subsequent development, so we extracted them
1. Extract the configuration class, put the configuration information into the config.py file in the project root directory, and then import it into the app.py file.
from datetime import timedelta

from redis import StrictRedis


classConfig():
    #Debug information
    DEBUG = True
    SECRET_KEY = 'fjsiogkgnmdinging'

    # Database information
    SQLALCHEMY_DATABASE_URI = 'mysql + pymysql://root:123456@localhost:3306/info36'
    SQLALCHEMY_TRACK_MODIFICATIONS = False

    # redis configuration
    REDIS_HOST = '127.0.0.1'
    REDIS_PORT = 6379

    # session configuration
    SESSION_TYPE = 'redis' #Set the storage type of session
    SESSION_REDIS = StrictRedis(host=REDIS_HOST, port=REDIS_PORT) # Specify the server where the session is stored
    # SESSION_USE_SIGNER = True # Set signature storage
    PERMANENT_SESSION_LIFETIME = timedelta(days=1) #Set signature expiration time

    # Configure the default log level
    LEVEL_NAME = logging.DEBUG


# Development environment configuration information
class DevelopConfig(Config):
    pass


# Production (online) environment configuration information
class ProductConfig(Config):
    DEBUG = False


#Test environment configuration information
class TestConfig(Config):
    pass


# Provide a unified access entrance
config_dict = {
    "develop": DevelopConfig,
    "product": ProductConfig,
    "test": TestConfig
}
2. Extract the initialization information and create a package in the project root directory. The package name is related to the project name. And put the initialization information in the init.py file, mainly to create a create_app method for easy calling
from flask_wtf.csrf import CSRFProtect
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from redis import StrictRedis
from flask_session import Session

from config import Config, config_dict


def create_app(config_name):
    app = Flask(__name__)

    # Get config configuration
    config = config_dict.get(config_name)

    app.config.from_object(config)


    # Call the log method to record program running information
    log_file(config.LEVEL_NAME)


    #Create a database association object and associate it with the app
    db = SQLAlchemy(app)

    #Create redis object
    # When decode_responses is set to True, the string data returned by Redis will be decoded into the Python string type. This makes it easy to process text data stored in Redis.
    # When decode_responses is set to False (default value), the string data returned by Redis will be returned in the form of byte strings (bytes).
    # This may be more appropriate when working with binary data or needing to interact with other Redis clients
    redis_store = StrictRedis(host=config.REDIS_HOST, port=config.REDIS_PORT, decode_responses=True)

    #Create session object
    Session(app)

    # Use CSRFProtect to protect app
    CSRFProtect(app)

    return app


def log_file(LEVEL_NAME):
    #Set the log recording level. There are four common ones, DEBUG<INFO<WARNING<ERROR
    logging.basicConfig(level=LEVEL_NAME) #Debug debug level
    #Create a logger and specify the path where the log is saved, the maximum size of each log file, and the upper limit of the number of log files saved.
    file_log_handler = RotatingFileHandler("logs/log", maxBytes=1024 * 1024 * 100, backupCount=10)
    # Create the format of the log record. Log level. Enter the file name and line number of the log information. Log information.
    formatter = logging.Formatter('%(levelname)s %(filename)s:%(lineno)d %(message)s')
    # Set the logging format for the newly created logger
    file_log_handler.setFormatter(formatter)
    # Add a logger to the global logging tool object (used by flask app)
    logging.getLogger().addHandler(file_log_handler)
3. Extraction of view functions, the view functions must be placed in the init file in the corresponding module,
########### 1. Create ################## in the init file under the module package index

from flask import Blueprint

#Create blueprint object
index_blue = Blueprint('/index',__name__)

#Introduce views
from info.modules.index import view
#################2. Use ###################### in the view file

from info.modules.index import index_blue


@index_blue.route('/', methods=['GET', 'POST'])
def hello_world():
    return "helloworld"
###################3. Register the blueprint in init.py in the project file#############

from flask_wtf.csrf import CSRFProtect
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from redis import StrictRedis
from flask_session import Session
from config import config_dict


def create_app(config_name):
    app = Flask(__name__)

    # Get config configuration
    config = config_dict.get(config_name)

    app.config.from_object(config)

    #Create a database association object and associate it with the app
    db = SQLAlchemy(app)

    #Create redis object
    # When decode_responses is set to True, the string data returned by Redis will be decoded into the Python string type. This makes it easy to process text data stored in Redis.
    # When decode_responses is set to False (default value), the string data returned by Redis will be returned in the form of byte strings (bytes).
    # This may be more appropriate when working with binary data or needing to interact with other Redis clients
    redis_store = StrictRedis(host=config.REDIS_HOST, port=config.REDIS_PORT, decode_responses=True)

    #Create session object
    Session(app)

    # Use CSRFProtect to protect app
    CSRFProtect(app)

    #Registration blueprint
    from info.modules.index import index_blue
    app.register_blueprint(index_blue)

    return app