# Requests库|UnitTest框架|数据库|日志

Requests库

学习目标

  1. 能够使用 Requests 库发送 get/post/put/delete 请求,获取响应状态码、数据
  2. 能够使用 UnitTest 管理测试用例

requests请求对象构建

介绍

  • Requests库:是 Python编写的,基于urllib 的 HTTP 库,使用方便。
    • 理解:Requests 库是接口自动化测试的工具箱

image-20231211141309886

安装

  • 安装:pip install requests -i https://pypi.douban.com/simple/ , 从豆瓣 pip 镜像下载安装 requests 库
  • 验证:pip show requests , 出现版本号等信息即为成功
    • 或者使用 pip list 查看安装的所有库

入门示例

1
2
3
4
5
6
7
8
9
10
11
12
# 1. 导入requests库
import requests

# 2. 准备测试数据
url = 'http://www.baidu.com/'

# 3. 发送接口请求
response = requests.get(url)

# 4. 查看响应结果
print(response.status_code)
print(response.text)

发送接口请求

  • resp = requests.请求方法(url='URL地址', params={k:v}, headers={k:v},data={k:v}, json={k:v}, cookies='cookie数据'(如:令牌))
  • 说明:
    • 常见的请求方法: get/post/put/delete
    • resp:响应结果
    • url: 请求的url地址
    • params:请求查询参数
    • data:表单参数
    • json:json参数
    • headers:请求头参数
    • cookies:cookie数据 - string类型
1
2
3
4
5
6
7
8
9
# 1. 导入requests库
import requests

# 2. 获取响应结果
resp = requests.post(url='http://ceshi3.dishait.cn/api/goods/search', json={'title': '手机', "page": 1})

# 3. 输出响应结果
print(resp.status_code)
print(resp.text)

get请求的查询参数

image-20231211141504902

get请求的查询参数案例

  • 发送带查询参数的get请求

  • 需求:

    • 访问TPshop搜索商品的接口,传递搜索关键字iPhone,查看响应数据
  • 分析:

post请求参数-data

image-20231211141651831

post请求参数案例

  • 接口URL

http://ceshi13.dishait.cn/admin/login

  • 请求方式

POST

  • Content-Type

application/x-www-form-urlencoded

  • 请求Body参数
参数名 示例值 参数类型 是否必填 参数描述
username admin Text 用户名
password admin Text 密码
1
2
3
4
5
6
7
8
9
# 1. 导入requests库
import requests

# 2. 获取响应结果
resp = requests.post(url='http://ceshi13.dishait.cn/admin/login',headers={'Content-Type':'application/x-www-form-urlencoded'},data={"username":"admin","password":"admin"})

# 3. 输出响应结果
print(resp.status_code)
print(resp.json())

post请求参数-json

image-20231211141843860

post请求参数案例

  • 需求:
    • 请求IHRM项目的登录接口,请求数据为json格式
  • 分析:

发送其他 HTTP 请求

  • 如何使用requests库发送其他 HTTP 请求类型?
    • requests.put(url, **kwargs)
    • requests.delete(url, **kwargs)

思考

  1. 如何使用requests发送GET/POST/PUT/DELETE请求?
  2. 如何使用requests提交表单数据?
  3. 如何使用requests提交JSON数据?

请求头和cookie设置

Cookie简介

  • 简介:工程师 针对 http协议是无连接、无状态特性,设计的 一种技术。 可以在浏览器端 存储用户的信息。
  • 特性:
    • cookie 用于存储 用户临时的不敏感信息。
    • cookie 位于浏览器(客户端)端。默认大小 4k(可以调整)
    • cookie 中的数据,可以随意被访问,没有安全性可言。
    • cookie 中存储的数据类型,受浏览器限制。
  • 在计算机中,认证用户身份的方式有多种!课程中接触 2种:
    • ihrm项目:token认证。
    • tpshop项目:cookie+Session认证。

image-20231228154910512

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import requests

