基於flask的網頁聊天室(二)

基於flask的網頁聊天室(二)

前言

接上一次的內容繼續完善,今天完成的內容不是不少,只是簡單的用戶註冊登陸,內容具體以下html

具體內容

此次要加入與數據哭交互的操做,因此首先要創建相關表結構,這裏使用flask-sqlalchemy來輔助建立vue

首先修改以前的init文件爲:html5

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是建立的數據庫表結構,也要引入內存當中。python

接下來看一下配置文件settings,只是一個很簡單的配置:mysql

class DebugConfig():
    DEBUG = True
    SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://root:******@127.0.0.1:3306/webChatroom'
    SECRET_KEY = 'webchatroom'

主要是在這裏先把數據庫url配置好web

而後是表結構models目前只有user表sql

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()

這樣就能夠經過執行django

  • python app.py db initflask

  • 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的頁面,消息表等。。

相關文章
相關標籤/搜索