主页 > 编程 > python >

Pymysql 封装数据库类 flask登录模块代码

2019-07-05 23:46 阅读:189 来源:智宇SEO自媒体

pymysql数据库操作类

/db.py

import pymysql
import logging
import sys

# 加入日志
# 获取logger实例
logger = logging.getLogger("baseSpider")
# 指定输出格式
formatter = logging.Formatter('%(asctime)s
              %(levelname)-8s:%(message)s')
# 文件日志
file_handler = logging.FileHandler("baseSpider.log")
file_handler.setFormatter(formatter)
# 控制台日志
console_handler = logging.StreamHandler(sys.stdout)
console_handler.setFormatter(formatter)

# 为logge添加具体的日志处理器
logger.addHandler(file_handler)
logger.addHandler(console_handler)

logger.setLevel(logging.INFO)


class DBHelper:
    # 构造函数
    def __init__(self, host='127.0.0.1', user='root',
                 pwd='root', db='stumakr'):
        self.host = host
        self.user = user
        self.pwd = pwd
        self.db = db
        self.conn = None
        self.cur = None

    # 连接数据库
    def connectDatabase(self):
        try:
            self.conn = pymysql.connect(self.host, self.user,
                                        self.pwd, self.db, charset='utf8')
        except:
            logger.error("connectDatabase failed")
            return False
        self.cur = self.conn.cursor()
        return True

    # 关闭数据库
    def close(self):
        # 如果数据打开,则关闭;否则没有操作
        if self.conn and self.cur:
            self.cur.close()
            self.conn.close()
        return True

    # 执行数据库的sq语句,主要用来做插入操作
    def execute(self, sql, params=None):
        # 连接数据库
        self.connectDatabase()
        try:
            if self.conn and self.cur:
                # 正常逻辑,执行sql,提交操作
                self.cur.execute(sql, params)
                self.conn.commit()
        except:
            logger.error("execute failed: " + sql)
            logger.error("params: " + params)
            self.close()
            return False
        return True

    # 用来查询表数据
    def fetchall(self, sql, params=None):
        self.execute(sql, params)
        return self.cur.fetchall()

1.  表单验证

/forms.py

from wtforms import Form,StringField
from wtforms.validators import InputRequired

class LoginForm(Form):
    name = StringField(validators=[InputRequired(message='请输入账号')])
    pwd  = StringField(validators=[InputRequired(message='请输入密码')])

2.登录模型类

/models.py

class Admin:
    def __init__(self):
        self.mydb = DBHelper()

    def login_check(self, sqlstr):
        try:
            check = self.mydb.fetchall(sqlstr)
            if len(check) == 0:
                # print("账号密码错误")
                return False
            else:
                # print("账号密码正确")
                # print(check)
                return check
        except Exception as e:
            print(e)

3.视图操作

/views.py
class LoginView(views.MethodView):    #定义类视图
    def get(self,message=None):
        return render_template('cms/login.html',message=message)
    def post(self):
        try:
            form = LoginForm(request.form)
            if form.validate():
                name = form.name.data
                pwd = form.pwd.data
                sqlstr = "select * from mk_user where usernameorid='{}' and pwd='{}'".format(name, pwd)
                admin = Admin()
                adminData = admin.login_check(sqlstr)
                if (adminData):
                    session['userid'] = adminData[0][0]
                    session['username'] = adminData[0][1]
                    return redirect(url_for('cms.index'))
                else:
                    return self.get(message='用户名或者密码错误')
            else:
                #print(form.errors)
                message = form.errors.popitem()[1][0]
                return self.get(message=message)
        except Exception as e:
            print(e)

bp.add_url_rule('/login/',view_func=LoginView.as_view('login'))


99%人还阅读了: