1、你是否经常需要统计一个函数的运行时间,姿势可以这样
import time # 统计程序运行时间装饰器 def timer(func): def wrapper(*args, **kw): start_time = time.time() # 这是函数真正执行的地方 func(*args, **kw) end_time = time.time() t = end_time - start_time print("花费时间:{}秒".format(t)) return t return wrapper
2、你是否经常需要查询数据库中某个表的的字段是否状态等于某个值,然后才能走后续流程,比如还款订单状态,一般需要订单状态校验通过,然后才可以进行后续的还款,因此我们需要去查询数据库,但是运气不一定那么好,正好查一次就是符合预期结果,因此需要多次重试,这样的问题也可以借助装饰器来解决
import pymysql,random from retrying import retry @retry(stop_max_attempt_number=3,wait_fixed = 10000) #引用了装饰器,最大尝试次数为3次,每次间隔时间为10s def query_repayment_order(): # 打开数据库连接,不需要指定数据库,因为需要创建数据库 conn = pymysql.connect('localhost', user="root", passwd="123456",db = "dtest_post_loan") # 获取游标 cursor = conn.cursor() # 创建pythonBD数据库 result=cursor.execute("SELECT * FROM repayment_order where order_uuid='9e958b6315944a5f841d754b2d4a1e41' and order_check_status=1") if result!=1: #order_check_status=1 是订单状态校验通过的意思order_check_status=0 是待校验的意思 raise Exception('your current repayment_order\'s order_check_status !=1 ') cursor.close() # 先关闭游标 conn.close() # 再关闭数据库连接 #a=query_repayment_order() #print(a)
3、你的接口是否经常遇见依赖访问第三方接口,比如银行查询账户流水,但是第三方接口未必是稳定的,
@retry(stop_max_attempt_number=3,wait_fixed = 10000) #引用了装饰器,最大尝试次数为3次,每次间隔时间为10s def query_account_balance(productCode,accountNo): url= "http://guangda.net/fn/api/query" headers={"request-source":"127.0.0.1"} data = {"productCode": productCode, "accountNo": accountNo} p=os.popen("ping guangda.net") x = p.read() print(x.count) p.close() if x.count('timeout'): print("ping不通") else: rp=requests.post(url,data=json.dumps(data),headers=headers) print(rp.text) query_account_balance("guangdaPPD","11005749366303")