Skip to content

Commit

Permalink
fix black (#2493)
Browse files Browse the repository at this point in the history
  • Loading branch information
LeoQuote authored Jan 29, 2024
1 parent 7e2d5e7 commit 8bec5f4
Show file tree
Hide file tree
Showing 40 changed files with 352 additions and 138 deletions.
6 changes: 5 additions & 1 deletion common/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,11 @@ def authenticate(self):
init_user(authenticated_user)
return {"status": 0, "msg": "ok", "data": authenticated_user}
else:
return {"status": 1, "msg": "用户名或密码错误,请重新输入!", "data": ""}
return {
"status": 1,
"msg": "用户名或密码错误,请重新输入!",
"data": "",
}
except:
logger.error("验证用户密码时报错")
logger.error(traceback.format_exc())
Expand Down
5 changes: 4 additions & 1 deletion common/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -539,7 +539,10 @@ def test_init_user(self):
class PermissionTest(TestCase):
def setUp(self) -> None:
self.user = User.objects.create(
username="test_user", display="中文显示", is_active=True, email="XXX@xxx.com"
username="test_user",
display="中文显示",
is_active=True,
email="XXX@xxx.com",
)
self.client.force_login(self.user)

Expand Down
6 changes: 3 additions & 3 deletions common/twofa/sms.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,9 +45,9 @@ def get_captcha(self, **kwargs):
result = {"status": 1, "msg": "系统未配置短信服务商!"}
else:
result["status"] = 1
result[
"msg"
] = f"获取验证码太频繁,请于{captcha['update_time'] - int(time.time()) + 60}秒后再试"
result["msg"] = (
f"获取验证码太频繁,请于{captcha['update_time'] - int(time.time()) + 60}秒后再试"
)
else:
if self.client:
result = self.client.send_code(**kwargs)
Expand Down
6 changes: 5 additions & 1 deletion common/utils/permission.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,11 @@ def wrapper(request, *args, **kw):
if user.role not in roles and user.is_superuser is False:
is_ajax = request.META.get("HTTP_X_REQUESTED_WITH") == "XMLHttpRequest"
if is_ajax:
result = {"status": 1, "msg": "您无权操作,请联系管理员", "data": []}
result = {
"status": 1,
"msg": "您无权操作,请联系管理员",
"data": [],
}
return HttpResponse(
json.dumps(result), content_type="application/json"
)
Expand Down
28 changes: 21 additions & 7 deletions common/utils/sendmsg.py
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,9 @@ def send_email(self, subject, body, to, **kwargs):
self.MAIL_REVIEW_FROM_ADDR, to + list_cc, main_msg.as_string()
)
server.quit()
logger.debug(f"邮件推送成功\n消息标题:{subject}\n通知对象:{to + list_cc}\n消息内容:{body}")
logger.debug(
f"邮件推送成功\n消息标题:{subject}\n通知对象:{to + list_cc}\n消息内容:{body}"
)
return "success"
except Exception:
errmsg = "邮件推送失败\n{}".format(traceback.format_exc())
Expand All @@ -150,7 +152,9 @@ def send_ding(url, content):
if r_json["errcode"] == 0:
logger.debug(f"钉钉Webhook推送成功\n通知对象:{url}\n消息内容:{content}")
else:
logger.error(f"钉钉Webhook推送失败错误码\n请求url:{url}\n请求data:{data}\n请求响应:{r_json}")
logger.error(
f"钉钉Webhook推送失败错误码\n请求url:{url}\n请求data:{data}\n请求响应:{r_json}"
)

