今天要上交代码进行代码审查, 对里面的敏感内容进行脱敏, 思路就是将代码中的字符串全部用星号代替, 并删除所有非代码文件
以下就是执行上述过程的脚本
import os
import re
# 获取当前目录下位于不同层级的所有.py文件
all_files = []
for root, dirs, files in os.walk('./'):
for file in files:
if file.endswith('.py'):
all_files.append(f'{root}/{file}')
# 加星号
for file in all_files:
with open(file) as f:
contents = f.readlines()
with open(file, 'w') as f:
for content in contents:
# 移除"""与'''干扰
content = re.sub('("([^"]*)")|\'([^\']*)\'', lambda m: f"'{'*'*(len(m.group())-2)}'" if m.group() not in ['""', "''"] else m.group(), content)
f.write(content)
# 删除所有.ipynb、.gitignore、.dockerignore、.md、.xlsx、.log文件
for root, dirs, files in os.walk('./'):
for file in files:
for ending in ['.ipynb', '.gitignore', '.dockerignore', '.md', '.xlsx', '.log']:
if file.endswith(ending):
# 删除文件
os.remove(f'{root}/{file}')
效果:
# 发送http请求
@classmethod
def send_request(cls, method: str, request_url: str, headers: dict, data: Union[dict, bytes]) -> requests.models.Response:
"""发送请求
Args:
method (str): 请求方式
request_url (str): 请求地址
headers (dict): 请求头
data (Union[dict, bytes]): 请求体
Raises:
Exception: 请求错误
exception: 通用异常
Returns:
requests.models.Response: 请求结果对象
"""
count = 0
while True:
if count < 2:
try:
if method == '***':
res = cls.s.get(request_url, params=data, headers=headers, verify=False, timeout=60)
elif method == '****':
if '**************' in headers.keys():
headers['**************'] = str(len(str(data)))
res = cls.s.post(request_url, json=data, headers=headers, verify=False, timeout=60)
elif method == '*************':
if '**************' in headers.keys():
headers['**************'] = str(len(data))
res = cls.s.post(request_url, data=data, headers=headers, verify=False, timeout=60)
time.sleep(3)
if res.status_code >= 400:
raise Exception('*****', res)
else:
return res
except Exception as e:
count += 1
print('*****')
time.sleep(5)
exception = e
else:
raise exception