一、项目基本结构
1、 exts.py
存在的目的:在Python中,如果两个或更多模块(文件)相互导入对方,就会形成导入循环。例如,模块A导入了模块B,同时模块B又导入了模块A,这就会导致导入循环。
比如在这个项目中如果在app.py 中定义db,在models.py中使用app.py 中的db,又在app.py 中使用models.py 中的ORM模型,这样就导致app.py 和models.py 互相引用。
python
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
2、 config.py
存放一些公共的配置信息,比如数据库信息,邮箱信息等
python
PORT = 3306
HOSTNAME = "127.0.0.1"
USERNAME = "root"
PASSWORD = 密码
DATABASE = 数据库名称
DB_URI = 'mysql+pymysql://{}:{}@{}:{}/{}?charset=utf8'.format(USERNAME, PASSWORD, HOSTNAME, PORT, DATABASE)
SQLALCHEMY_DATABASE_URI = DB_URI
SQLALCHEMY_TRACK_MODIFICATIONS = False
4、view.py
编写视图相关的代码!!
python
from flask import Blueprint, render_template
bp = Blueprint('front', __name__, url_prefix='/')
@bp.route('/')
def index():
return render_template('front/index.html')
6、models.py
编写ORM模型
python
from datetime import datetime
from werkzeug.security import generate_password_hash, check_password_hash
from exts import db
import shortuuid
import enum
class Gender(enum.Enum):
MALE = 1
FEMALE = 2
SECRET = 3
UNKNOW = 4
class FrontUser(db.Model):
__tablename__ = 'user'
# 从安全角度考虑,前台用户id不能再使用自增长,
id = db.Column(db.String(100), primary_key=True, default=shortuuid.uuid)
telephone = db.Column(db.String(100), unique=True, nullable=False)
username = db.Column(db.String(20), nullable=False)
_password = db.Column(db.String(200), nullable=False)
email = db.Column(db.String(50), unique=True)
realname = db.Column(db.String(50))
avatar = db.Column(db.String(100))
signature = db.Column(db.String(200))
gender = db.Column(db.Enum(Gender), default=Gender.UNKNOW)
join_time = db.Column(db.DateTime, default=datetime.now)
# 所以需要重写__init__构造函数,将password的值取出
def __int__(self, *args, **kwargs):
if "password" in kwargs:
self.password = kwargs.get('password')
kwargs.pop("password")
super(FrontUser, self).__init__(*args, **kwargs)
@property
def password(self):
return self._password
@password.setter
def password(self, row_password):
self._password = generate_password_hash(row_password)
def check_password(self, row_password):
return check_password_hash(self.password, row_password)
7、form.py
存放该项目中的后台数据验证
python
class LoginForm(BaseForm):
telephone = StringField(validators=[Regexp(r"^1[34789]\d{9}", message="手机号码格式错误!")])
password = StringField(validators=[Regexp(r"^[0-9a-zA-Z_\.]{6,20}$", message="密码必须是由6-20位数字、字母组成。")])
remember = IntegerField()
8、manage.py
python
from flask_script import Manager
from flask_migrate import Migrate, MigrateCommand
from exts import db
from app import create_app
from apps.front import models as front_models
FrontUser = front_models.FrontUser
app = create_app()
manager = Manager(app)
Migrate(app, db)
manager.add_command('db', MigrateCommand)
# 前台用户
@manager.option('-t', '--telephone', dest='telephone')
@manager.option('-p', '--password', dest='password')
@manager.option('-u', '--username', dest='username')
def create_front_user(telephone, password, username):
font_user = FrontUser(telephone=telephone, password=password, username=username)
db.session.add(font_user)
db.session.commit()
if __name__ == '__main__':
manager.run()
3、app.py
python
from flask import Flask
from exts import db
from apps.front.views import bp as front_bp
import config
def create_app():
app = Flask(__name__)
app.config.from_object(config)
db.init_app(app)
app.register_blueprint(front_bp)
return app
if __name__ == '__main__':
app = create_app()
app.run()
二、将ORM映射到数据库中
- 初始化迁移文件 python manage.py db init
- 将模型的映射添加到文件中 python manage.py db migrate
- 将映射文件真正的映射到数据库中 python manage.py db upgrade
三、通过指令创建用户
bash
python manage.py create_front_user -t '18828361988' -p '12345678' -u '嘻嘻哈哈'
运行结果:
四、前端视图显示
通过访问 http://127.0.0.1:5000/ 链接即可