def send_ding2user(self, userid_list, content):
"""
Expand All @@ -171,7 +175,9 @@ def send_ding2user(self, userid_list, content):
if r_json["errcode"] == 0:
logger.debug(f"钉钉推送成功\n通知对象:{userid_list}\n消息内容:{content}")
else:
logger.error(f"钉钉推送失败\n请求连接:{send_url}\n请求参数:{data}\n请求响应:{r_json}")
logger.error(
f"钉钉推送失败\n请求连接:{send_url}\n请求参数:{data}\n请求响应:{r_json}"
)

def send_wx2user(self, msg, user_list):
if not user_list:
Expand All @@ -191,7 +197,9 @@ def send_wx2user(self, msg, user_list):
if r_json["errcode"] == 0:
logger.debug(f"企业微信推送成功\n通知对象:{to_user}")
else:
logger.error(f"企业微信推送失败\n请求连接:{send_url}\n请求参数:{data}\n请求响应:{r_json}")
logger.error(
f"企业微信推送失败\n请求连接:{send_url}\n请求参数:{data}\n请求响应:{r_json}"
)

def send_qywx_webhook(self, qywx_webhook, msg):
send_url = qywx_webhook
Expand All @@ -212,7 +220,9 @@ def send_qywx_webhook(self, qywx_webhook, msg):
if r_json["errcode"] == 0:
logger.debug(f"企业微信机器人推送成功\n通知对象:机器人")
else:
logger.error(f"企业微信机器人推送失败\n请求连接:{send_url}\n请求参数:{data}\n请求响应:{r_json}")
logger.error(
f"企业微信机器人推送失败\n请求连接:{send_url}\n请求参数:{data}\n请求响应:{r_json}"
)

@staticmethod
def send_feishu_webhook(url, title, content):
Expand All @@ -239,7 +249,9 @@ def send_feishu_webhook(url, title, content):
):
logger.debug(f"飞书Webhook推送成功\n通知对象:{url}\n消息内容:{content}")
else:
logger.error(f"飞书Webhook推送失败错误码\n请求url:{url}\n请求data:{data}\n请求响应:{r_json}")
logger.error(
f"飞书Webhook推送失败错误码\n请求url:{url}\n请求data:{data}\n请求响应:{r_json}"
)

@staticmethod
def send_feishu_user(title, content, open_id, user_mail):
Expand All @@ -261,4 +273,6 @@ def send_feishu_user(title, content, open_id, user_mail):
if r["code"] == 0:
logger.debug(f"飞书单推推送成功\n通知对象:{url}\n消息内容:{content}")
else:
logger.error(f"飞书单推推送失败错误码\n请求url:{url}\n请求data:{data}\n请求响应:{r}")
logger.error(
f"飞书单推推送失败错误码\n请求url:{url}\n请求data:{data}\n请求响应:{r}"
)
26 changes: 17 additions & 9 deletions sql/archiver.py
Original file line number Diff line number Diff line change
Expand Up @@ -148,7 +148,9 @@ def archive_apply(request):
):
return JsonResponse({"status": 1, "msg": "请填写完整!", "data": {}})
if mode == "dest" and not all([dest_instance_name, dest_db_name, dest_table_name]):
return JsonResponse({"status": 1, "msg": "归档到实例时目标实例信息必选!", "data": {}})
return JsonResponse(
{"status": 1, "msg": "归档到实例时目标实例信息必选!", "data": {}}
)

# 获取源实例信息
try:
Expand All @@ -165,7 +167,9 @@ def archive_apply(request):
instance_name=dest_instance_name
)
except Instance.DoesNotExist:
return JsonResponse({"status": 1, "msg": "你所在组未关联该实例!", "data": {}})
return JsonResponse(
{"status": 1, "msg": "你所在组未关联该实例!", "data": {}}
)
else:
d_ins = None

Expand Down Expand Up @@ -203,7 +207,9 @@ def archive_apply(request):
audit_handler.create_audit()
except AuditException as e:
logger.error(f"新建审批流失败: {str(e)}")
return JsonResponse({"status": 1, "msg": "新建审批流失败, 请联系管理员", "data": {}})
return JsonResponse(
{"status": 1, "msg": "新建审批流失败, 请联系管理员", "data": {}}
)
audit_handler.workflow.status = audit_handler.audit.current_status
if audit_handler.audit.current_status == WorkflowStatus.PASSED:
audit_handler.workflow.state = True
Expand Down Expand Up @@ -376,9 +382,9 @@ def archive(archive_id):
elif mode == "file":
output_directory = os.path.join(settings.BASE_DIR, "downloads/archiver")
os.makedirs(output_directory, exist_ok=True)
args[
"file"
] = f"{output_directory}/{s_ins.instance_name}-{src_db_name}-{src_table_name}.txt"
args["file"] = (
f"{output_directory}/{s_ins.instance_name}-{src_db_name}-{src_table_name}.txt"
)
if no_delete:
args["no-delete"] = True
elif mode == "purge":
Expand Down Expand Up @@ -447,9 +453,11 @@ def archive(archive_id):
shell_cmd = " ".join(cmd_args)
ArchiveLog.objects.create(
archive=archive_info,
cmd=shell_cmd.replace(s_ins.password, "***").replace(d_ins.password, "***")
if mode == "dest"
else shell_cmd.replace(s_ins.password, "***"),
cmd=(
shell_cmd.replace(s_ins.password, "***").replace(d_ins.password, "***")
if mode == "dest"
else shell_cmd.replace(s_ins.password, "***")
),
condition=condition,
mode=mode,
no_delete=no_delete,
Expand Down
10 changes: 6 additions & 4 deletions sql/data_dictionary.py
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,9 @@ def export(request):
elif request.user.is_superuser:
dbs = query_engine.get_all_databases().rows
else:
return JsonResponse({"status": 1, "msg": "仅管理员可以导出整个实例的字典信息!", "data": []})
return JsonResponse(
{"status": 1, "msg": "仅管理员可以导出整个实例的字典信息!", "data": []}
)

# 获取数据,存入目录
path = os.path.join(settings.BASE_DIR, "downloads", "dictionary")
Expand Down Expand Up @@ -149,9 +151,9 @@ def export(request):
return JsonResponse({"status": 1, "msg": "实例名或db名不合法", "data": []})
response = FileResponse(open(fullpath, "rb"))
response["Content-Type"] = "application/octet-stream"
response[
"Content-Disposition"
] = f'attachment;filename="{quote(instance_name)}_{quote(db_name)}.html"'
response["Content-Disposition"] = (
f'attachment;filename="{quote(instance_name)}_{quote(db_name)}.html"'
)
return response

else:
Expand Down
1 change: 1 addition & 0 deletions sql/engines/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
"""engine base库, 包含一个``EngineBase`` class和一个get_engine函数"""

import importlib
from sql.engines.models import ResultSet, ReviewSet
from sql.utils.ssh_tunnel import SSHConnection
Expand Down
4 changes: 3 additions & 1 deletion sql/engines/goinception.py
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,9 @@ def execute_check(self, instance=None, db_name=None, sql=""):
{sql.rstrip(';')};
inception_magic_commit;"""
inception_result = self.query(sql=inception_sql)
check_result.syntax_type = 2 # TODO 工单类型 0、其他 1、DDL,2、DML 仅适用于MySQL,待调整
check_result.syntax_type = (
2 # TODO 工单类型 0、其他 1、DDL,2、DML 仅适用于MySQL,待调整
)
for r in inception_result.rows:
check_result.rows += [ReviewResult(inception_result=r)]
if r[2] == 1: # 警告
Expand Down
14 changes: 10 additions & 4 deletions sql/engines/mongo.py
Original file line number Diff line number Diff line change
Expand Up @@ -363,7 +363,9 @@ def exec_cmd(self, sql, db_name=None, slave_ok=""):
msg = "\n".join(_re_msg)
msg = msg.replace("true\n", "")
except Exception as e:
logger.warning(f"mongo语句执行报错,语句:{sql}{e}错误信息{traceback.format_exc()}")
logger.warning(
f"mongo语句执行报错,语句:{sql}{e}错误信息{traceback.format_exc()}"
)
finally:
if is_load:
fp.close()
Expand Down Expand Up @@ -639,7 +641,8 @@ def execute_check(self, db_name=None, sql=""):
id=line,
errlevel=2,
stagestatus="后台创建索引",
errormessage="创建索引没有加 background:true" + alert,
errormessage="创建索引没有加 background:true"
+ alert,
sql=check_sql,
)
elif not is_in:
Expand All @@ -650,7 +653,8 @@ def execute_check(self, db_name=None, sql=""):
) # 获得表的总条数
if count >= 5000000:
check_result.warning = (
alert + "大于500万条,请在业务低谷期创建索引"
alert
+ "大于500万条,请在业务低谷期创建索引"
)
check_result.warning_count += 1
result = ReviewResult(
Expand Down Expand Up @@ -1119,7 +1123,9 @@ def query(self, db_name=None, sql="", limit_num=0, close_conn=True, **kwargs):
)

