1. 啟動(dòng)文件 - manage.py
from flask_script import Manager
from utils.app import create_app
# 創(chuàng)建app
app = create_app()
# 管理啟動(dòng)項(xiàng)目
manage = Manager(app=app)
if __name__ == '__main__':
# 啟動(dòng)項(xiàng)目
manage.run()
2. 創(chuàng)建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對(duì)象,指定static, templates文件夾路徑,讓項(xiàng)目運(yùn)行時(shí)可以直接調(diào)用
app = Flask(__name__,
static_folder=STATIC_DIR,
template_folder=TEMPLATES_DIR)
# 配置
app.config.from_object(Config)
# 注冊(cè)藍(lán)圖
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')
# 初始化(綁定)第三方庫(kù)
init_ext(app)
return app
3. 配置文件 - config.py
from utils.functions import get_mysqldb_url, get_redisdb_url
class Config():
# 配置數(shù)據(jù)庫(kù)
SQLALCHEMY_DATABASE_URI = get_mysqldb_url()
SQLALCHEMY_TRACK_MODIFICATIONS = False
# 配置session
SESSION_TYPE = 'redis'
SESSION_REDIS = get_redisdb_url()
4. 注冊(cè)插件,綁定數(shù)據(jù)庫(kù)方法的保存文件 - functions.py
import redis
from flask_session import Session
from app.models import db
from app.setting import MYSQL_DATABASES, REDIS_DATABASES
# 注冊(cè)插件
def init_ext(app):
# 綁定數(shù)據(jù)庫(kù)和app
db.init_app(app)
# 綁定session 和app
sess = Session()
sess.init_app(app=app)
return app
# 配置mysql數(shù)據(jù)庫(kù)
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數(shù)據(jù)庫(kù)
def get_redisdb_url():
host = REDIS_DATABASES['HOST']
port = REDIS_DATABASES['PORT']
return redis.Redis(host=host, port=port)
5. 路徑,數(shù)據(jù)庫(kù)基礎(chǔ)設(shè)置文件 - setting.py
import os
# 基礎(chǔ)路徑(項(xiàng)目)
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')
# ========數(shù)據(jù)庫(kù)配置
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. 文件關(guān)聯(lián)關(guān)系示意
注意: 各文件引入其它文件內(nèi)容需導(dǎo)入, 調(diào)用Flask或者第三方庫(kù),也需導(dǎo)入