1. 目录结构
2. 入口文件app.py
from manger import create_app, db
from flask_migrate import Migrate
from manger import models
# 传入settings参数,开发版本“develop”,线上版本“product”
app = create_app('develop')
# 数据库设置
migrate = Migrate(app, db)
@app.route('/')
def hello_world(): # put application's code here
return 'Hello World!'
if __name__ == '__main__':
app.run()
3. 配置文件config.py
import logging
import os
from datetime import timedelta
# from redis import StrictRedis
class Config():
# 调试信息
DEBUG = True
SECRET_KEY = os.urandom(16)
# 数据库信息
MYSQL_DIALECT = 'mysql'
MYSQL_DIRVER = 'pymysql'
MYSQL_NAME = 'root'
MYSQL_PWD = '123456'
MYSQL_HOST = 'localhost'
MYSQL_PORT = 3306
MYSQL_DB = 'manger'
MYSQL_CHARSET = 'utf8mb4'
SQLALCHEMY_DATABASE_URI = f'{MYSQL_DIALECT}+{MYSQL_DIRVER}://{MYSQL_NAME}:{MYSQL_PWD}@{MYSQL_HOST}:{MYSQL_PORT}/{MYSQL_DB}?charset={MYSQL_CHARSET}'
SQLALCHEMY_TRACK_MODIFICATIONS = True
# redis配置
REDIS_HOST = '127.0.0.1'
REDIS_PORT = 6379
# session配置
# SESSION_TYPE = 'redis' # 设置session的存储类型
# SESSION_REDIS = StrictRedis(host=REDIS_HOST, port=REDIS_PORT) # 指定session存储的服务器
# SESSION_USE_SIGNER = True # 设置签名存储
PERMANENT_SESSION_LIFETIME = timedelta(days=1) # 设置签名过期时间
# 配置默认的log等级
LEVEL_NAME = logging.DEBUG
# 开发环境配置信息
class DevelopConfig(Config):
pass
# 生产(线上)环境配置信息
class ProductConfig(Config):
DEBUG = False
# 测试环境配置信息
class TestConfig(Config):
pass
# 提供一个统一的访问入口
config_dict = {
"develop": DevelopConfig,
"product": ProductConfig,
"test": TestConfig
}
4. 项目包的init.py文件
import logging
from logging.handlers import RotatingFileHandler
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from config import Config, config_dict
db = SQLAlchemy()
def create_app(config_name):
app = Flask(__name__)
# 获取config配置
config = config_dict.get(config_name)
app.config.from_object(config)
# 调用日志方法,记录程序运行信息
log_file(config.LEVEL_NAME)
# 创建数据库关联对象并关联app
db.init_app(app)
# 创建redis对象
# 当 decode_responses 设置为 True 时,Redis 返回的字符串数据将会被解码为 Python 字符串类型。这样可以方便地处理 Redis 中存储的文本数据。
# 而当 decode_responses 设置为 False(默认值)时,Redis 返回的字符串数据将会以字节字符串(bytes)的形式返回。
# 这在处理二进制数据或者需要与其他 Redis 客户端进行交互时可能更为合适
# redis_store = StrictRedis(host=config.REDIS_HOST, port=config.REDIS_PORT, decode_responses=True)
# 创建session对象
# Session(app)
# 注册蓝图
from manger.user import user_blue
app.register_blueprint(user_blue)
return app
def log_file(LEVEL_NAME):
# 设置日志的记录等级,常见的有四种,DEBUG
5. app文件的init.py 和 views.py 文件
from flask import Blueprint
user_blue = Blueprint('user', __name__, url_prefix='/user') # url_prefix设置名称用于区分
# 引入view
from manger.user import views
from . import user_blue
@user_blue.route('/getUser', methods=['GET'])
def getUser():
return 'ok'
6. 数据库模型models.py
from manger import db
from datetime import datetime
from werkzeug.security import generate_password_hash, check_password_hash
class BaseModel:
create_time = db.Column(db.DateTime, default=datetime.now, doc='创建时间')
# onupdate=datetime.now 更改后的时间
update_time = db.Column(db.DateTime, default=datetime.now, onupdate=datetime.now, doc='修改时间')
class User(db.Model, BaseModel):
"""
姓名,密码,年龄,性别,出生日期,家庭地址,创建时间,修改时间
"""
__tablename__ = 'user'
class GENDER:
MALE = 0
FEMALE = 1
class Level:
ADMIN = 0
USER = 0
id = db.Column('user_id', db.Integer, primary_key=True, doc='用户ID')
name = db.Column(db.String(12), doc='用户姓名')
pwd = db.Column(db.String(12), doc='密码')
gender = db.Column(db.Integer, default=GENDER.FEMALE, doc='性别')
birthday = db.Column(db.Date, doc='生日')
address = db.Column(db.String(25), doc='地址')
level = db.Column(db.Integer, default=Level.ADMIN, doc='用户等级')
# 当用户访问时会通过这个传出pwd
@property
def password(self):
return self.pwd
# 加密密码,用户输入的密码会先传入这进行加密
@password.setter
def password(self, t_pwd):
self.pwd = generate_password_hash(t_pwd)
# 校验密码,会将数据库中密码解密然后比对用户输入的密码
def check_password(self, t_pwd):
return check_password_hash(self.pwd, t_pwd)
def to_dict(self):
return {
"id": self.id,
"name": self.name,
"password": self.password,
"gender": self.gender,
"birthday": self.birthday,
"address": self.address,
"level": self.level
}