except Exception as e:
logger.warning(f"Mongo命令执行报错,语句:{sql}, 错误信息:{traceback.format_exc()}")
logger.warning(
f"Mongo命令执行报错,语句:{sql}, 错误信息:{traceback.format_exc()}"
)
result_set.error = str(e)
finally:
if close_conn:
Expand Down
8 changes: 6 additions & 2 deletions sql/engines/mssql.py
Original file line number Diff line number Diff line change
Expand Up @@ -352,7 +352,9 @@ def query(
result_set.rows = [tuple(x) for x in rows]
result_set.affected_rows = len(result_set.rows)
except Exception as e:
logger.warning(f"MsSQL语句执行报错,语句:{sql},错误信息{traceback.format_exc()}")
logger.warning(
f"MsSQL语句执行报错,语句:{sql},错误信息{traceback.format_exc()}"
)
result_set.error = str(e)
finally:
if close_conn:
Expand Down Expand Up @@ -420,7 +422,9 @@ def execute(self, db_name=None, sql="", close_conn=True, parameters=None):
try:
cursor.execute(statement)
except Exception as e:
logger.warning(f"Mssql命令执行报错,语句:{sql}, 错误信息:{traceback.format_exc()}")
logger.warning(
f"Mssql命令执行报错,语句:{sql}, 错误信息:{traceback.format_exc()}"
)
execute_result.error = str(e)
execute_result.rows.append(
ReviewResult(
Expand Down
16 changes: 12 additions & 4 deletions sql/engines/mysql.py
Original file line number Diff line number Diff line change
Expand Up @@ -524,7 +524,9 @@ def query(
if kwargs.get("binary_as_hex"):
result_set = self.result_set_binary_as_hex(result_set)
except Exception as e:
logger.warning(f"MySQL语句执行报错,语句:{sql},错误信息{traceback.format_exc()}")
logger.warning(
f"MySQL语句执行报错,语句:{sql},错误信息{traceback.format_exc()}"
)
result_set.error = str(e)
finally:
if close_conn:
Expand Down Expand Up @@ -617,14 +619,18 @@ def execute_check(self, db_name=None, sql=""):
instance=self.instance, db_name=db_name, sql=sql
)
except Exception as e:
logger.debug(f"{self.inc_engine.name}检测语句报错:错误信息{traceback.format_exc()}")
logger.debug(
f"{self.inc_engine.name}检测语句报错:错误信息{traceback.format_exc()}"
)
raise RuntimeError(
f"{self.inc_engine.name}检测语句报错,请注意检查系统配置中{self.inc_engine.name}配置,错误信息:\n{e}"
)

# 判断Inception检测结果
if check_result.error:
logger.debug(f"{self.inc_engine.name}检测语句报错:错误信息{check_result.error}")
logger.debug(
f"{self.inc_engine.name}检测语句报错:错误信息{check_result.error}"
)
raise RuntimeError(
f"{self.inc_engine.name}检测语句报错,错误信息:\n{check_result.error}"
)
Expand Down Expand Up @@ -699,7 +705,9 @@ def execute(self, db_name=None, sql="", close_conn=True, parameters=None):
conn.commit()
cursor.close()
except Exception as e:
logger.warning(f"MySQL语句执行报错,语句:{sql},错误信息{traceback.format_exc()}")
logger.warning(
f"MySQL语句执行报错,语句:{sql},错误信息{traceback.format_exc()}"
)
result.error = str(e)
if close_conn:
self.close()
Expand Down
20 changes: 15 additions & 5 deletions sql/engines/oracle.py
Original file line number Diff line number Diff line change
Expand Up @@ -608,7 +608,9 @@ def explain_check(self, db_name=None, sql="", close_conn=False):
else:
result["rows"] = rows[0]
except Exception as e:
logger.warning(f"Oracle 语句执行报错,语句:{sql},错误信息{traceback.format_exc()}")
logger.warning(
f"Oracle 语句执行报错,语句:{sql},错误信息{traceback.format_exc()}"
)
result["msg"] = str(e)
finally:
if close_conn:
Expand Down Expand Up @@ -691,7 +693,9 @@ def query(
result_set.rows = [tuple(x) for x in rows]
result_set.affected_rows = len(result_set.rows)
except Exception as e:
logger.warning(f"Oracle 语句执行报错,语句:{sql},错误信息{traceback.format_exc()}")
logger.warning(
f"Oracle 语句执行报错,语句:{sql},错误信息{traceback.format_exc()}"
)
result_set.error = str(e)
finally:
if close_conn:
Expand Down Expand Up @@ -751,7 +755,9 @@ def execute_check(self, db_name=None, sql="", close_conn=True):
id=line,
errlevel=2,
stagestatus="驳回高危SQL",
errormessage="禁止提交匹配" + critical_ddl_regex + "条件的语句!",
errormessage="禁止提交匹配"
+ critical_ddl_regex
+ "条件的语句!",
sql=sqlitem.statement,
)
# 驳回未带where数据修改语句,如确实需做全部删除或更新,显示的带上where 1=1
Expand Down Expand Up @@ -1421,7 +1427,9 @@ def sqltuningadvisor(self, db_name=None, sql="", close_conn=True, **kwargs):
result_set.rows = [tuple(x) for x in rows]
result_set.affected_rows = len(result_set.rows)
except Exception as e:
logger.warning(f"Oracle 语句执行报错,语句:{sql},错误信息{traceback.format_exc()}")
logger.warning(
f"Oracle 语句执行报错,语句:{sql},错误信息{traceback.format_exc()}"
)
result_set.error = str(e)
finally:
# 结束分析任务
Expand All @@ -1445,7 +1453,9 @@ def execute(self, db_name=None, sql="", close_conn=True, parameters=None):
statement = statement.rstrip(";")
cursor.execute(statement, parameters or [])
except Exception as e:
logger.warning(f"Oracle语句执行报错,语句:{sql},错误信息{traceback.format_exc()}")
logger.warning(
f"Oracle语句执行报错,语句:{sql},错误信息{traceback.format_exc()}"
)
result.error = str(e)
if close_conn:
self.close()
Expand Down
4 changes: 3 additions & 1 deletion sql/engines/pgsql.py
Original file line number Diff line number Diff line change
Expand Up @@ -208,7 +208,9 @@ def query(
result_set.rows = rows
result_set.affected_rows = effect_row
except Exception as e:
logger.warning(f"PgSQL命令执行报错,语句:{sql}, 错误信息:{traceback.format_exc()}")
logger.warning(
f"PgSQL命令执行报错,语句:{sql}, 错误信息:{traceback.format_exc()}"
)
result_set.error = str(e)
finally:
if close_conn:
Expand Down
Loading

1 comment on commit 8bec5f4

@ma0dan

This comment was marked as spam.

Please sign in to comment.