ezKit 1.7.8__py3-none-any.whl → 1.8.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- ezKit/bottle.py +7 -2
- ezKit/bottle_extensions.py +14 -18
- ezKit/database.py +104 -71
- ezKit/http.py +21 -22
- ezKit/mongo.py +3 -3
- ezKit/redis.py +5 -4
- ezKit/sendemail.py +0 -7
- ezKit/utils.py +2 -2
- {ezKit-1.7.8.dist-info → ezKit-1.8.0.dist-info}/METADATA +1 -1
- ezKit-1.8.0.dist-info/RECORD +17 -0
- ezKit/files.py +0 -348
- ezKit/plots.py +0 -155
- ezKit/qywx.py +0 -172
- ezKit/reports.py +0 -274
- ezKit/zabbix.py +0 -737
- ezKit-1.7.8.dist-info/RECORD +0 -22
- {ezKit-1.7.8.dist-info → ezKit-1.8.0.dist-info}/LICENSE +0 -0
- {ezKit-1.7.8.dist-info → ezKit-1.8.0.dist-info}/WHEEL +0 -0
- {ezKit-1.7.8.dist-info → ezKit-1.8.0.dist-info}/top_level.txt +0 -0
ezKit/files.py
DELETED
@@ -1,348 +0,0 @@
|
|
1
|
-
import re
|
2
|
-
from copy import deepcopy
|
3
|
-
from socket import inet_aton
|
4
|
-
|
5
|
-
from loguru import logger
|
6
|
-
|
7
|
-
from . import plots, utils
|
8
|
-
|
9
|
-
|
10
|
-
class Files(object):
|
11
|
-
''' 文件 '''
|
12
|
-
|
13
|
-
''' Markdown 和 HTML 文件 '''
|
14
|
-
_markdown_file, _html_file = None, None
|
15
|
-
|
16
|
-
def __init__(self, markdown_file=None, html_file=None):
|
17
|
-
''' Initiation '''
|
18
|
-
self._markdown_file = markdown_file
|
19
|
-
self._html_file = html_file
|
20
|
-
|
21
|
-
'''
|
22
|
-
def multiple_pieces(
|
23
|
-
self,
|
24
|
-
title='',
|
25
|
-
description='',
|
26
|
-
data=[],
|
27
|
-
image={},
|
28
|
-
number_type=None,
|
29
|
-
number_unit=None,
|
30
|
-
number_handling=None,
|
31
|
-
sort_by_ip=False
|
32
|
-
):
|
33
|
-
|
34
|
-
'''
|
35
|
-
|
36
|
-
def unavailable_hosts(self, hosts=[], **kwargs):
|
37
|
-
''' 异常服务器处理 '''
|
38
|
-
|
39
|
-
logger.success('unavailable hosts | start')
|
40
|
-
|
41
|
-
try:
|
42
|
-
|
43
|
-
# 如果存在异常服务器, 则写入文件
|
44
|
-
if hosts != []:
|
45
|
-
with open(self._markdown_file, 'a') as _file:
|
46
|
-
_file.writelines([
|
47
|
-
'\n',
|
48
|
-
'**异常服务器:**\n',
|
49
|
-
'\n',
|
50
|
-
])
|
51
|
-
for _host in hosts:
|
52
|
-
_file.write('- <span style="color: red">{}</span>\n'.format(_host))
|
53
|
-
|
54
|
-
logger.success('unavailable hosts | end')
|
55
|
-
|
56
|
-
return True
|
57
|
-
|
58
|
-
except Exception as e:
|
59
|
-
logger.exception(e)
|
60
|
-
logger.error('unavailable hosts | end')
|
61
|
-
return False
|
62
|
-
|
63
|
-
def single_piece(
|
64
|
-
self,
|
65
|
-
title='',
|
66
|
-
description='',
|
67
|
-
data=[],
|
68
|
-
image={},
|
69
|
-
number_type=None,
|
70
|
-
number_unit=None,
|
71
|
-
number_handling=None,
|
72
|
-
table_header_title='Host',
|
73
|
-
table_header_data='Data',
|
74
|
-
sort_by_ip=False,
|
75
|
-
**kwargs
|
76
|
-
):
|
77
|
-
''' 单条数据 '''
|
78
|
-
|
79
|
-
match True:
|
80
|
-
case True if type(title) != str or title == '':
|
81
|
-
logger.error('ERROR!! title is not string or none')
|
82
|
-
return None
|
83
|
-
case True if type(description) != str or description == '':
|
84
|
-
logger.error('ERROR!! description is not string or none')
|
85
|
-
return None
|
86
|
-
case True if type(data) != list or data == []:
|
87
|
-
logger.error('ERROR!! data is not list or none')
|
88
|
-
return None
|
89
|
-
case True if type(image) != dict or image == 0:
|
90
|
-
logger.error('ERROR!! image is not dictionary or none')
|
91
|
-
return None
|
92
|
-
|
93
|
-
# 拷贝数据
|
94
|
-
_data = deepcopy(data)
|
95
|
-
|
96
|
-
# 根据 IP 排序
|
97
|
-
if sort_by_ip == True:
|
98
|
-
_ips = utils.list_sort([_host['interfaces'][0]['ip'] for _host in _data], key=inet_aton, deduplication=True)
|
99
|
-
_data = [_host for _ip in _ips for _host in _data if _ip == _host['interfaces'][0]['ip']]
|
100
|
-
|
101
|
-
logger.success('{} | start'.format(title))
|
102
|
-
|
103
|
-
try:
|
104
|
-
|
105
|
-
# 初始化变量
|
106
|
-
_data_idx, _data_result = [], []
|
107
|
-
|
108
|
-
for _host in _data:
|
109
|
-
_value = None
|
110
|
-
if _host.get('history') != None:
|
111
|
-
match True:
|
112
|
-
case True if number_type == 'int':
|
113
|
-
_value = int(_host['history']['value'])
|
114
|
-
case True if number_type == 'float':
|
115
|
-
_value = float(_host['history']['value'])
|
116
|
-
case _:
|
117
|
-
_value = _host['history']['value']
|
118
|
-
_data_idx.append(_host['name'])
|
119
|
-
_data_result.append(number_handling(_value) if callable(number_handling) == True else _value)
|
120
|
-
|
121
|
-
# 判断结果
|
122
|
-
if (len(_data_idx) > 0) and (image != {}):
|
123
|
-
|
124
|
-
with open(self._markdown_file, 'a') as _file:
|
125
|
-
|
126
|
-
_file.writelines([
|
127
|
-
'\n',
|
128
|
-
'## {}\n'.format(title),
|
129
|
-
'\n',
|
130
|
-
'{}\n'.format(description),
|
131
|
-
'\n',
|
132
|
-
'| {} | {} |\n'.format(table_header_title, table_header_data),
|
133
|
-
'| --- | --: |\n'
|
134
|
-
])
|
135
|
-
|
136
|
-
for _i, _v in enumerate(_data_idx):
|
137
|
-
_file.write('| {0} | {1:.2f}{2} |\n'.format(_v, _data_result[_i], number_unit))
|
138
|
-
|
139
|
-
_plot_image = {
|
140
|
-
'title': title,
|
141
|
-
'kind': image['kind'],
|
142
|
-
'size': (20, (len(_data_idx) / 5) * 2),
|
143
|
-
'path': image['path'],
|
144
|
-
'dpi': 300,
|
145
|
-
'width': 0.8
|
146
|
-
}
|
147
|
-
|
148
|
-
_plot_result = plots.bar({image['label']: _data_result}, _data_idx, _plot_image)
|
149
|
-
|
150
|
-
# '<img src="cid:{}">\n'.format(_image['cid'])
|
151
|
-
# '\n'.format(_image['cid'])
|
152
|
-
# 图片显示大小: 仅设置 width, height 自适应
|
153
|
-
if _plot_result == True:
|
154
|
-
_file.writelines([
|
155
|
-
'\n',
|
156
|
-
'<img src="cid:{}" width="1000px">\n'.format(image['cid'])
|
157
|
-
])
|
158
|
-
|
159
|
-
logger.success('{} | end'.format(title))
|
160
|
-
|
161
|
-
return True
|
162
|
-
|
163
|
-
except Exception as e:
|
164
|
-
logger.exception(e)
|
165
|
-
logger.error('{} | end'.format(title))
|
166
|
-
return False
|
167
|
-
|
168
|
-
def multiple_pieces(
|
169
|
-
self,
|
170
|
-
title='',
|
171
|
-
description='',
|
172
|
-
data=[],
|
173
|
-
image={},
|
174
|
-
number_type=None,
|
175
|
-
number_unit=None,
|
176
|
-
number_handling=None,
|
177
|
-
table_header_title='Host',
|
178
|
-
sort_by_ip=False,
|
179
|
-
**kwargs
|
180
|
-
):
|
181
|
-
''' 多条数据 '''
|
182
|
-
|
183
|
-
match True:
|
184
|
-
case True if type(title) != str or title == '':
|
185
|
-
logger.error('ERROR!! title is not string or none')
|
186
|
-
return None
|
187
|
-
case True if type(description) != str or description == '':
|
188
|
-
logger.error('ERROR!! description is not string or none')
|
189
|
-
return None
|
190
|
-
case True if type(data) != list or data == []:
|
191
|
-
logger.error('ERROR!! data is not list or none')
|
192
|
-
return None
|
193
|
-
case True if type(image) != dict or image == 0:
|
194
|
-
logger.error('ERROR!! image is not dictionary or none')
|
195
|
-
return None
|
196
|
-
|
197
|
-
# 拷贝数据
|
198
|
-
_data = deepcopy(data)
|
199
|
-
|
200
|
-
# 根据 IP 排序
|
201
|
-
if sort_by_ip == True:
|
202
|
-
_ips = utils.list_sort([_host['interfaces'][0]['ip'] for _host in _data], key=inet_aton, deduplication=True)
|
203
|
-
_data = [_host for _ip in _ips for _host in _data if _ip == _host['interfaces'][0]['ip']]
|
204
|
-
|
205
|
-
logger.success('{} | start'.format(title))
|
206
|
-
|
207
|
-
try:
|
208
|
-
|
209
|
-
# 初始化变量 (用于 pandas 处理数据)
|
210
|
-
_data_idx, _data_max, _data_avg, _data_min = [], [], [], []
|
211
|
-
|
212
|
-
# 提取数据
|
213
|
-
for _host in _data:
|
214
|
-
_num_max, _num_avg, _num_min = utils.mam_of_numbers([_x['value'] for _x in _host['history']], number_type)
|
215
|
-
if (_num_max != None) and (_num_avg != None) and (_num_min != None):
|
216
|
-
_data_idx.append(_host['name'])
|
217
|
-
_data_max.append(number_handling(_num_max) if callable(number_handling) == True else _num_max)
|
218
|
-
_data_avg.append(number_handling(_num_avg) if callable(number_handling) == True else _num_avg)
|
219
|
-
_data_min.append(number_handling(_num_min) if callable(number_handling) == True else _num_min)
|
220
|
-
|
221
|
-
# 判断结果
|
222
|
-
if (len(_data_idx) > 0) and (image != None):
|
223
|
-
|
224
|
-
# 写入文件
|
225
|
-
with open(self._markdown_file, 'a') as _file:
|
226
|
-
|
227
|
-
_file.writelines([
|
228
|
-
'\n',
|
229
|
-
'## {}\n'.format(title),
|
230
|
-
'\n',
|
231
|
-
'{}\n'.format(description),
|
232
|
-
'\n',
|
233
|
-
'| {} | Min | Average | Max |\n'.format(table_header_title),
|
234
|
-
'| --- | --: | --: | --: |\n'
|
235
|
-
])
|
236
|
-
|
237
|
-
for _i, _v in enumerate(_data_idx):
|
238
|
-
_file.write('| {0} | {1:.2f}{4} | {2:.2f}{4} | {3:.2f}{4} |\n'.format(_v, _data_min[_i], _data_avg[_i], _data_max[_i], number_unit))
|
239
|
-
|
240
|
-
_plot_data = [
|
241
|
-
{'key': 'max', 'label': 'Max', 'kind': 'barh', 'data': _data_max, 'color': '#E74C3C', 'width': 0.8},
|
242
|
-
{'key': 'avg', 'label': 'Avg', 'kind': 'barh', 'data': _data_avg, 'color': '#3498DB', 'width': 0.8},
|
243
|
-
{'key': 'min', 'label': 'Min', 'kind': 'barh', 'data': _data_min, 'color': '#2ECC71', 'width': 0.8}
|
244
|
-
]
|
245
|
-
|
246
|
-
_plot_image = {
|
247
|
-
'title': title,
|
248
|
-
'size': (20, (len(_data_idx) / 5) * 2),
|
249
|
-
'path': image['path'],
|
250
|
-
'dpi': 300
|
251
|
-
}
|
252
|
-
|
253
|
-
_plot_result = plots.bar_cover(_plot_data, _data_idx, _plot_image)
|
254
|
-
|
255
|
-
# '<img src="cid:{}">\n'.format(_image['cid'])
|
256
|
-
# '\n'.format(_image['cid'])
|
257
|
-
# 图片显示大小: 仅设置 width, height 自适应
|
258
|
-
if _plot_result == True:
|
259
|
-
_file.writelines([
|
260
|
-
'\n',
|
261
|
-
'<img src="cid:{}" width="1000px">\n'.format(image['cid'])
|
262
|
-
])
|
263
|
-
|
264
|
-
logger.success('{} | end'.format(title))
|
265
|
-
|
266
|
-
return True
|
267
|
-
|
268
|
-
except Exception as e:
|
269
|
-
logger.exception(e)
|
270
|
-
logger.error('{} | end'.format(title))
|
271
|
-
return False
|
272
|
-
|
273
|
-
def handling_html(self, *args, **kwargs):
|
274
|
-
''' 处理 HTML '''
|
275
|
-
|
276
|
-
logger.success('handling HTML | start')
|
277
|
-
|
278
|
-
try:
|
279
|
-
|
280
|
-
if utils.check_file_type(self._html_file, 'file'):
|
281
|
-
|
282
|
-
# HTML内容
|
283
|
-
_html_lines = None
|
284
|
-
|
285
|
-
# 移除自带样式
|
286
|
-
with open(self._html_file, "r") as _html_input:
|
287
|
-
_html_lines = _html_input.readlines()
|
288
|
-
del _html_lines[7:161]
|
289
|
-
|
290
|
-
# 遍历内容
|
291
|
-
for _i, _v in enumerate(_html_lines):
|
292
|
-
|
293
|
-
# 移除表格宽度
|
294
|
-
_table_width = re.compile(r'<table style="width:100%;">')
|
295
|
-
if len(_table_width.findall(_v)) > 0:
|
296
|
-
_html_lines[_i] = re.sub(_table_width, '<table>', _v)
|
297
|
-
|
298
|
-
# 移除 colgroup
|
299
|
-
_colgroup = re.compile(r'</?colgroup>')
|
300
|
-
if len(_colgroup.findall(_v)) > 0:
|
301
|
-
_html_lines[_i] = re.sub(_colgroup, '', _v)
|
302
|
-
|
303
|
-
# 移除列宽度
|
304
|
-
_col_width = re.compile(r'<col style="width: .*%" />')
|
305
|
-
if len(_col_width.findall(_v)) > 0:
|
306
|
-
_html_lines[_i] = re.sub(_col_width, '', _v)
|
307
|
-
|
308
|
-
# 写入文件
|
309
|
-
with open(self._html_file, "w") as _html_output:
|
310
|
-
_html_output.writelines(_html_lines)
|
311
|
-
|
312
|
-
logger.success('handling HTML | end')
|
313
|
-
return True
|
314
|
-
|
315
|
-
except Exception as e:
|
316
|
-
logger.exception(e)
|
317
|
-
logger.error('handling HTML | end')
|
318
|
-
return False
|
319
|
-
|
320
|
-
def markdown_to_html(self, dir='.', **kwargs):
|
321
|
-
'''
|
322
|
-
Markdown to HTML
|
323
|
-
使用 MacDown 生成 HTML, 然后提取样式到 markdown.html
|
324
|
-
pandoc 生成的 HTML 默认 max-width: 36em, 如果表格内容很长, 会导致表格样式难看
|
325
|
-
所以在 markdown.html 的 body{...} 中添加配置 max-width: unset, 解决内容过长的样式问题
|
326
|
-
所有 a 标签添加 text-decoration: none; 去除链接下划线
|
327
|
-
pandoc --no-highlight -s --quiet -f markdown -t html -H markdown.html -o history.html history.md
|
328
|
-
'''
|
329
|
-
|
330
|
-
logger.success('markdown to html | start')
|
331
|
-
|
332
|
-
try:
|
333
|
-
|
334
|
-
_result = utils.shell(
|
335
|
-
'pandoc --no-highlight -s --quiet -f markdown -t html -H {}/markdown.html -o {} {}'.format(dir, self._html_file, self._markdown_file)
|
336
|
-
)
|
337
|
-
|
338
|
-
if _result != None and _result.returncode == 0:
|
339
|
-
logger.success('markdown to html | end')
|
340
|
-
return True
|
341
|
-
else:
|
342
|
-
logger.error('markdown to html | end')
|
343
|
-
return False
|
344
|
-
|
345
|
-
except Exception as e:
|
346
|
-
logger.exception(e)
|
347
|
-
logger.error('markdown to html | end')
|
348
|
-
return False
|
ezKit/plots.py
DELETED
@@ -1,155 +0,0 @@
|
|
1
|
-
import matplotlib.patches as mpatches
|
2
|
-
import matplotlib.pyplot as plt
|
3
|
-
import numpy as np
|
4
|
-
import pandas as pd
|
5
|
-
from loguru import logger
|
6
|
-
|
7
|
-
|
8
|
-
def bar(data={}, index=[], image={}, **kwargs):
|
9
|
-
'''
|
10
|
-
标准条形图
|
11
|
-
https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.plot.html
|
12
|
-
https://matplotlib.org/stable/api/pyplot_summary.html
|
13
|
-
'''
|
14
|
-
try:
|
15
|
-
_df = pd.DataFrame(data, index=index)
|
16
|
-
'''
|
17
|
-
title: 标题
|
18
|
-
kind: 类型
|
19
|
-
figsize: 图片大小, 以 100 为基数, 这里输出的图片为 2000 x 2000
|
20
|
-
width: 图形条宽度
|
21
|
-
dpi: 清晰度
|
22
|
-
bbox_inches='tight' 去除图片周边空白
|
23
|
-
'''
|
24
|
-
_ax = _df.plot(title=image.get('title'), kind=image.get('kind', 'bar'), figsize=image.get('size', (10, 10)), width=image.get('width', 0.8))
|
25
|
-
_ax.set_xlim(image.get('xlim'))
|
26
|
-
_ax.set_ylim(image.get('ylim'))
|
27
|
-
_ax.figure.savefig(image.get('path', 'image.png'), dpi=image.get('dpi', 300), bbox_inches='tight')
|
28
|
-
return True
|
29
|
-
|
30
|
-
except Exception as e:
|
31
|
-
logger.exception(e)
|
32
|
-
return False
|
33
|
-
|
34
|
-
def bar_cover(data=[], index=[], image={}, **kwargs):
|
35
|
-
'''
|
36
|
-
重叠条形图
|
37
|
-
https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.plot.html
|
38
|
-
https://matplotlib.org/stable/api/pyplot_summary.html
|
39
|
-
df.plot.bar() 和 df.plot.barh() 中 stacked=True 的效果是叠加, 即所有图层堆积拼接在一起
|
40
|
-
这里需要的效果是图层重叠, 即按从大到小的顺序依次重叠
|
41
|
-
但是 pandas 没有好的处理方法, 为了实现重叠效果, 以下使用设置 ax 处理
|
42
|
-
'''
|
43
|
-
|
44
|
-
try:
|
45
|
-
|
46
|
-
# 创建数据实例
|
47
|
-
_df = pd.DataFrame({item['key']: item['data'] for item in data}, index)
|
48
|
-
|
49
|
-
'''
|
50
|
-
设置图形类型、颜色、宽度
|
51
|
-
注意顺序: 从大到小排列
|
52
|
-
因为图层是叠加的, 所以后面的图层会覆盖前面的图层
|
53
|
-
如果后面图层的较大, 就会前面较小的图层, 所以把图层较大的放在前面, 图层较小的放在后面
|
54
|
-
_, ax = plt.subplots()
|
55
|
-
df.MAX.plot(kind='barh', ax=ax, color='#E74C3C', width=0.8)
|
56
|
-
df.MID.plot(kind='barh', ax=ax, color='#3498DB', width=0.8)
|
57
|
-
df.MIN.plot(kind='barh', ax=ax, color='#2ECC71', width=0.8)
|
58
|
-
'''
|
59
|
-
_, _ax = plt.subplots()
|
60
|
-
for i in data:
|
61
|
-
_df[i['key']].plot(kind=i.get('kind', 'bar'), ax=_ax, color=i.get('color'), width=i.get('width', 0.8))
|
62
|
-
|
63
|
-
'''
|
64
|
-
设置 Label
|
65
|
-
即图片右上角的说明信息, 这里也有顺序, 会按照 handles 中的顺序显示
|
66
|
-
https://stackoverflow.com/a/69897921
|
67
|
-
patch_max = mpatches.Patch(color='#E74C3C', label='Max')
|
68
|
-
patch_mid = mpatches.Patch(color='#3498DB', label='Mid')
|
69
|
-
patch_min = mpatches.Patch(color='#2ECC71', label='Min')
|
70
|
-
plt.legend(handles=[patch_max, patch_mid, patch_min])
|
71
|
-
'''
|
72
|
-
plt.legend(handles=[mpatches.Patch(color=i.get('color'), label=i.get('label')) for i in data])
|
73
|
-
|
74
|
-
# 设置标题
|
75
|
-
plt.title(image.get('title'))
|
76
|
-
|
77
|
-
# 设置上下限
|
78
|
-
plt.xlim(image.get('xlim'))
|
79
|
-
plt.ylim(image.get('ylim'))
|
80
|
-
|
81
|
-
# 创建图片实例
|
82
|
-
_fig = plt.gcf()
|
83
|
-
|
84
|
-
# 设置图片大小
|
85
|
-
# https://www.zhihu.com/question/37221233
|
86
|
-
_fig.set_size_inches(image.get('size', (10, 10)))
|
87
|
-
|
88
|
-
# 保存图片
|
89
|
-
# bbox_inches='tight' 去除图片周边空白
|
90
|
-
_fig.savefig(image.get('path', 'image.png'), dpi=image.get('dpi', 300), bbox_inches='tight')
|
91
|
-
|
92
|
-
# Close a figure window
|
93
|
-
plt.close()
|
94
|
-
|
95
|
-
# Return
|
96
|
-
return True
|
97
|
-
|
98
|
-
except Exception as e:
|
99
|
-
logger.exception(e)
|
100
|
-
return False
|
101
|
-
|
102
|
-
def bar_extend(data=[], index=[], image={}, **kwargs):
|
103
|
-
'''
|
104
|
-
扩展的条形图
|
105
|
-
https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.plot.html
|
106
|
-
https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.bar.html
|
107
|
-
https://matplotlib.org/stable/gallery/lines_bars_and_markers/barchart.html
|
108
|
-
https://stackoverflow.com/a/68107816
|
109
|
-
'''
|
110
|
-
try:
|
111
|
-
|
112
|
-
_x = np.arange(len(index))
|
113
|
-
|
114
|
-
_bar_width = image.get('width', 0.8)
|
115
|
-
|
116
|
-
_fig, _ax = plt.subplots()
|
117
|
-
|
118
|
-
_rects = _ax.bar(_x, data, _bar_width, label=image.get('label'), color=image.get('color'))
|
119
|
-
|
120
|
-
# Set base
|
121
|
-
_ax.set_title(image.get('title'))
|
122
|
-
_ax.set_xlabel(image.get('xlabel'))
|
123
|
-
_ax.set_ylabel(image.get('ylabel'))
|
124
|
-
_ax.set_xticks(_x, index)
|
125
|
-
|
126
|
-
# Set view limits
|
127
|
-
_ax.set_xlim(image.get('xlim'))
|
128
|
-
_ax.set_ylim(image.get('ylim'))
|
129
|
-
|
130
|
-
# 设置图例
|
131
|
-
_ax.legend()
|
132
|
-
|
133
|
-
# bar 顶部显示 value
|
134
|
-
_ax.bar_label(_rects, padding=3)
|
135
|
-
|
136
|
-
# 自动调整参数, 使图形适合图形区域
|
137
|
-
_fig.tight_layout()
|
138
|
-
|
139
|
-
# 图片大小
|
140
|
-
# 默认 300px 为 1 个单位
|
141
|
-
# 默认 1920px * 1440px, 即 6.4 * 4.8
|
142
|
-
_fig.set_size_inches(image.get('size', (6.4, 4.8)))
|
143
|
-
|
144
|
-
# 生成图片文件
|
145
|
-
# bbox_inches='tight' 去除图片周边空白
|
146
|
-
_fig.savefig(image.get('path', 'image.png'), dpi=image.get('dpi', 300), bbox_inches='tight')
|
147
|
-
|
148
|
-
# Close a figure window
|
149
|
-
plt.close()
|
150
|
-
|
151
|
-
return True
|
152
|
-
|
153
|
-
except Exception as e:
|
154
|
-
logger.exception(e)
|
155
|
-
return False
|
ezKit/qywx.py
DELETED
@@ -1,172 +0,0 @@
|
|
1
|
-
"""
|
2
|
-
企业微信开发者中心
|
3
|
-
|
4
|
-
https://developer.work.weixin.qq.com/
|
5
|
-
https://developer.work.weixin.qq.com/document/path/90313 (全局错误码)
|
6
|
-
|
7
|
-
参考文档:
|
8
|
-
|
9
|
-
https://www.gaoyuanqi.cn/python-yingyong-qiyewx/
|
10
|
-
https://www.jianshu.com/p/020709b130d3
|
11
|
-
"""
|
12
|
-
import json
|
13
|
-
import time
|
14
|
-
|
15
|
-
import requests
|
16
|
-
from loguru import logger
|
17
|
-
|
18
|
-
from . import utils
|
19
|
-
|
20
|
-
|
21
|
-
class QYWX:
|
22
|
-
"""企业微信"""
|
23
|
-
|
24
|
-
url_prefix = 'https://qyapi.weixin.qq.com'
|
25
|
-
work_id: str | None = None
|
26
|
-
agent_id: str | None = None
|
27
|
-
agent_secret: str | None = None
|
28
|
-
access_token: str | None = None
|
29
|
-
|
30
|
-
def __init__(self, work_id: str | None, agent_id: str | None, agent_secret: str | None):
|
31
|
-
"""Initiation"""
|
32
|
-
self.work_id = work_id
|
33
|
-
self.agent_id = agent_id
|
34
|
-
self.agent_secret = agent_secret
|
35
|
-
|
36
|
-
"""获取 Token"""
|
37
|
-
self.getaccess_token()
|
38
|
-
|
39
|
-
def getaccess_token(self) -> str | None:
|
40
|
-
try:
|
41
|
-
response = requests.get(f'{self.url_prefix}/cgi-bin/gettoken?corpid={self.work_id}&corpsecret={self.agent_secret}')
|
42
|
-
if response.status_code == 200:
|
43
|
-
result: dict = response.json()
|
44
|
-
self.access_token = result.get('access_token')
|
45
|
-
else:
|
46
|
-
self.access_token = None
|
47
|
-
return result.get('access_token')
|
48
|
-
except:
|
49
|
-
return None
|
50
|
-
|
51
|
-
def get_agent_list(self) -> dict | str | None:
|
52
|
-
try:
|
53
|
-
self.getaccess_token() if self.access_token == None else next
|
54
|
-
response = requests.get(f'{self.url_prefix}/cgi-bin/agent/list?access_token={self.access_token}')
|
55
|
-
if response.status_code == 200:
|
56
|
-
response_data: dict = response.json()
|
57
|
-
if response_data.get('errcode') == 42001:
|
58
|
-
self.getaccess_token()
|
59
|
-
time.sleep(1)
|
60
|
-
self.get_agent_list()
|
61
|
-
return response_data
|
62
|
-
return response.text
|
63
|
-
except:
|
64
|
-
return None
|
65
|
-
|
66
|
-
def get_department_list(self, id) -> dict | str | None:
|
67
|
-
try:
|
68
|
-
self.getaccess_token() if self.access_token == None else next
|
69
|
-
response = requests.get(f'{self.url_prefix}/cgi-bin/department/list?access_token={self.access_token}&id={id}')
|
70
|
-
if response.status_code == 200:
|
71
|
-
response_data: dict = response.json()
|
72
|
-
if response_data.get('errcode') == 42001:
|
73
|
-
self.getaccess_token()
|
74
|
-
time.sleep(1)
|
75
|
-
self.get_department_list(id)
|
76
|
-
return response_data
|
77
|
-
return response.text
|
78
|
-
except:
|
79
|
-
return None
|
80
|
-
|
81
|
-
def get_user_list(self, id) -> dict | str | None:
|
82
|
-
try:
|
83
|
-
self.getaccess_token() if self.access_token == None else next
|
84
|
-
response = requests.get(f'{self.url_prefix}/cgi-bin/user/list?access_token={self.access_token}&department_id={id}')
|
85
|
-
if response.status_code == 200:
|
86
|
-
response_data: dict = response.json()
|
87
|
-
if response_data.get('errcode') == 42001:
|
88
|
-
self.getaccess_token()
|
89
|
-
time.sleep(1)
|
90
|
-
self.get_user_list(id)
|
91
|
-
return response_data
|
92
|
-
return response.text
|
93
|
-
except:
|
94
|
-
return None
|
95
|
-
|
96
|
-
def get_user_id_by_mobile(self, mobile) -> dict | str | None:
|
97
|
-
try:
|
98
|
-
self.getaccess_token() if self.access_token == None else next
|
99
|
-
json_string = json.dumps({'mobile': mobile})
|
100
|
-
response = requests.post(f'{self.url_prefix}/cgi-bin/user/getuserid?access_token={self.access_token}', data=json_string)
|
101
|
-
if response.status_code == 200:
|
102
|
-
response_data: dict = response.json()
|
103
|
-
if response_data.get('errcode') == 42001:
|
104
|
-
self.getaccess_token()
|
105
|
-
time.sleep(1)
|
106
|
-
self.get_user_id_by_mobile(id)
|
107
|
-
return response_data
|
108
|
-
return response.text
|
109
|
-
except:
|
110
|
-
return None
|
111
|
-
|
112
|
-
def get_user_info(self, id) -> dict | str | None:
|
113
|
-
try:
|
114
|
-
self.getaccess_token() if self.access_token == None else next
|
115
|
-
response = requests.get(f'{self.url_prefix}/cgi-bin/user/get?access_token={self.access_token}&userid={id}')
|
116
|
-
if response.status_code == 200:
|
117
|
-
response_data: dict = response.json()
|
118
|
-
if response_data.get('errcode') == 42001:
|
119
|
-
self.getaccess_token()
|
120
|
-
time.sleep(1)
|
121
|
-
self.get_user_info(id)
|
122
|
-
return response_data
|
123
|
-
return response.text
|
124
|
-
except:
|
125
|
-
return None
|
126
|
-
|
127
|
-
def send_message_by_mobile(self, mobile: str | list, message: str, debug: bool = False) -> bool:
|
128
|
-
"""发送消息"""
|
129
|
-
"""
|
130
|
-
参考文档:
|
131
|
-
|
132
|
-
https://developer.work.weixin.qq.com/document/path/90235
|
133
|
-
"""
|
134
|
-
try:
|
135
|
-
self.getaccess_token() if self.access_token == None else next
|
136
|
-
|
137
|
-
users: list = []
|
138
|
-
|
139
|
-
match True:
|
140
|
-
case True if utils.v_true(mobile, list):
|
141
|
-
users = mobile
|
142
|
-
case True if utils.v_true(mobile, str):
|
143
|
-
users.append(mobile)
|
144
|
-
case _:
|
145
|
-
return None
|
146
|
-
|
147
|
-
for user in users:
|
148
|
-
user_object = self.get_user_id_by_mobile(user)
|
149
|
-
json_dict = {
|
150
|
-
'touser': user_object.get('userid'),
|
151
|
-
'msgtype': 'text',
|
152
|
-
'agentid': self.agent_id,
|
153
|
-
'text': {'content': message},
|
154
|
-
'safe': 0,
|
155
|
-
'enable_id_trans': 0,
|
156
|
-
'enable_duplicate_check': 0,
|
157
|
-
'duplicate_check_interval': 1800
|
158
|
-
}
|
159
|
-
json_string = json.dumps(json_dict)
|
160
|
-
response = requests.post(f'{self.url_prefix}/cgi-bin/message/send?access_token={self.access_token}', data=json_string)
|
161
|
-
if response.status_code == 200:
|
162
|
-
response_data: dict = response.json()
|
163
|
-
if response_data.get('errcode') == 42001:
|
164
|
-
self.getaccess_token()
|
165
|
-
time.sleep(1)
|
166
|
-
self.send_message_by_mobile(mobile, message)
|
167
|
-
|
168
|
-
return True
|
169
|
-
|
170
|
-
except Exception as e:
|
171
|
-
logger.exception(e) if utils.v_true(debug, bool) else next
|
172
|
-
return False
|