1. 启动文件 - manage.py
from flask_script import Manager
from utils.app import create_app
# 创建app
app = create_app()
# 管理启动项目
manage = Manager(app=app)
if __name__ == '__main__':
# 启动项目
manage.run()
2. 创建app文件 - app.py
from flask import Flask
from app.setting import STATIC_DIR, TEMPLATES_DIR
from app.user_views import user_blue
from app.house_views import house_blue
from app.order_views import order_blue
from utils.config import Config
from utils.functions import init_ext
def create_app():
# 初始化flask对象,指定static, templates文件夹路径,让项目运行时可以直接调用
app = Flask(__name__,
static_folder=STATIC_DIR,
template_folder=TEMPLATES_DIR)
# 配置
app.config.from_object(Config)
# 注册蓝图
app.register_blueprint(blueprint=user_blue, url_prefix='/user')
app.register_blueprint(blueprint=house_blue, url_prefix='/house')
app.register_blueprint(blueprint=order_blue, url_prefix='/order')
# 初始化(绑定)第三方库
init_ext(app)
return app
3. 配置文件 - config.py
from utils.functions import get_mysqldb_url, get_redisdb_url
class Config():
# 配置数据库
SQLALCHEMY_DATABASE_URI = get_mysqldb_url()
SQLALCHEMY_TRACK_MODIFICATIONS = False
# 配置session
SESSION_TYPE = 'redis'
SESSION_REDIS = get_redisdb_url()
4. 注册插件,绑定数据库方法的保存文件 - functions.py
import redis
from flask_session import Session
from app.models import db
from app.setting import MYSQL_DATABASES, REDIS_DATABASES
# 注册插件
def init_ext(app):
# 绑定数据库和app
db.init_app(app)
# 绑定session 和app
sess = Session()
sess.init_app(app=app)
return app
# 配置mysql数据库
def get_mysqldb_url():
driver = MYSQL_DATABASES['DRIVER']
dh = MYSQL_DATABASES['DH']
root = MYSQL_DATABASES['ROOT']
password = MYSQL_DATABASES['PASSWORD']
host = MYSQL_DATABASES['HOST']
port = MYSQL_DATABASES['PORT']
name = MYSQL_DATABASES['NAME']
return '{}+{}://{}:{}@{}:{}/{}'.format(driver, dh, root, password, host, port, name)
# 配置REDIS数据库
def get_redisdb_url():
host = REDIS_DATABASES['HOST']
port = REDIS_DATABASES['PORT']
return redis.Redis(host=host, port=port)
5. 路径,数据库基础设置文件 - setting.py
import os
# 基础路径(项目)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# template 路径
TEMPLATES_DIR = os.path.join(BASE_DIR, 'templates')
# static 路径
STATIC_DIR = os.path.join(BASE_DIR, 'static')
# meida 路径
MEDIA_DIR = os.path.join(STATIC_DIR, 'media')
# 保存图片的路径
UPLOAD_DIR = os.path.join(MEDIA_DIR, 'upload')
# 保存房屋图片的路径
HOUSE_DIR = os.path.join(UPLOAD_DIR, 'house')
# ========数据库配置
MYSQL_DATABASES = {
'DRIVER': 'mysql',
'DH': 'pymysql',
'ROOT': 'root',
'PASSWORD': '123456',
'HOST': '127.0.0.1',
'PORT': 3306,
'NAME': 'ajzf'
}
REDIS_DATABASES = {
'HOST': '127.0.0.1',
'PORT': '6379'
}
6. 文件关联关系示意
注意: 各文件引入其它文件内容需导入, 调用Flask或者第三方库,也需导入