前言
接上一次的内容继续完善,今天完成的内容不是很多,只是简单的用户注册登录,内容具体如下
具体内容
这次要加入与数据哭交互的操作,所以首先要建立相关表结构,这里使用flask-sqlalchemy来辅助创建
首先修改之前的init文件为:
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
from WEB_chatroom.models import *
from web_chatroom.auth import auth
from web_chatroom.chat import chat
def create_app():
app = Flask(__name__)
app.reGISter_blueprint(auth)
app.register_blueprint(chat)
# 添加配置
app.config.from_object('web_chatroom.settings.DebuGConfig')
# 读取配置
db.init_app(app)
return app
这是为了引入SQLAlchemy()对象db,并读取相关的配置,首先要注意的是db = SQLAlchemy()必须要在from web_chatroom.auth import auth之前,因为我在auth.py中使用了db,所以必须要在db创建之后,同时,models是创建的数据库表结构,也要引入内存当中。
接下来看一下配置文件settings,只是一个很简单的配置:
class DebugConfig():
DEBUG = True
SQLALCHEMY_DATABASE_URI = 'Mysql+pymysql://root:******@127.0.0.1:3306/webChatroom'
SECRET_KEY = 'webchatroom'
主要是在这里先把数据库url配置好
然后是表结构models目前只有user表
from web_chatroom import db
class User(db.Model):
id = db.Column(db.Integer,primary_key=True,autoincrement=True)
email = db.Column(db.String(256),unique=True,nullable=False)
username = db.Column(db.String(32),unique=True,nullable=False)
passWord_hash = db.Column(db.String(128))
为了能够像Django一样能够执行数据库迁移的操作,我们使用flask-migrate来维护数据库迁移的版本,于是将之前的app.py修改:
from web_chatroom import create_app,db
from flask_script import Manager
from flask_migrate import Migrate,MigrateCommand
app = create_app()
manager = Manager(app)
migrate = Migrate(app,db)
manager.add_command('db',MigrateCommand)
if __name__ == '__main__':
manager.run()
这样就可以通过执行
-
python app.py db init
-
Python app.py db migrate
-
python app.py db upgrate
完成数据库的迁移
那么相关数据库的建立已完成,接下来可以完善用户的注册登录了
为了辅助表单验证,先建立了utils文件夹,并在其中建立fORMs.py保存了wtforms的相关form类:
from wtforms import Form
from wtforms.fields import simple,HTML5
from wtforms import validators
from wtforms import widgets
class LoginForm(Form):
username = simple.StringField(
validators=[
validators.DataRequired(message='用户名不能为空.')
],
widget=widgets.TextInput(),
)
password = simple.PasswordField(
validators=[
validators.DataRequired(message='密码不能为空.'),
validators.Length(min=8, message='密码长度必须大于%(min)d'),
],
widget=widgets.PasswordInput(),
)
class RegisterForm(Form):
username = simple.StringField(
validators=[
validators.DataRequired(message='用户名不能为空.')
],
widget=widgets.TextInput(),
)
password = simple.PasswordField(
validators=[
validators.DataRequired(message='密码不能为空.'),
validators.Length(min=8, message='密码长度必须大于%(min)d'),
],
widget=widgets.PasswordInput(),
)
email = html5.EmailField(
label='邮箱',
validators=[
validators.DataRequired(message='邮箱不能为空.'),
validators.Email(message='邮箱格式错误')
],
widget=widgets.TextInput(input_type='email'),
)
接下来修改一下登录与注册的html页面,具体代码就不放了,然后在auth.py中的视图函数中处理验证:
from flask import render_template,flash,redirect,url_for
from flask import request
from web_chatroom import models
from web_chatroom import db
import hashlib
from utils import forms
auth = Blueprint('auth', __name__)
@auth.route('/login', methods=['GET', "POST"],endpoint='login')
def login():
if request.method == 'GET':
return render_template('login.html')
elif request.method == 'POST':
form = forms.LoginForm(formdata=request.form)
if form.validate():
password_hash = hashlib.md5(form.data['password'].encode('utf-8')).hexdigest()
count = db.session.query(models.User).filter(db.and_(models.User.username == form.data['username'],
models.User.password_hash == password_hash)).count()
if count:
return redirect(url_for('chat.chat'))
else:
flash('用户名或密码错误')
return redirect(url_for('auth.login'))
pass
else:
for error in form.errors:
flash(form.errors[error][0])
return redirect(url_for('auth.login'))
@auth.route('/register', methods=['GET', "POST"],endpoint='register')
def register():
if request.method == 'GET':
return render_template('register.html')
elif request.method == 'POST':
form = forms.RegisterForm(formdata=request.form)
if form.validate():
count = db.session.query(models.User).filter(db.or_(models.User.username == form.data['username'],
models.User.email == form.data['email'])).count()
if count:
flash('用户名或邮箱已存在')
return redirect(url_for('auth.register'))
else:
password_hash = hashlib.md5(form.data['password'].encode('utf-8')).hexdigest()
db.session.add(models.User(username=form.data['username'],
email=form.data['email'],
password_hash=password_hash))
db.session.commit()
db.session.close()
flash('注册成功')
return redirect(url_for('auth.login'))
else:
for error in form.errors:
flash(form.errors[error][0])
return redirect(url_for('auth.register'))
验证的错误信息通过flash在页面显示,像这样:
注册同理,最后登录成功会跳转到chat.html页面,chat.py中的视图函数就只先写了个显示:
from flask import Blueprint
from flask import render_template,flash,redirect,url_for
from flask import request
chat = Blueprint('chat', __name__)
@chat.route('/chat', methods=['GET', "POST"],endpoint='chat')
def chatroom():
if request.method == 'GET':
return render_template('chatroom.html')
当然页面里目前什么也没有。。。
最后,当前项目的目录结构是这样的:
总结
今天主要完成了简单的数据库交互,明天继续加入cookie,session,以及csrf的保护,以及chat的页面,消息表等。。