# 发送 获取验证码请求
resp_v = requests.get(url="http://tpshop-test.itheima.net/index.php?
m=Home&c=User&a=verify&r=0.21519623710645064")

# 从 获取验证码 的响应结果,提取 cookie
my_cookie = resp_v.cookies

# 发送 登录请求 url、请求头、请求体。 携带 cookie。 得响应结果
resp = requests.post(url="http://tpshop-test.itheima.net/index.php?
m=Home&c=User&a=do_login&t=0.7094195931397276",
# headers={"Content-Type": "application/x-www-form-urlencoded"},
data={"username": "13012345678", "password": "12345678", "verify_code":
"8888"},
cookies=my_cookie)

# 打印响应结果
print(resp.json())

# 发送 查看我的订单 请求
resp_o = requests.get(url="http://tpshop-test.itheima.net/Home/Order/order_list.html",
cookies=my_cookie)
print(resp_o.text)

设置请求头

image-20231211142118843

案例一

案例二

  • 设置cookie
    •  获取cookies:cookies = response.cookies
    •  requests.get(url, cookies={“c1”: “v1”})
1
2
3
4
5
6
7
8
9
import requests
res_v = requests.get("http://tpshop-test.itheima.net/index.php?m=Home&c=User&a=verify")
cookies_data = res_v.cookies
form_data = {"username": "13012345678","password": "123456","verify_code": "8888"}
res_l = requests.post("http://tpshop-test.itheima.net/index.php?m=Home&c=User&a=do_login",
data=form_data, cookies=cookies_data)
res_o = requests.get("http://tpshop-test.itheima.net/Home/Order/order_list.html",
cookies=cookies_data)
print(res_o.text)

Session简介

  • 简介:也叫 会话。通常出现在网络通信中,从客户端借助访问终端登录上服务器,直到 退出登录 所产生的通信数据,保存在 会话中。

  • 特性:

    • Session 用于存储 用户的信息。

    • Session 位于服务端。大小直接使用服务器存储空间

    • Session 中的数据,不能随意被访问,安全性较高。

    • Session 中存储的数据类型,受服务器影响,几乎能支持所有的数据类型。

Session自动管理Cookie

  • 因为 Cookie 中的 数据,都是 Session 传递的。因此,Session 可以直接 自动管理 cookie

案例

  • 借助session重新实现 上述 TPshop商城登录,并获取 “我的订单” 页面数据。
  • 实现步骤:
    • 创建一个 Session 实例。
    • 使用 Session 实例,调 get方法,发送 获取验证码请求。(不需要获取cookie)
    • 使用 同一个 Session 实例,调用 post方法,发送 登录请求。(不需要携带 cookie)
    • 使用 同一个 Session 实例,调用 get方法,发送 查看我的订单请求。(不需要携带 cookie)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import requests

# 1. 创建一个 Session 实例。
session = requests.Session()

# 2. 使用 Session 实例,调 get方法,发送 获取验证码请求。(不需要获取cookie)
resp_v = session.get(url="http://tpshop-test.itheima.net/index.php?
m=Home&c=User&a=verify&r=0.21519623710645064")

# 3. 使用 同一个 Session 实例,调用 post方法,发送 登录请求。(不需要携带 cookie)
resp = session.post(url="http://tpshop-test.itheima.net/index.php?
m=Home&c=User&a=do_login&t=0.7094195931397276",
data={"username": "13012345678", "password": "12345678", "verify_code":"8888"})
print(resp.json())

# 4. 使用 同一个 Session 实例,调用 get 方法,发送 查看我的订单请求。(不需要携带 cookie)
resp_o = session.get(url="http://tpshop-test.itheima.net/Home/Order/order_list.html")
print(resp_o.text)

Session对象发送请求

  • 创建session对象:session = requests.Session()
  • 说明:
    •  Session对象代表一次用户会话:从客户端浏览器连接服务器开始,到客户端浏览器与服务器断开
    •  会话能让我们在跨请求时候保持某些参数,比如在同一个 session 实例发出的所有请求之间保持 cookie

案例三

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import requests
# 获取验证码
session = requests.Session()
response = session.get("http://tpshoptest.
itheima.net/index.php?m=Home&c=User&a=verify")
print(response.cookies)

# 登录
login_data = {"username": "13012345678", "password": "123456", "verify_code": "8888"}
response = session.post("http://tpshoptest.
itheima.net/index.php?m=Home&c=User&a=do_login", data=login_data)
print(response.cookies)
print("login response data=", response.json())

# 我的订单
response = session.get("http://tpshop-test.itheima.net/Home/Order/order_list.html")
print(response.text)

思考

  1. 设置请求头的参数是哪个?
  2. 设置cookie的参数是哪个?
  3. session对象作用?
  4. Cookie 和 Session 区别
    1. 数据存储位置:
      • cookie存储在浏览器;session存储在服务器。
    2. 安全性:
    • cookie中的数据可以随意获取,没有安全性可言。Session的数据多为加密存储,安全较高!
    1. 数据类型:
    • cookie支持的数据类型受浏览器限制,较少;Session直接使用服务器存储,支持所有数据类型
    1. 大小:
    • cookie大小默认 4k; Session 大小约为服务器存储空间大小

response响应对象

获取响应内容方法

  • 获取 URL:resp.url
  • 获取 响应状态码:resp.status_code
  • 获取 Cookie:resp.cookies
  • 获取 响应头:resp.headers
  • 获取 响应体:
    • 文本格式:resp.text
    • json格式:resp.json()

image-20231211142628860

案例一

  • 需求:
    • 访问百度接口http://www.baidu.com,获取以下响应数据
      • 获取响应状态码
      • 获取请求URL
      • 获取响应字符编码
      • 获取响应头数据
      • 获取文本形式的响应内容
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import requests
resp = requests.get(url="http://www.baidu.com")

# - 获取 URL:resp.url
print("url =", resp.url)

# - 获取 响应状态码:resp.status_code
print("status_code =", resp.status_code)

# - 获取 Cookie:resp.cookies
print("cookies =", resp.cookies)

# - 获取 响应头:resp.headers
print("headers =", resp.headers)

# - 获取 响应体:
# - 文本格式:resp.text
print("body_text =", resp.text)

# - json格式:resp.json() 当显示 JSONDecodeError 错误时,说明 resp 不能转换为 json格式数据。
print("body_json =", resp.json())

获取响应内容-JSON

  • json_data = response.json()
    • 提示:如果 JSON 解码失败,response.json() 会抛出异常

案例

思考

  1. Response对象常见方法有哪些?
  2. response.json()获取的是什么格式的数据?

UnitTest框架

学习目标

  1. 理解使用UnitTest的目的
  2. 能够使用UnitTest管理测试用例

Unittest框架

  • UnitTest 是开发人员用来实现 “单元测试” 的框架。测试工程师,可以在自动化 “测试执行” 时使用。
  • 使用 UnitTest 的好处:
    1. 方便管理、维护测试用例。
    2. 提供丰富的断言方法。
    3. 生成测试报告。(需要插件 HTMLTestReport)

image-20231211143615809

TestCase

1
2
3
4
5
6
7
8
# 1 导包:import unittest
# 2 定义测试类从 TestCase 类继承
class TestXXX(unittest.TestCase):
pass
# 3 测试方法定义必须以 test 开头。 建议添加 编号!
class TestXXX(unittest.TestCase):
def test01_xxx(self):
pass

Fixture

1
2
1、方法级别的 setUp(self) tearDown(self) 每个普通方法执行 之前/之后 自动运行。
2、类级别的 setUpClass(cls) tearDownClass(cls) 在类内所有方法直 之前/之后 运行一次。

TestSuite

1
2
3
4
5
6
1、实例化测试集对象 suite = unittest.TestSuite()
2、添加指定类的全部测试方法。
suite.addTest(unittest.makeSuite(类名))
Testsuite 通过搜索创建测试集
suite = unittest.TestLoader().discover(搜索目录, 搜索文件名)
suite = unittest.TestLoader().discover("./", "test*.py")

TestRunner

1
2
runner = HTMLTestReport("./report1.html", description="描述信息", title="报告标题")
runner.run(suite)

示例_测试类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
"""
unittest 测试框架代码所处文件要求: 遵守 标识符命名规范:
1. 只能使用 字母、数字、下划线
2. 数字不能开头
3. 避免使用 关键字、已知函数名
类:首字母必须大写。建议以 Test 开头
方法:必须 test 开头,建议 编号
"""
import unittest

# 待测试方法
def add(x, y):
return x + y

# 封装 测试类,从 unittest.TestCase 类继承
class TestAdd(unittest.TestCase):
def setUp(self) -> None:
print("-----setUp------")

def tearDown(self) -> None:
print("-----tearDown------")

@classmethod
def setUpClass(cls) -> None:
print("====setUpClass=====")

@classmethod
def tearDownClass(cls) -> None:
print("====tearDownClass=====")

# 自定义的测试方法
def test01_add(self):
print("测试方法1")
ret = add(10, 20)
# 断言响应结果
self.assertEqual(30, ret)

def test02_add(self):
print("测试方法2")
ret = add(100, 200)
# 断言
self.assertEqual(300, ret)

示例:生成测试报告

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import unittest
from htmltestreport import HTMLTestReport

# 创建 suite 实例
from py10_unittest_demo import TestAdd
suite = unittest.TestSuite()

# 指定测试类,添加 测试方法
suite.addTest(unittest.makeSuite(TestAdd))

# 创建 HTMLTestReport 实例
runner = HTMLTestReport("测试报告.html")

# 调用 run() 传入 suite
runner.run(suite)

案例一

  • 练习 : UnitTest框架管理ihrm登录接口脚本
  • 实现要求:
    1. 按照功能模块组织测试类,一条测试用例对应一个测试方法
    2. 添加断言:响应状态码/success/code/message
    3. 封装测试套件批量执行用例
    4. 生成测试报告

image-20231211143704907

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class TestLogin(unittest.TestCase):
def test01_login_success(self):

# 测试数据
mobile = "13800000002"
password = "123456"

# 发送请求
url = "http://www.test.com//login"
data = {"mobile": mobile, "password": password}
response = requests.post(url, json=data)
json_data = response.json()

# 断言
self.assertEqual(200, response.status_code)
self.assertEqual(True, json_data.get("success"))
self.assertEqual(10000, json_data.get("code"))
self.assertIn("操作成功", json_data.get("message"))

案例二

image-20231211143812846

思考

  1. 使用UnitTest框架的目的?
  2. TestFixture、TestCase、TestSuite、TestRunner使用

数据库操作

学习目标

  1. 知道数据库操作的应用场景
  2. 掌握使用PyMySQL对数据库的增、删、改、查
  3. 数据库工具类封装

数据库操作应用场景

  • 接口自动化测试数据库主要应用场景?
    • 测试数据校验
      • 接口发送请求后明确会对数据库中的某个字段进行修改,但,响应结果中无该字段数据时。
        • 如:ihrm 删除员工接口。 is_delete 字段,没有 在响应结果中出现! 需要 借助数据库 校验!
    • 测试数据构造
      • 测试数据使用一次就失效。
        • 如:ihrm 添加员工接口,使用的手机号!
      • 测试前,无法保证测试数据是否存在。
        • 如:ihrm 查询员工接口,使用的 员工id
  • 接口自动化测试与数据库交互场景有哪些?
  • 数据库操作的应用场景有哪些?

数据库操作实现

学习目标

  1. 掌握操作数据库的基本流程
  2. 掌握使用PyMySQL对数据库的增、删、改、查

安装 PyMySQL

  • PyMySQL:Python3.x 版本中连接 MySQL 服务器的一个库
  • 安装PyMySQL:pip install PyMySQL

操作数据库的基本流程

  • 代码实现步骤:
    • 导包 import pymysql
    1. 创建连接。 conn = pymysql.connect(host,port, user, password, database, charset)
    2. 获取游标。 cursor = conn.cursor()
    • 执行 SQL。 cursor.execute( ”sql语句“)
      • 查询语句(select)
      • 处理结果集(提取数据 fetch*)
      • 增删改语句(insert、update、delete)
      • 成功:提交事务 conn.commit()
      • 失败:回滚事务 conn.rollback()
    • 关闭游标。cursor.close()
    • 关闭连接。conn.close()

image-20231211144427947

  • 测试数据 :
    •  host: 211.103.136.244
    •  port: 7061
    •  user: student
    •  password: iHRM_student_2021
    •  database: test_db

连接数据库

  • 建立连接方法 :

    • conn = pymysql.connect(host=None, user=None, password="",database=None, port=0, charset="")
  • 参数说明:

    • host:数据库所在主机 IP地址 - string
    • port:数据库使用的 端口号 - int
    • user:连接数据库使用的 用户名 - string
    • password:连接数据库使用的 密码 - string
    • database:要连接的那个数据库的名字 - string
    • charset:字符集。常用 utf8 - string
    • conn:连接数据库的对象。

获取游标对象

  • cursor = conn.cursor()

  • 说明:

    •  调用数据库连接对象的cursor()方法获取游标对象

执行SQL语句

  • cursor.execute(sql)

  • 说明:

    •  调用游标对象的execute()方法来执行SQL语句
    •  sql: 要执行的sql语句

释放资源

1
2
3
4
5
# 关闭游标对象
cursor.close()

# 关闭数据库连接
conn.close()
  • 说明:
    •  调用数据库连接对象、游标对象的close()方法来释放资源

案例一

  • 需求 : 查询数据库,获取MySQL服务器 版本信息
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# 1. 导包
import pymysql

# 2. 建立连接
conn = pymysql.connect(host="localhost", port=3306, user="root",password="123456", database="it666", charset="utf8")

# 3. 获取游标
cursor = conn.cursor()

# 4. 执行 sql 语句(查询)
cursor.execute("select version()")

# 5. 获取结果
res = cursor.fetchone()
print("res =", res[0])

# 6. 关闭游标
cursor.close()

# 7. 关闭连接
conn.close()

案例一

  • 需求:
    • 连接到数据库(host:211.103.136.244 port:7061 user:student password:iHRM_student_2021database:test_db)
    • 获取数据库服务器版本信息
  • 分析:
    • 如何获取数据库的连接?
    • 获取数据库服务器版本信息的SQL语句是什么?
      • sql语句:select version()
  • 如何执行SQL语句?
    • cursor.execute(“select version()”)
    • 获取查询结果:cursor.fetchone()
  • 如何释放资源?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# 导包
import pymysql
# 创建数据库连接
conn = pymysql.connect(host="localhost", user="root", password="root", database="books")
# 创建游标对象
cursor = conn.cursor()
# 执行操作:查询数据库版本信息
cursor.execute("select version()")
# 获取查询结果
result = cursor.fetchone()
print("result=", result)
# 关闭游标对象
cursor.close()
# 关闭数据库连接
conn.close()

数据库查询

image-20231211145008342

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# 1. 导包
import pymysql

# 2. 建立连接
conn = pymysql.connect(host="localhost", port=3306, user="root", password="123456", database="it666", charset="utf8")

# 3. 获取游标
cursor = conn.cursor() # 指向 0 号位置。

# 4. 执行 sql 语句(查询)--- t_book
cursor.execute("select * from users;")

# 5. 获取结果 - 提取第一条
res1 = cursor.fetchone()
print("res1 =", res1)
# 修改游标位置:回零
cursor.rownumber = 0
# 获取结果 - 提取前 2 条
res2 = cursor.fetchmany(2)
print("res2 =", res2)
# 修改游标位置:回零
cursor.rownumber = 0
res3 = cursor.fetchall()
print("res3 =", res3)
# 修改游标位置:指向第 2 条记录
cursor.rownumber = 2
res4 = cursor.fetchmany(2)
print("res4 =", res4)

# 6. 关闭游标
cursor.close()

# 7. 关闭连接
conn.close()

异常捕获

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# 1. 导包
import pymysql

# 定义全局变量,初值为 None
conn = None
cursor = None

try:
# 2. 建立连接
conn = pymysql.connect(host="localhost", port=3306, user="root", password="123456", database="it666",
charset="utf8")
# 3. 获取游标
cursor = conn.cursor() # 指向 0 号位置。
# 4. 执行 sql 语句(查询)--- t_book
cursor.execute("select * from users;")
# 5. 获取结果 - 提取第一条
res1 = cursor.fetchone()
print("res1 =", res1)
# 修改游标位置:回零
cursor.rownumber = 0
# 5. 获取结果 - 提取前 2 条
res2 = cursor.fetchmany(2)
print("res2 =", res2)
# 修改游标位置:回零
cursor.rownumber = 0
res3 = cursor.fetchall()
print("res3 =", res3)
# 修改游标位置:指向第 2 条记录
cursor.rownumber = 2
res4 = cursor.fetchmany(2)
print("res4 =", res4)
except Exception as err:
print("查询语句执行 出错:", str(err))
finally:
# 6. 关闭游标
cursor.close()
# 7. 关闭连接
conn.close()

execute方法

  • cursor 对象的 execute方法:执行sql并返回结果到客户端

image-20231211145138574

fetch*()方法

image-20231211145239831

案例二

  • 案例 : 查询books表的指定信息
  • 数据库地址:
    • host: 211.103.136.244, port: 7061,
    • user: student, password: iHRM_student_2021, database: test_db
  • 要求:
    • ①:查询t_book表第一条数据
    • ②:获取t_book前两条数据
    • ③:查询t_book表的全部数据
  • 分析:
    • cursor.fetchone()
    • cursor.fetchmany(2)
    • cursor.fetall()

fetch*()方法原理

  • rownumber属性:标识游标的当前位置(默认初始位置从0开始)
  • fetch*()方法是基于游标当前位置逐行向下获取数据

image-20231211145759835

案例三

  • 练习 : 查询books表的指定信息

  • 要求:

    • ①:查询t_book表的全部字段数据
    • ②:获取查询结果集的第一条数据
    • ③:获取查询结果集的第3条和第4条数据
    • ④:获取全部的查询结果集及总记录数
  • 分析:

    • select * from t_book

    • cursor.rownumber= 0 cursor.fetchone()

    • cursor.rownumber= 2 cursor.fetchmany(2)

    • cursor.rownumber= 0 cursor.fetchall()

数据库更新

image-20231211150036647

案例四

  • 练习 : 更新t_book表的指定信息
  • 数据库地址:
    • host: 211.103.136.244, port: 7061,
    • user: student, password: iHRM_student_2021, database: test_db
  • 要求单独实现:
    • ①:新增一条图书数据(id:5 title:西游记 pub_date:1986-01-01 )
    • ②:把图书名称为‘西游记’的阅读量加一
    • ③:删除名称为‘西游记’的图书
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
"""
新增一条图书数据(id:5 title:西游记 pub_date:1986-01-01 )
insert into t_book(id, title, pub_date) values(5, '西游记', '1986-01-01');
1. 导包
2. 创建连接
3. 获取游标
4. 执行 insert 语句
5. 提交/回滚事务
6. 关闭游标
7. 关闭连接
"""
# 1. 导包
import pymysql

# 定义全局变量
conn = None
cursor = None
try:
# 2. 创建连接
conn = pymysql.connect(host="localhost", port=3306, user="root",
password="123456",
database="it666", charset="utf8")
# 3. 获取游标
cursor = conn.cursor()
# 4. 执行 insert 语句
cursor.execute("insert into person(id, name, city,score) values(175, '西游记', '深圳','66');")
# 查看 sql执行,影响多少行
print("影响的行数:", conn.affected_rows())
# 5. 提交事务
conn.commit()
except Exception as err:
print("插入数据错误:", str(err))
# 回滚事务
conn.rollback()
finally:
# 6. 关闭游标
cursor.close()
# 7. 关闭连接
conn.close()
1
2
# 修改数据

1
2
# 删除数据

数据库工具类封装

学习目标

  • 掌握数据库工具类封装

封装的目的

  • 将 常用的数据库操作,封装到 一个方法。 后续再操作数据库时,通过调用该方法来实现。
  • 提高代码的 复用性!

数据库工具类封装

image-20231211150253753

总结

  1. 操作数据库的应用场景有哪些?
  2. 能否使用PyMySQL对数据库的增、删、改、查?
  3. 数据库工具类封装

日志收集

学习目标

  • 掌握如何使用logging实现日志收集

认识日志收集

学习目标

  •  理解在项目中为什么要收集日志
  •  知道如何区分日志信息的重要级别

什么是日志

  • 日志就是用于记录系统运行时的信息,对一个事件的记录;也称为Log
  • 有哪些信息需要记录?
    • 脚本运行过程中某个重要变量的值
    • 方法的输入参数和返回结果
    • 异常信息

什么要收集日志

image-20231211150617828

日志级别

  • 日志级别 : 是指日志信息的优先级、重要性或者严重程度

image-20231211150822827

  • 提示 :
    •  当为程序指定一个日志级别后,程序会记录所有日志级别大于或等于指定日志级别的日志信息,而不是仅仅记录指定级别的日志信息;
    •  一般建议只使用DEBUG、INFO、WARNING、ERROR这四个级别

日志收集

image-20231211150926589

思考

  1. 收集日志有什么作用?
  2. 常见的日志级别有哪些?

Logging日志模块用法

学习目标

  • 能够把日志输出到控制台和日志文件中

收集日志达成的效果

  •  可以把日志输出到不同位置
    •  控制台
    •  日志文件(防止日志文件过大,每日生成一个日志文件)
  •  记录更加详细的日志信息
    •  打印日志的时间
    •  日志的级别
    •  打印日志的位置
    •  日志内容
  •  可以打印不同级别的日志
    •  INFO
    •  ERROR

日志收集的实现

image-20231211151141059

日志器介绍

image-20231211151245927

Handler处理器介绍

image-20231211151331105

Formatter格式化器介绍

image-20231211151412958

image-20231211151439679

打印日志

  • 调用 logging 中的不同方法可以打印不同级别的日志

image-20231211151515344

  • 注意 : 打印日志使用的是小写的字母

思考

  1. 如何把日志输出到控制台?
  2. 如何把日志输出到日志文件?
  3. 如何设置日志的格式?
  4. 如何打印不同级别的日志?

总结

  1. 为什么要收集日志?
  2. 如何使用Logging日志模块实现日志的收集?