日志、产生随机数据、生成时间发的封装
日志文件
logging
模块的打印格式可以通过重新来指定,所以修改一下打印的样式和输出的颜色
-
重写
new
方法可以实现单例
,减少反复重新实例化log操作类带来的损耗 -
使用
self.fontColor()
来指定不同级别高级的日志打印颜色
import os import logging from logging.handlers import BaseRotatingHandler, TimedRotatingFileHandler from src.utils.constant import LOG_PATH class LogOperator: __instance = None sh = logging.StreamHandler() def __new__(cls, path=LOG_PATH, level='DEBUG', RotatingFileHandler: BaseRotatingHandler = None): """ :param path: report path :param args: :param kwargs: :return: """ if not cls.__instance: cls.__instance = super().__new__(cls) log = logging.getLogger('wytest') log.setLevel(level) cls.__instance.log = log if path: if not os.path.isdir(path): os.mkdir(path) if RotatingFileHandler and isinstance(RotatingFileHandler, BaseRotatingHandler): fh = RotatingFileHandler else: fh = TimedRotatingFileHandler(os.path.join(path, 'logging.log'), when='d', interval=1, backupCount=7, encoding="utf-8") fh.setLevel(level) cls.__instance.log.addHandler(fh) formatter = logging.Formatter("%(asctime)s | 【%(levelname)s】 | %(name)s | %(message)s") fh.setFormatter(formatter) return cls.__instance def debug(self, message): self.fontColor('\033[0;34m{}\033[0;34m{}\033[0;34m{}\033[0;34m{}') self.log.debug(message) def info(self, message): self.fontColor('\033[0;32m{}\033[0;32m{}\033[0;32m{}\033[0;32m{}') self.log.info(message) def warning(self, message): self.fontColor('\033[0;33m{}\033[0;43m{}\033[0;33m{}\033[0;33m{}') self.log.warning(message) def error(self, message): self.fontColor('\033[0;31m{}\033[0;41m{}\033[0;31m{}\033[0;31m{}') self.log.error(message) def exception(self, message): self.fontColor('\033[0;31m{}\033[0;41m{}\033[0;31m{}\033[0;31m{}') self.log.exception(message) def critical(self, message): self.fontColor('\033[0;35m{}\033[0;45m{}\033[0;35m{}\033[0;35m{}') self.log.critical(message) def fontColor(self, color): # 不同的日志输出不同的颜色 formatter = logging.Formatter(color.format("%(asctime)s| ", "【%(levelname)s】", "| %(name)s ", " | %(message)s")) self.sh.setFormatter(formatter) self.log.addHandler(self.sh) logger = LogOperator() if __name__ == '__main__': logger.debug('debug') logger.info('info') logger.warning('warning') logger.error('error') logger.critical('CRITICAL')
使用的时候直接使用实例化好了的logger
即可,from src.utils.logoperator import logger
时间操作
在代码中经常需要进行时间的获取、计算,将常用的方法封装一下
timeoperator.py
-
获取当前时间戳
-
获取指定格式当前时间
-
获取当前时间n天后的时间(n可为+-)
-
获取岁数
-
获取指定月份的第一天和最后一天
-
获取随机的一天
import random import time import datetime import calendar class TimeOperator: @property def now(self): """ 返回当前时间戳 :return: """ return time.time() @property def now1(self): """ 以 年-月-日 时:分:秒 格式返回当前时间 :return: """ return time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) @property def now2(self): """ 以 年-月-日 格式返回当前时间 :return: """ return time.strftime("%Y-%m-%d", time.localtime()) @property def now3(self): """ 以 年月日时分秒 格式返回当前时间 :return: """ return time.strftime("%Y%m%d%H%M%S", time.localtime()) @property def now_month(self): """ 以 年-月 格式返回当前时间 :return: """ return time.strftime("%Y-%m", time.localtime()) def other_month(self, add_num=0): """ 当前月份的n个月后的 年-月 """ y_m = self.now_month y, m = [int(i) for i in y_m.split("-")] m += add_num if m > 12: m -= 12 y += 1 return f'{y}-{m:02d}' def other_day(self, day): """ 以 年-月-日 时:分:秒 格式返回当前时间+偏移时间 :return: """ return str(datetime.datetime.today() + datetime.timedelta(days=day)).split(".")[0] def get_age(self, birthday): """ :param birthday: 年-月-日 :return: """ y, m, d = [int(i) for i in birthday.split('-')] birthday = datetime.date(y, m, d) today = datetime.date.today() return today.year - birthday.year - ((today.month, today.day) < (birthday.month, birthday.day)) def get_year_month(self, year=0, month=0): now = datetime.datetime.now() if year == 0: year = now.year if month == 0: month = now.month return year, month def get_month_day(self, year=0, month=0): """ 获取指定月份第一天和最后一天 """ year, month = self.get_year_month(year, month) month_first_day, month_last_day = calendar.monthrange(year, month) return month_first_day, month_last_day def get_random_day(self, year=0, month=0): """ 获取指定年月的随机的一天 """ year, month = self.get_year_month(year, month) month_first_day, month_last_day = self.get_month_day(year, month) day = random.randint(month_first_day, month_last_day) return f'{year}-{month}-{day:02d}' def get_random_time(self): """ 获取随机 时:分:秒 """ h = random.randint(0, 23) m = random.randint(0, 59) s = random.randint(0, 59) return f'{h:02d}:{m:02d}:{s:02d}' def get_other_m_d(self, n=0, t=None): """ 获取n个月后的年月日范围 """ if t: y, m = t.split("-") else: y, m, _ = self.now2.split("-") y = int(y) m = int(m) + n d1, d2 = self.get_month_day(int(y), m) return f'{y:04d}-{m:02d}-{1:02d}', f'{y:04d}-{m:02d}-{d2:02d}' timeoperator = TimeOperator()
随机值和通用的方法
Faker
库提供了很多测试随机值的生成方法,将他包装一下放到
tools.py
import base64 import urllib.parse from faker import Faker fk = Faker(locale='zh_CN') def random_mobile(): """随机生成手机号""" return fk.phone_number() def random_msisdn(): return fk.msisdn() def random_name(): """随机生成中文名字""" return fk.name() def random_ssn(): """随机生成一个身份证号""" return fk.ssn() def random_addr(): """随机生成一个地址""" return fk.address() def random_city(): """随机生成一个城市名""" return fk.city() def random_company(): """随机生成一个公司名""" return fk.company() def random_postcode(): """随机生成一个邮编""" return fk.postcode() def random_email(): """随机生成一个邮箱号""" return fk.email() def random_date(): """随机生成一个日期""" return fk.date() def radom_date_time(): """随机生成一个时间""" return fk.date_time() def random_ipv4(): """随机生成一个ipv4的地址""" return fk.ipv4() def random_job(): """随机生成一个职业""" return fk.job() def base64_encode(data: str): """base64编码""" return base64.b64encode(data.encode('utf-8')).decode('utf-8') def md5_encrypt(data: str): """md5加密""" from hashlib import md5 new_md5 = md5() new_md5.update(data.encode('utf-8')) return new_md5.hexdigest() def rsa_encrypt(msg, server_pub): """ rsa加密 :param msg: 待加密文本 :param server_pub: 密钥 :return: """ import rsa msg = msg.encode('utf-8') pub_key = server_pub.encode("utf-8") public_key_obj = rsa.PublicKey.load_pkcs1_openssl_pem(pub_key) cryto_msg = rsa.encrypt(msg, public_key_obj) # 生成加密文本 cipher_base64 = base64.b64encode(cryto_msg) # 将加密文本转化为 base64 编码 return cipher_base64.decode() def get_url(url, type=True): """ url转码 type=True: %E6%88%91%E8%A6%81%E5%8F%8D%E9%A6%88 =》我要反馈 type=False: 我要反馈 =》%E6%88%91%E8%A6%81%E5%8F%8D%E9%A6%88 """ if type: return urllib.parse.unquote(url) else: return urllib.parse.quote(url)
https://blog.csdn.net/jiangjunsss/article/details/123405019--转载自
用刷抖音刷剧的时间做点对自己有用的事情!