异常、JSON 与装饰器
一、异常处理
-
在连接到 MySQL 数据库的过程中,如果不有效的处理异常,则异常信息过于复杂,对于用户不太友好,且暴露敏感信息。所以,程序必须有效的处理和控制异常,按照既定的流程执行:
import pymysql try: conn=pymysql.connect(host='localhost',user='root',password='123456',database='lenarn',charset='utf8') print("连接到数据库成功") sql = "select username,password,role from user where userid<6" sursor.execute(sql) print("连接到数据库成功") except: print("连接到数据库失败") -
更完整的异常处理:
# try...except...finally... import pymysql try: conn=pymysql.connect(host='localhost',user='root',password='123456',database='lenarn',charset='utf8') print("连接到数据库成功") sql = "select username,password,role from user where userid<6" sursor.execute(sql) except: print("连接到数据库失败") finally: conn.close() # 无论成功与否,本代码都会执行,数据库连接关闭 -
针对不同的异常,显示不同的错误提示
import pymysql try: conn=pymysql.connect(host='localhost',user='root',password='123456',database='lenarn',charset='utf8') print("连接到数据库成功") sql = "select username,password,role from user where userid<6" sursor.execute(sql) except pymysql.err.OperationalError as e: print(e) except pymysql.err.ProgrammingError as e: print(e) except Exception as e: print("代码存在其他异常") finally: conn.close() -
主动抛出异常,让程序停止
raise Exception("数据库处理出错")
二、JSON 处理
-
将 python 对象序列化成字符串
import json from exercise.commen import query_mysql result = query_mysql("select username,password,role from user where userid<6") jsonstr = json.dumps(result) print(jsonstr) -
将 JSON 字符串反序列化为 python 对象
source = '[{"username":"user1","password":"12345","phone":"13344445555"}]' jsonobj = json.loads(source) print(jsonobj[1]['username']) -
json 库中还有 json.load 和 json.dump,用于操作文件
with open('./1.txt',mode='w') as f: json.dump(result,f) # 将result存到文件
三、装饰器
-
在函数或方法或类前面,使用 @符号进行声明的特殊操作,可以改变程序的执行顺序
# 统计某段代码的执行时间 import time def test() start = time.time() # 获取当前时间 result = 99999 for i in range(100) result = result + i -result * 15 pritn(result) end = time.time() print(end - start) # 共用时 # 定义装饰器,用于统计函数的运行时间 # 函数里面继续定义了一个函数,称之为内部函数(闭包) # 装饰器自带一个参数,func,用于获取被装饰函数的地址 # 内部函数运行结束后,必须要返回其函数名(地址) def start(func): def inner(): start = time.time() func() # 被调用的装饰函数 end = time.time() print(end - start) return inner @start def test2(): result = 99999 for i in range(100) result = result + i -result * 15 print(result) test2()