pymysql 连接 MySQL 实现简单登录!

213 阅读2分钟

根据前两篇文章,已经可以利用 Flask 实现简单的路由访问,接下来结合 mysql 实现简单的登录。

新建一个名为 python_test 的数据库, 添加 user 表

CREATE DATABASE /*!32312 IF NOT EXISTS*/`python_test` /*!40100 DEFAULT CHARACTER SET utf8 */ /*!80016 DEFAULT ENCRYPTION='N' */;

USE `python_test`;

/*Table structure for table `user` */

DROP TABLE IF EXISTS `user`;

CREATE TABLE `user` (
  `id` int NOT NULL AUTO_INCREMENT,
  `name` varchar(10) DEFAULT NULL,
  `password` varchar(10) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8;

/*Data for the table `user` */

insert  into `user`(`id`,`name`,`password`) values (1,'admin','123456'),(5,'oppo','456789'),(6,'vivo','987654'),(7,'huawei','');

12345678910111213141516171819

文件结构如下所示

![](https://p6-tt-ipv6.byteimg.com/large/pgc-image/df8092e69aa4465e88e236f3958026fd)

新建登陆页面 index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>登录</title>
</head>
<body>
<form action="/login" method="post">
    <div style="position: absolute;margin-left: 750px;margin-top: 350px">
        <p>姓名:<input type="text" name="name"></p>
        <p>密码:<input type="password" name="password"></p>
        <p><input type="submit" value="登录" style="position: absolute;margin-left: 90px"></p>
    </div>
</form>
</body>
</html>

新建登陆成功页面 success.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>首页</title>
</head>
<body>
<p>欢迎你{{name}}
    <button onclick="back()">退出登录</button>
</p>
</body>
</html>
<script>
    function back() {
        history.back();
    }
</script>

新建 user_model.py 实体类和数据库 user 表对应

class User:
    i_d = 0
    name = ''
    password = ''

    def __init__(self, i_d, name, password):
        self.id = i_d
        self.name = name
        self.password = password

新建 user_mysql.py 连接查询数据库

import pymysql

def get_by_name(name):
    conn = pymysql.connect(host='127.0.0.1', user='root', password='123456', database='python_test', charset='utf8')
    cursor = conn.cursor()
    sql = "select * from user where name='%s'" % name
    # sql = "select * from user"
    cursor.execute(sql)
    results = format_data(cursor.description, cursor.fetchall())
    cursor.close()
    conn.close()
    return results

# 数据格式化 fields 字段名,result 结果集
def format_data(fields, result):
    # 列字段数组 格式['id', 'name', 'password']
    field = []
    for i in fields:
        field.append(i[0])
    # 返回的数组集合 格式[{'id': 1, 'name': 'admin', 'password': '123456'}]
    results = []
    for res in result:
        line_data = {}
        for index in range(0, len(field)):
            line_data[field[index]] = res[index]
        results.append(line_data)
    return results

新建 user_dao 处理登录业务逻辑

import user_mysql, user_model

def login_dao(name, password):
    if len(user_mysql.get_by_name(name)) > 0:
        res = user_mysql.get_by_name(name)[0]
        user = user_model.User(i_d=res['id'], name=res['name'], password=res['password'])
        if user.name == name and user.password == password:
            return 1
        else:
            return '密码错误'
    return '用户名不存在'

新建 user_dao 处理登录业务逻辑

import user_mysql, user_model

def login_dao(name, password):
    if len(user_mysql.get_by_name(name)) > 0:
        res = user_mysql.get_by_name(name)[0]
        user = user_model.User(i_d=res['id'], name=res['name'], password=res['password'])
        if user.name == name and user.password == password:
            return 1
        else:
            return '密码错误'
    return '用户名不存在'

以上代码都是一些简单逻辑就不过多解释了,下面运行测试

运行 user_controller.py 文件

![](https://p26-tt.byteimg.com/large/pgc-image/17142eeed6844d00903f960d6b66dc78)

浏览器打开网址: http://127.0.0.1:5000/

![](https://p6-tt-ipv6.byteimg.com/large/pgc-image/94c2d2e6cf7743e5836798e0f5536b9a)

测试登录---->登陆成功

![](https://p1-tt-ipv6.byteimg.com/large/pgc-image/43de83307eb3477588535abfe9e4fd67)

测试登录---->登陆失败

![](https://p26-tt.byteimg.com/large/pgc-image/3c637cf20ace448397985d12fd999acd)
![](https://p9-tt-ipv6.byteimg.com/large/pgc-image/bcbc3c677e3747b7973145941db8b457)

如上,就简单实现了 Flask + pymysql 简单登录。

**简单吧。**简单吧。完整代码点这获取