引言 当我们需要在Flask中对数据库(mysql)进行数据操作时,可以直接使用PyMysql库。 学习内容

  • 【工具类】PyMysql的封装
    • 安装pymysql
    • pymysql基本操作流程
    • 常用方法
  • 【整合】Flask(蓝图)整合PyMsql

1.【工具类】PyMysql的封装

1.安装PyMysql

  1. # 使用pipenv进行安装
  2. pipenv install pymysql

2.PyMysql基本操作流程

1.Flask整合PyMysql - 图1

3.常用方法

分类 操作项 方法 备注
创建 创建-连接 conn = pymysql.connect(host=data[‘host’],
port=data[‘port’],
user=data[‘user’],
password=data[‘password’],
database=data[‘database’])

创建-游标对象 cursor=conn.cursor(pymysql.cursors.DictCursor)
推荐 使用with方式
with conn.cursor(pymysql.cursors.DictCursor) as cursor
执行 执行SQL cursor.execute(sql)
提交 事务提交 conn.commit()
关闭 关闭-游标 cousor.close()
推荐 使用with方式
with conn.cursor(pymysql.cursors.DictCursor) as cursor
关闭-连接 conn.close()

3.代码实现

将PyMsql操作封装成一个工具类,方便其他业务场景的使用。

  1. # -*- coding: utf-8 -*-
  2. """
  3. ====================================
  4. @File Name :dbUtils.py
  5. @Time : 2022/4/23 9:35
  6. @Program IDE :PyCharm
  7. @Create by Author : 一一Cooling
  8. ====================================
  9. """
  10. import pymysql # 【step1】导入包
  11. import json, time
  12. data = {"host": "42.193.53.xx", "port": x310, "user": 'adminxxxxx',
  13. "password": '123456',
  14. "database": 'xx-mock'}
  15. class DB_Utils:
  16. def __init__(self):
  17. # 【step2】创建数据库连接
  18. self.conn = pymysql.connect(host=data['host'],
  19. port=data['port'],
  20. user=data['user'],
  21. password=data['password'],
  22. database=data['database'])
  23. # 【step3】创建游标对象
  24. self.cursor = self.conn.cursor(pymysql.cursors.DictCursor) # 设置为【字典游标】
  25. # 非select操作(不需进行--事务提交)
  26. def no_select_sql(self, sql):
  27. try:
  28. with self.conn.cursor(pymysql.cursors.DictCursor) as cursor:
  29. res = cursor.execute(sql) # 【step3】 执行sql
  30. self.conn.commit() # 【step4】提交事务
  31. return res
  32. except Exception as e:
  33. return f"【数据库-异常--执行出错!】-->{e}"
  34. # finally:
  35. # # gevent:不需要finally
  36. # time.sleep(2)
  37. # self.cour.close()
  38. # self.conn.close()
  39. # 非select操作(不需进行--事务提交)
  40. def select_sql(self, sql):
  41. try:
  42. with self.conn.cursor(pymysql.cursors.DictCursor) as cursor:
  43. cursor.execute(sql) # 【step3】 执行sql
  44. res = cursor.fetchall() # 【step4】显示所有数据
  45. res_length = len(res)
  46. self.queryResult = {"reslut": res, "total": res_length}
  47. return self.queryResult
  48. except Exception as e:
  49. return f"【数据库-异常--执行出错!】-->{e}"
  50. # finally:
  51. # # gevent:不需要finally
  52. # time.sleep(2)
  53. #
  54. # self.conn.close()
  55. if __name__ == '__main__':
  56. db_utils = DB_Utils()
  57. # sql = "select * from users where username='admin' and password='123456'"
  58. username = "admin"
  59. password = "123456"
  60. sql = f"select * from users where username='{username}' and password='{password}'"
  61. print(db_utils.select_sql(sql))

2.【整合】Flask(蓝图)整合PyMsql

1.蓝图对象实现

  1. # -*- coding: utf-8 -*-
  2. """
  3. ====================================
  4. @File Name :doMysql.py
  5. @Time : 2022/4/13 14:46
  6. @Program IDE :PyCharm
  7. @Create by Author : 一一Cooling
  8. ====================================
  9. """
  10. import json,operator
  11. from utils.optUtils import dictSort
  12. from flask import request,jsonify
  13. from utils.dbUtils import DB_Utils
  14. db_utils = DB_Utils()
  15. from flask import Blueprint as bp
  16. sqlApp = bp("sqlApp", __name__,url_prefix="/sql")
  17. @sqlApp.get("/")
  18. def index():
  19. return 'hello--sql'
  20. @sqlApp.post("/login")
  21. def execSQL():
  22. requestBody = json.loads(request.get_data(as_text=True))
  23. # requestBody = request.get_json()
  24. username = requestBody['username']
  25. password = requestBody['password']
  26. dataMsg = f"{username}+{password}"
  27. print("输入:\t", dataMsg)
  28. # return "123456"
  29. # 业务sql
  30. sql = f"select * from users where username='{username}' and password='{password}'"
  31. # data = sqlProcess(sql)
  32. data = db_utils.select_sql(sql) #sql执行
  33. print("res-data输出:\t", data)
  34. # return 'hello'
  35. if data is None:
  36. print("暂无数据")
  37. msg = {"status": 'False','code':"E5001"}
  38. msg.update(data)
  39. else:
  40. msg = {"status": 'True','code':"S2001","a":"test21"}
  41. msg.update(data)
  42. dictSort(data=msg) #按照ascii升序排序
  43. # print("res输出:\t", msg)
  44. return jsonify(msg)
  45. # return "dataMsg"
  46. # # 关闭数据库连接
  47. #
  48. # if __name__ == '__main__':
  49. # runFlask()

2.蓝图绑定

  1. #!/usr/bin/env pytho
  2. # -*- coding: utf-8 -*-
  3. """
  4. @author:cooling
  5. @file:main.py
  6. @time:2022/04/16
  7. """
  8. import resource.flaskConfig as config1
  9. from flask import Flask
  10. from flask_cors import CORS
  11. from api.login import loginApp # 【step4】【导入】蓝图-模块文件
  12. from api.cookie import cookieApp
  13. from api.session import sessionApp
  14. from api.flaskSQL import sqlApp
  15. from api.webhook import webhookApp
  16. app = Flask(__name__)
  17. CORS(app) # 解决跨域
  18. app.secret_key = "test2022"
  19. app.debug = True
  20. # 处理中文乱码
  21. # app.config['JSON_AS_ASCII'] = False
  22. app.config.from_object(config1)
  23. # 【step5】 注册:蓝图对象
  24. # loginApp.register_blueprint(cookieApp) # 将cookieApp嵌套绑定到loginApp上
  25. app.register_blueprint(loginApp)
  26. app.register_blueprint(cookieApp)
  27. app.register_blueprint(sessionApp)
  28. app.register_blueprint(sqlApp)
  29. app.register_blueprint(webhookApp)
  30. @app.get("/")
  31. def index():
  32. return "index-flask"
  33. # if __name__ == '__main__':
  34. # app.run(port=8806,host="0.0.0.0",debug=True)

image.png

3.接口验证

使用apifox对“/sql/login”进行验证,如下图所示:
image.png