tools.py 62 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401
  1. # -*- coding: utf-8 -*-
  2. """
  3. Created on 2018-09-06 14:21
  4. ---------
  5. @summary: 工具
  6. ---------
  7. @author: Boris
  8. @email: boris_liu@foxmail.com
  9. """
  10. import asyncio
  11. import calendar
  12. import codecs
  13. import configparser # 读配置文件的
  14. import datetime
  15. import functools
  16. import hashlib
  17. import html
  18. import importlib
  19. import json
  20. import os
  21. import pickle
  22. import random
  23. import re
  24. import socket
  25. import ssl
  26. import string
  27. import sys
  28. import time
  29. import traceback
  30. import urllib
  31. import urllib.parse
  32. import uuid
  33. import weakref
  34. from functools import partial, wraps
  35. from hashlib import md5
  36. from pprint import pformat
  37. from pprint import pprint
  38. from urllib import request
  39. from urllib.parse import urljoin
  40. import bson
  41. import execjs # pip install PyExecJS
  42. import redis
  43. import requests
  44. import six
  45. from requests.cookies import RequestsCookieJar
  46. from w3lib.url import canonicalize_url as _canonicalize_url
  47. import setting as setting
  48. from db.redisdb import RedisDB
  49. from utils.log import logger as log
  50. os.environ["EXECJS_RUNTIME"] = "Node" # 设置使用node执行js
  51. # 全局取消ssl证书验证
  52. ssl._create_default_https_context = ssl._create_unverified_context
  53. TIME_OUT = 30
  54. TIMER_TIME = 5
  55. redisdb = None
  56. def get_redisdb():
  57. global redisdb
  58. if not redisdb:
  59. redisdb = RedisDB()
  60. return redisdb
  61. # 装饰器
  62. class Singleton(object):
  63. def __init__(self, cls):
  64. self._cls = cls
  65. self._instance = {}
  66. def __call__(self, *args, **kwargs):
  67. if self._cls not in self._instance:
  68. self._instance[self._cls] = self._cls(*args, **kwargs)
  69. return self._instance[self._cls]
  70. def log_function_time(func):
  71. try:
  72. @functools.wraps(func) # 将函数的原来属性付给新函数
  73. def calculate_time(*args, **kw):
  74. began_time = time.time()
  75. callfunc = func(*args, **kw)
  76. end_time = time.time()
  77. log.debug(func.__name__ + " run time = " + str(end_time - began_time))
  78. return callfunc
  79. return calculate_time
  80. except:
  81. log.debug("求取时间无效 因为函数参数不符")
  82. return func
  83. def run_safe_model(module_name):
  84. def inner_run_safe_model(func):
  85. try:
  86. @functools.wraps(func) # 将函数的原来属性付给新函数
  87. def run_func(*args, **kw):
  88. callfunc = None
  89. try:
  90. callfunc = func(*args, **kw)
  91. except Exception as e:
  92. log.error(module_name + ": " + func.__name__ + " - " + str(e))
  93. traceback.print_exc()
  94. return callfunc
  95. return run_func
  96. except Exception as e:
  97. log.error(module_name + ": " + func.__name__ + " - " + str(e))
  98. traceback.print_exc()
  99. return func
  100. return inner_run_safe_model
  101. def memoizemethod_noargs(method):
  102. """Decorator to cache the result of a method (without arguments) using a
  103. weak reference to its object
  104. """
  105. cache = weakref.WeakKeyDictionary()
  106. @functools.wraps(method)
  107. def new_method(self, *args, **kwargs):
  108. if self not in cache:
  109. cache[self] = method(self, *args, **kwargs)
  110. return cache[self]
  111. return new_method
  112. ########################【网页解析相关】###############################
  113. def get_longest_common_sub_string(str1: str, str2: str) -> str:
  114. """
  115. 获取两个字符串的最长公共子串。
  116. 构造一个矩阵,横向是字符串1,纵向是字符串2,例如:
  117. 青南是天才!?
  118. 听0 0 0 0 00 0
  119. 说0 0 0 0 00 0
  120. 青1 0 0 0 00 0
  121. 南0 1 0 0 00 0
  122. 是0 0 1 0 00 0
  123. 天0 0 0 1 00 0
  124. 才0 0 0 0 10 0
  125. !0 0 0 0 01 0
  126. 显然,只要斜对角线最长的就是最长公共子串
  127. :param str1:
  128. :param str2:
  129. :return:
  130. """
  131. if not all([str1, str2]):
  132. return ''
  133. matrix = [[0] * (len(str2) + 1) for _ in range(len(str1) + 1)]
  134. max_length = 0
  135. start_position = 0
  136. for index_of_str1 in range(1, len(str1) + 1):
  137. for index_of_str2 in range(1, len(str2) + 1):
  138. if str1[index_of_str1 - 1] == str2[index_of_str2 - 1]:
  139. matrix[index_of_str1][index_of_str2] = matrix[index_of_str1 - 1][index_of_str2 - 1] + 1
  140. if matrix[index_of_str1][index_of_str2] > max_length:
  141. max_length = matrix[index_of_str1][index_of_str2]
  142. start_position = index_of_str1 - max_length
  143. else:
  144. matrix[index_of_str1][index_of_str2] = 0
  145. return str1[start_position: start_position + max_length]
  146. def get_cookies(response):
  147. cookies = requests.utils.dict_from_cookiejar(response.cookies)
  148. return cookies
  149. def get_cookies_from_str(cookie_str):
  150. """
  151. >>> get_cookies_from_str("key=value; key2=value2; key3=; key4=; ")
  152. {'key': 'value', 'key2': 'value2', 'key3': '', 'key4': ''}
  153. Args:
  154. cookie_str: key=value; key2=value2; key3=; key4=
  155. Returns:
  156. """
  157. cookies = {}
  158. for cookie in cookie_str.split(";"):
  159. cookie = cookie.strip()
  160. if not cookie:
  161. continue
  162. key, value = cookie.split("=", 1)
  163. key = key.strip()
  164. value = value.strip()
  165. cookies[key] = value
  166. return cookies
  167. def get_cookies_jar(cookies):
  168. """
  169. @summary: 适用于selenium生成的cookies转requests的cookies
  170. requests.get(xxx, cookies=jar)
  171. 参考:https://www.cnblogs.com/small-bud/p/9064674.html
  172. ---------
  173. @param cookies: [{},{}]
  174. ---------
  175. @result: cookie jar
  176. """
  177. cookie_jar = RequestsCookieJar()
  178. for cookie in cookies:
  179. cookie_jar.set(cookie["name"], cookie["value"])
  180. return cookie_jar
  181. def get_cookies_from_selenium_cookie(cookies):
  182. """
  183. @summary: 适用于selenium生成的cookies转requests的cookies
  184. requests.get(xxx, cookies=jar)
  185. 参考:https://www.cnblogs.com/small-bud/p/9064674.html
  186. ---------
  187. @param cookies: [{},{}]
  188. ---------
  189. @result: cookie jar
  190. """
  191. cookie_dict = {}
  192. for cookie in cookies:
  193. if cookie.get("name"):
  194. cookie_dict[cookie["name"]] = cookie["value"]
  195. return cookie_dict
  196. def cookiesjar2str(cookies):
  197. str_cookie = ""
  198. for k, v in requests.utils.dict_from_cookiejar(cookies).items():
  199. str_cookie += k
  200. str_cookie += "="
  201. str_cookie += v
  202. str_cookie += "; "
  203. return str_cookie
  204. def cookies2str(cookies):
  205. str_cookie = ""
  206. for k, v in cookies.items():
  207. str_cookie += k
  208. str_cookie += "="
  209. str_cookie += v
  210. str_cookie += "; "
  211. return str_cookie
  212. def get_urls(
  213. html,
  214. stop_urls=(
  215. "javascript",
  216. "+",
  217. ".css",
  218. ".js",
  219. ".rar",
  220. ".xls",
  221. ".exe",
  222. ".apk",
  223. ".doc",
  224. ".jpg",
  225. ".png",
  226. ".flv",
  227. ".mp4",
  228. ),
  229. ):
  230. # 不匹配javascript、 +、 # 这样的url
  231. regex = r'<a.*?href.*?=.*?["|\'](.*?)["|\']'
  232. urls = get_info(html, regex)
  233. urls = sorted(set(urls), key=urls.index)
  234. if stop_urls:
  235. stop_urls = isinstance(stop_urls, str) and [stop_urls] or stop_urls
  236. use_urls = []
  237. for url in urls:
  238. for stop_url in stop_urls:
  239. if stop_url in url:
  240. break
  241. else:
  242. use_urls.append(url)
  243. urls = use_urls
  244. return urls
  245. def get_full_url(root_url, sub_url):
  246. """
  247. @summary: 得到完整的ur
  248. ---------
  249. @param root_url: 根url (网页的url)
  250. @param sub_url: 子url (带有相对路径的 可以拼接成完整的)
  251. ---------
  252. @result: 返回完整的url
  253. """
  254. return urljoin(root_url, sub_url)
  255. def joint_url(url, params):
  256. # param_str = "?"
  257. # for key, value in params.items():
  258. # value = isinstance(value, str) and value or str(value)
  259. # param_str += key + "=" + value + "&"
  260. #
  261. # return url + param_str[:-1]
  262. if not params:
  263. return url
  264. params = urlencode(params)
  265. separator = "?" if "?" not in url else "&"
  266. return url + separator + params
  267. def canonicalize_url(url):
  268. """
  269. url 归一化 会参数排序 及去掉锚点
  270. """
  271. return _canonicalize_url(url)
  272. def get_url_md5(url):
  273. url = canonicalize_url(url)
  274. url = re.sub("^http://", "https://", url)
  275. return get_md5(url)
  276. def fit_url(urls, identis):
  277. identis = isinstance(identis, str) and [identis] or identis
  278. fit_urls = []
  279. for link in urls:
  280. for identi in identis:
  281. if identi in link:
  282. fit_urls.append(link)
  283. return list(set(fit_urls))
  284. def get_param(url, key):
  285. params = url.split("?")[-1].split("&")
  286. for param in params:
  287. key_value = param.split("=", 1)
  288. if key == key_value[0]:
  289. return key_value[1]
  290. return None
  291. def urlencode(params):
  292. """
  293. 字典类型的参数转为字符串
  294. @param params:
  295. {
  296. 'a': 1,
  297. 'b': 2
  298. }
  299. @return: a=1&b=2
  300. """
  301. return urllib.parse.urlencode(params)
  302. def urldecode(url):
  303. """
  304. 将字符串类型的参数转为json
  305. @param url: xxx?a=1&b=2
  306. @return:
  307. {
  308. 'a': 1,
  309. 'b': 2
  310. }
  311. """
  312. params_json = {}
  313. params = url.split("?")[-1].split("&")
  314. for param in params:
  315. key, value = param.split("=")
  316. params_json[key] = unquote_url(value)
  317. return params_json
  318. def unquote_url(url, encoding="utf-8"):
  319. """
  320. @summary: 将url解码
  321. ---------
  322. @param url:
  323. ---------
  324. @result:
  325. """
  326. return urllib.parse.unquote(url, encoding=encoding)
  327. def quote_url(url, encoding="utf-8"):
  328. """
  329. @summary: 将url编码 编码意思http://www.w3school.com.cn/tags/html_ref_urlencode.html
  330. ---------
  331. @param url:
  332. ---------
  333. @result:
  334. """
  335. return urllib.parse.quote(url, safe="%;/?:@&=+$,", encoding=encoding)
  336. def quote_chinese_word(text, encoding="utf-8"):
  337. def quote_chinese_word_func(text):
  338. chinese_word = text.group(0)
  339. return urllib.parse.quote(chinese_word, encoding=encoding)
  340. return re.sub("([\u4e00-\u9fa5]+)", quote_chinese_word_func, text, flags=re.S)
  341. def unescape(str):
  342. """
  343. 反转译
  344. """
  345. return html.unescape(str)
  346. def excape(str):
  347. """
  348. 转译
  349. """
  350. return html.escape(str)
  351. _regexs = {}
  352. # @log_function_time
  353. def get_info(html, regexs, allow_repeat=True, fetch_one=False, split=None):
  354. regexs = isinstance(regexs, str) and [regexs] or regexs
  355. infos = []
  356. for regex in regexs:
  357. if regex == "":
  358. continue
  359. if regex not in _regexs.keys():
  360. _regexs[regex] = re.compile(regex, re.S)
  361. if fetch_one:
  362. infos = _regexs[regex].search(html)
  363. if infos:
  364. infos = infos.groups()
  365. else:
  366. continue
  367. else:
  368. infos = _regexs[regex].findall(str(html))
  369. if len(infos) > 0:
  370. # print(regex)
  371. break
  372. if fetch_one:
  373. infos = infos if infos else ("",)
  374. return infos if len(infos) > 1 else infos[0]
  375. else:
  376. infos = allow_repeat and infos or sorted(set(infos), key=infos.index)
  377. infos = split.join(infos) if split else infos
  378. return infos
  379. def table_json(table, save_one_blank=True):
  380. """
  381. 将表格转为json 适应于 key:value 在一行类的表格
  382. @param table: 使用selector封装后的具有xpath的selector
  383. @param save_one_blank: 保留一个空白符
  384. @return:
  385. """
  386. data = {}
  387. trs = table.xpath(".//tr")
  388. for tr in trs:
  389. tds = tr.xpath("./td|./th")
  390. for i in range(0, len(tds), 2):
  391. if i + 1 > len(tds) - 1:
  392. break
  393. key = tds[i].xpath("string(.)").extract_first(default="").strip()
  394. value = tds[i + 1].xpath("string(.)").extract_first(default="").strip()
  395. value = replace_str(value, "[\f\n\r\t\v]", "")
  396. value = replace_str(value, " +", " " if save_one_blank else "")
  397. if key:
  398. data[key] = value
  399. return data
  400. def get_table_row_data(table):
  401. """
  402. 获取表格里每一行数据
  403. @param table: 使用selector封装后的具有xpath的selector
  404. @return: [[],[]..]
  405. """
  406. datas = []
  407. rows = table.xpath(".//tr")
  408. for row in rows:
  409. cols = row.xpath("./td|./th")
  410. row_datas = []
  411. for col in cols:
  412. data = col.xpath("string(.)").extract_first(default="").strip()
  413. row_datas.append(data)
  414. datas.append(row_datas)
  415. return datas
  416. def rows2json(rows, keys=None):
  417. """
  418. 将行数据转为json
  419. @param rows: 每一行的数据
  420. @param keys: json的key,空时将rows的第一行作为key
  421. @return:
  422. """
  423. data_start_pos = 0 if keys else 1
  424. datas = []
  425. keys = keys or rows[0]
  426. for values in rows[data_start_pos:]:
  427. datas.append(dict(zip(keys, values)))
  428. return datas
  429. def get_form_data(form):
  430. """
  431. 提取form中提交的数据
  432. :param form: 使用selector封装后的具有xpath的selector
  433. :return:
  434. """
  435. data = {}
  436. inputs = form.xpath(".//input")
  437. for input in inputs:
  438. name = input.xpath("./@name").extract_first()
  439. value = input.xpath("./@value").extract_first()
  440. if name:
  441. data[name] = value
  442. return data
  443. def get_domain(url):
  444. return urllib.parse.urlparse(url).netloc
  445. def get_index_url(url):
  446. return "/".join(url.split("/")[:3])
  447. def get_ip(domain):
  448. ip = socket.getaddrinfo(domain, "http")[0][4][0]
  449. return ip
  450. def get_localhost_ip():
  451. """
  452. 利用 UDP 协议来实现的,生成一个UDP包,把自己的 IP 放如到 UDP 协议头中,然后从UDP包中获取本机的IP。
  453. 这个方法并不会真实的向外部发包,所以用抓包工具是看不到的
  454. :return:
  455. """
  456. s = None
  457. try:
  458. s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  459. s.connect(("8.8.8.8", 80))
  460. ip = s.getsockname()[0]
  461. finally:
  462. if s:
  463. s.close()
  464. return ip
  465. def ip_to_num(ip):
  466. import struct
  467. ip_num = socket.ntohl(struct.unpack("I", socket.inet_aton(str(ip)))[0])
  468. return ip_num
  469. def is_valid_proxy(proxy, check_url=None):
  470. """
  471. 检验代理是否有效
  472. @param proxy: xxx.xxx.xxx:xxx
  473. @param check_url: 利用目标网站检查,目标网站url。默认为None, 使用代理服务器的socket检查, 但不能排除Connection closed by foreign host
  474. @return: True / False
  475. """
  476. is_valid = False
  477. if check_url:
  478. proxies = {"http": f"http://{proxy}", "https": f"https://{proxy}"}
  479. headers = {
  480. "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36"
  481. }
  482. response = None
  483. try:
  484. response = requests.get(
  485. check_url, headers=headers, proxies=proxies, stream=True, timeout=20
  486. )
  487. is_valid = True
  488. except Exception as e:
  489. log.error("check proxy failed: {} {}".format(e, proxy))
  490. finally:
  491. if response:
  492. response.close()
  493. else:
  494. ip, port = proxy.split(":")
  495. with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sk:
  496. sk.settimeout(7)
  497. try:
  498. sk.connect((ip, int(port))) # 检查代理服务器是否开着
  499. is_valid = True
  500. except Exception as e:
  501. log.error("check proxy failed: {} {}:{}".format(e, ip, port))
  502. return is_valid
  503. def is_valid_url(url):
  504. """
  505. 验证url是否合法
  506. :param url:
  507. :return:
  508. """
  509. if re.match(r"(^https?:/{2}\w.+$)|(ftp://)", url):
  510. return True
  511. else:
  512. return False
  513. def get_text(soup, *args):
  514. try:
  515. return soup.get_text()
  516. except Exception as e:
  517. log.error(e)
  518. return ""
  519. def del_html_tag(content, except_line_break=False, save_img=False, white_replaced=""):
  520. """
  521. 删除html标签
  522. @param content: html内容
  523. @param except_line_break: 保留p标签
  524. @param save_img: 保留图片
  525. @param white_replaced: 空白符替换
  526. @return:
  527. """
  528. content = replace_str(content, "(?i)<script(.|\n)*?</script>") # (?)忽略大小写
  529. content = replace_str(content, "(?i)<style(.|\n)*?</style>")
  530. content = replace_str(content, "<!--(.|\n)*?-->")
  531. content = replace_str(
  532. content, "(?!&[a-z]+=)&[a-z]+;?"
  533. ) # 干掉&nbsp等无用的字符 但&xxx= 这种表示参数的除外
  534. if except_line_break:
  535. content = content.replace("</p>", "/p")
  536. content = replace_str(content, "<[^p].*?>")
  537. content = content.replace("/p", "</p>")
  538. content = replace_str(content, "[ \f\r\t\v]")
  539. elif save_img:
  540. content = replace_str(content, "(?!<img.+?>)<.+?>") # 替换掉除图片外的其他标签
  541. content = replace_str(content, "(?! +)\s+", "\n") # 保留空格
  542. content = content.strip()
  543. else:
  544. content = replace_str(content, "<(.|\n)*?>")
  545. content = replace_str(content, "\s", white_replaced)
  546. content = content.strip()
  547. return content
  548. def del_html_js_css(content):
  549. content = replace_str(content, "(?i)<script(.|\n)*?</script>") # (?)忽略大小写
  550. content = replace_str(content, "(?i)<style(.|\n)*?</style>")
  551. content = replace_str(content, "<!--(.|\n)*?-->")
  552. return content
  553. def is_have_chinese(content):
  554. regex = "[\u4e00-\u9fa5]+"
  555. chinese_word = get_info(content, regex)
  556. return chinese_word and True or False
  557. def is_have_english(content):
  558. regex = "[a-zA-Z]+"
  559. english_words = get_info(content, regex)
  560. return english_words and True or False
  561. def get_chinese_word(content):
  562. regex = "[\u4e00-\u9fa5]+"
  563. chinese_word = get_info(content, regex)
  564. return chinese_word
  565. def get_english_words(content):
  566. regex = "[a-zA-Z]+"
  567. english_words = get_info(content, regex)
  568. return english_words or ""
  569. ##################################################
  570. def get_json(json_str):
  571. """
  572. @summary: 取json对象
  573. ---------
  574. @param json_str: json格式的字符串
  575. ---------
  576. @result: 返回json对象
  577. """
  578. try:
  579. return json.loads(json_str) if json_str else {}
  580. except Exception as e1:
  581. try:
  582. json_str = json_str.strip()
  583. json_str = json_str.replace("'", '"')
  584. keys = get_info(json_str, "(\w+):")
  585. for key in keys:
  586. json_str = json_str.replace(key, '"%s"' % key)
  587. return json.loads(json_str) if json_str else {}
  588. except Exception as e2:
  589. pass
  590. return {}
  591. def jsonp2json(jsonp):
  592. """
  593. 将jsonp转为json
  594. @param jsonp: jQuery172013600082560040794_1553230569815({})
  595. @return:
  596. """
  597. try:
  598. return json.loads(re.match(".*?({.*}).*", jsonp, re.S).group(1))
  599. except:
  600. raise ValueError("Invalid Input")
  601. def dumps_json(data, indent=4, sort_keys=False):
  602. """
  603. @summary: 格式化json 用于打印
  604. ---------
  605. @param data: json格式的字符串或json对象
  606. ---------
  607. @result: 格式化后的字符串
  608. """
  609. try:
  610. if isinstance(data, str):
  611. data = get_json(data)
  612. data = json.dumps(
  613. data,
  614. ensure_ascii=False,
  615. indent=indent,
  616. skipkeys=True,
  617. sort_keys=sort_keys,
  618. default=str,
  619. )
  620. except Exception as e:
  621. data = pformat(data)
  622. return data
  623. def get_json_value(json_object, key):
  624. """
  625. @summary:
  626. ---------
  627. @param json_object: json对象或json格式的字符串
  628. @param key: 建值 如果在多个层级目录下 可写 key1.key2 如{'key1':{'key2':3}}
  629. ---------
  630. @result: 返回对应的值,如果没有,返回''
  631. """
  632. current_key = ""
  633. value = ""
  634. try:
  635. json_object = (
  636. isinstance(json_object, str) and get_json(json_object) or json_object
  637. )
  638. current_key = key.split(".")[0]
  639. value = json_object[current_key]
  640. key = key[key.find(".") + 1 :]
  641. except Exception as e:
  642. return value
  643. if key == current_key:
  644. return value
  645. else:
  646. return get_json_value(value, key)
  647. def get_all_keys(datas, depth=None, current_depth=0):
  648. """
  649. @summary: 获取json李所有的key
  650. ---------
  651. @param datas: dict / list
  652. @param depth: 字典key的层级 默认不限制层级 层级从1开始
  653. @param current_depth: 字典key的当前层级 不用传参
  654. ---------
  655. @result: 返回json所有的key
  656. """
  657. keys = []
  658. if depth and current_depth >= depth:
  659. return keys
  660. if isinstance(datas, list):
  661. for data in datas:
  662. keys.extend(get_all_keys(data, depth, current_depth=current_depth + 1))
  663. elif isinstance(datas, dict):
  664. for key, value in datas.items():
  665. keys.append(key)
  666. if isinstance(value, dict):
  667. keys.extend(get_all_keys(value, depth, current_depth=current_depth + 1))
  668. return keys
  669. def to_chinese(unicode_str):
  670. format_str = json.loads('{"chinese":"%s"}' % unicode_str)
  671. return format_str["chinese"]
  672. ##################################################
  673. def replace_str(source_str, regex, replace_str=""):
  674. """
  675. @summary: 替换字符串
  676. ---------
  677. @param source_str: 原字符串
  678. @param regex: 正则
  679. @param replace_str: 用什么来替换 默认为''
  680. ---------
  681. @result: 返回替换后的字符串
  682. """
  683. str_info = re.compile(regex)
  684. return str_info.sub(replace_str, source_str)
  685. def del_redundant_blank_character(text):
  686. """
  687. 删除冗余的空白符, 只保留一个
  688. :param text:
  689. :return:
  690. """
  691. return re.sub("\s+", " ", text)
  692. ##################################################
  693. def get_conf_value(config_file, section, key):
  694. cp = configparser.ConfigParser(allow_no_value=True)
  695. with codecs.open(config_file, "r", encoding="utf-8") as f:
  696. cp.read_file(f)
  697. return cp.get(section, key)
  698. def mkdir(path):
  699. try:
  700. if not os.path.exists(path):
  701. os.makedirs(path)
  702. except OSError as exc: # Python >2.5
  703. pass
  704. def write_file(filename, content, mode="w", encoding="utf-8"):
  705. """
  706. @summary: 写文件
  707. ---------
  708. @param filename: 文件名(有路径)
  709. @param content: 内容
  710. @param mode: 模式 w/w+ (覆盖/追加)
  711. ---------
  712. @result:
  713. """
  714. directory = os.path.dirname(filename)
  715. mkdir(directory)
  716. with open(filename, mode, encoding=encoding) as file:
  717. file.writelines(content)
  718. def read_file(filename, readlines=False, encoding="utf-8"):
  719. """
  720. @summary: 读文件
  721. ---------
  722. @param filename: 文件名(有路径)
  723. @param readlines: 按行读取 (默认False)
  724. ---------
  725. @result: 按行读取返回List,否则返回字符串
  726. """
  727. content = None
  728. try:
  729. with open(filename, "r", encoding=encoding) as file:
  730. content = file.readlines() if readlines else file.read()
  731. except Exception as e:
  732. log.error(e)
  733. return content
  734. def get_oss_file_list(oss_handler, prefix, date_range_min, date_range_max=None):
  735. """
  736. 获取文件列表
  737. @param prefix: 路径前缀 如 data/car_service_line/yiche/yiche_serial_zongshu_info
  738. @param date_range_min: 时间范围 最小值 日期分隔符为/ 如 2019/03/01 或 2019/03/01/00/00/00
  739. @param date_range_max: 时间范围 最大值 日期分隔符为/ 如 2019/03/01 或 2019/03/01/00/00/00
  740. @return: 每个文件路径 如 html/e_commerce_service_line/alibaba/alibaba_shop_info/2019/03/22/15/53/15/8ca8b9e4-4c77-11e9-9dee-acde48001122.json.snappy
  741. """
  742. # 计算时间范围
  743. date_range_max = date_range_max or date_range_min
  744. date_format = "/".join(
  745. ["%Y", "%m", "%d", "%H", "%M", "%S"][: date_range_min.count("/") + 1]
  746. )
  747. time_interval = [
  748. {"days": 365},
  749. {"days": 31},
  750. {"days": 1},
  751. {"hours": 1},
  752. {"minutes": 1},
  753. {"seconds": 1},
  754. ][date_range_min.count("/")]
  755. date_range = get_between_date(
  756. date_range_min, date_range_max, date_format=date_format, **time_interval
  757. )
  758. for date in date_range:
  759. file_folder_path = os.path.join(prefix, date)
  760. objs = oss_handler.list(prefix=file_folder_path)
  761. for obj in objs:
  762. filename = obj.key
  763. yield filename
  764. def is_html(url):
  765. if not url:
  766. return False
  767. try:
  768. content_type = request.urlopen(url).info().get("Content-Type", "")
  769. if "text/html" in content_type:
  770. return True
  771. else:
  772. return False
  773. except Exception as e:
  774. log.error(e)
  775. return False
  776. def is_exist(file_path):
  777. """
  778. @summary: 文件是否存在
  779. ---------
  780. @param file_path:
  781. ---------
  782. @result:
  783. """
  784. return os.path.exists(file_path)
  785. def download_file(url, file_path, *, call_func=None, proxies=None, data=None):
  786. """
  787. 下载文件,会自动创建文件存储目录
  788. Args:
  789. url: 地址
  790. file_path: 文件存储地址
  791. call_func: 下载成功的回调
  792. proxies: 代理
  793. data: 请求体
  794. Returns:
  795. """
  796. directory = os.path.dirname(file_path)
  797. mkdir(directory)
  798. # 进度条
  799. def progress_callfunc(blocknum, blocksize, totalsize):
  800. """回调函数
  801. @blocknum : 已经下载的数据块
  802. @blocksize : 数据块的大小
  803. @totalsize: 远程文件的大小
  804. """
  805. percent = 100.0 * blocknum * blocksize / totalsize
  806. if percent > 100:
  807. percent = 100
  808. # print ('进度条 %.2f%%' % percent, end = '\r')
  809. sys.stdout.write("进度条 %.2f%%" % percent + "\r")
  810. sys.stdout.flush()
  811. if url:
  812. try:
  813. if proxies:
  814. # create the object, assign it to a variable
  815. proxy = request.ProxyHandler(proxies)
  816. # construct a new opener using your proxy settings
  817. opener = request.build_opener(proxy)
  818. # install the openen on the module-level
  819. request.install_opener(opener)
  820. request.urlretrieve(url, file_path, progress_callfunc, data)
  821. if callable(call_func):
  822. call_func()
  823. return 1
  824. except Exception as e:
  825. log.error(e)
  826. return 0
  827. else:
  828. return 0
  829. def get_file_list(path, ignore=[]):
  830. templist = path.split("*")
  831. path = templist[0]
  832. file_type = templist[1] if len(templist) >= 2 else ""
  833. # 递归遍历文件
  834. def get_file_list_(path, file_type, ignore, all_file=[]):
  835. file_list = os.listdir(path)
  836. for file_name in file_list:
  837. if file_name in ignore:
  838. continue
  839. file_path = os.path.join(path, file_name)
  840. if os.path.isdir(file_path):
  841. get_file_list_(file_path, file_type, ignore, all_file)
  842. else:
  843. if not file_type or file_name.endswith(file_type):
  844. all_file.append(file_path)
  845. return all_file
  846. return get_file_list_(path, file_type, ignore) if os.path.isdir(path) else [path]
  847. def rename_file(old_name, new_name):
  848. os.rename(old_name, new_name)
  849. def del_file(path, ignore=()):
  850. files = get_file_list(path, ignore)
  851. for file in files:
  852. try:
  853. os.remove(file)
  854. except Exception as e:
  855. log.error(
  856. """
  857. 删除出错: %s
  858. Exception : %s
  859. """
  860. % (file, str(e))
  861. )
  862. finally:
  863. pass
  864. def get_file_type(file_name):
  865. """
  866. @summary: 取文件后缀名
  867. ---------
  868. @param file_name:
  869. ---------
  870. @result:
  871. """
  872. try:
  873. return os.path.splitext(file_name)[1]
  874. except Exception as e:
  875. log.exception(e)
  876. def get_file_path(file_path):
  877. """
  878. @summary: 取文件路径
  879. ---------
  880. @param file_path: /root/a.py
  881. ---------
  882. @result: /root
  883. """
  884. try:
  885. return os.path.split(file_path)[0]
  886. except Exception as e:
  887. log.exception(e)
  888. #############################################
  889. def exec_js(js_code):
  890. """
  891. @summary: 执行js代码
  892. ---------
  893. @param js_code: js代码
  894. ---------
  895. @result: 返回执行结果
  896. """
  897. return execjs.eval(js_code)
  898. def compile_js(js_func):
  899. """
  900. @summary: 编译js函数
  901. ---------
  902. @param js_func:js函数
  903. ---------
  904. @result: 返回函数对象 调用 fun('js_funName', param1,param2)
  905. """
  906. ctx = execjs.compile(js_func)
  907. return ctx.call
  908. ###############################################
  909. #############################################
  910. def date_to_timestamp(date, time_format="%Y-%m-%d %H:%M:%S"):
  911. """
  912. @summary:
  913. ---------
  914. @param date:将"2011-09-28 10:00:00"时间格式转化为时间戳
  915. @param format:时间格式
  916. ---------
  917. @result: 返回时间戳
  918. """
  919. timestamp = time.mktime(time.strptime(date, time_format))
  920. return int(timestamp)
  921. def timestamp_to_date(timestamp, time_format="%Y-%m-%d %H:%M:%S"):
  922. """
  923. @summary:
  924. ---------
  925. @param timestamp: 将时间戳转化为日期
  926. @param format: 日期格式
  927. ---------
  928. @result: 返回日期
  929. """
  930. if timestamp is None:
  931. raise ValueError("timestamp is null")
  932. date = time.localtime(timestamp)
  933. return time.strftime(time_format, date)
  934. def get_current_timestamp():
  935. return int(time.time())
  936. def get_current_date(date_format="%Y-%m-%d %H:%M:%S"):
  937. return datetime.datetime.now().strftime(date_format)
  938. # return time.strftime(date_format, time.localtime(time.time()))
  939. def get_date_number(year=None, month=None, day=None):
  940. """
  941. @summary: 获取指定日期对应的日期数
  942. 默认当前周
  943. ---------
  944. @param year: 2010
  945. @param month: 6
  946. @param day: 16
  947. ---------
  948. @result: (年号,第几周,第几天) 如 (2010, 24, 3)
  949. """
  950. if year and month and day:
  951. return datetime.date(year, month, day).isocalendar()
  952. elif not any([year, month, day]):
  953. return datetime.datetime.now().isocalendar()
  954. else:
  955. assert year, "year 不能为空"
  956. assert month, "month 不能为空"
  957. assert day, "day 不能为空"
  958. def get_between_date(
  959. begin_date, end_date=None, date_format="%Y-%m-%d", **time_interval
  960. ):
  961. """
  962. @summary: 获取一段时间间隔内的日期,默认为每一天
  963. ---------
  964. @param begin_date: 开始日期 str 如 2018-10-01
  965. @param end_date: 默认为今日
  966. @param date_format: 日期格式,应与begin_date的日期格式相对应
  967. @param time_interval: 时间间隔 默认一天 支持 days、seconds、microseconds、milliseconds、minutes、hours、weeks
  968. ---------
  969. @result: list 值为字符串
  970. """
  971. date_list = []
  972. begin_date = datetime.datetime.strptime(begin_date, date_format)
  973. end_date = (
  974. datetime.datetime.strptime(end_date, date_format)
  975. if end_date
  976. else datetime.datetime.strptime(
  977. time.strftime(date_format, time.localtime(time.time())), date_format
  978. )
  979. )
  980. time_interval = time_interval or dict(days=1)
  981. while begin_date <= end_date:
  982. date_str = begin_date.strftime(date_format)
  983. date_list.append(date_str)
  984. begin_date += datetime.timedelta(**time_interval)
  985. if end_date.strftime(date_format) not in date_list:
  986. date_list.append(end_date.strftime(date_format))
  987. return date_list
  988. def get_between_months(begin_date, end_date=None):
  989. """
  990. @summary: 获取一段时间间隔内的月份
  991. 需要满一整月
  992. ---------
  993. @param begin_date: 开始时间 如 2018-01-01
  994. @param end_date: 默认当前时间
  995. ---------
  996. @result: 列表 如 ['2018-01', '2018-02']
  997. """
  998. def add_months(dt, months):
  999. month = dt.month - 1 + months
  1000. year = dt.year + month // 12
  1001. month = month % 12 + 1
  1002. day = min(dt.day, calendar.monthrange(year, month)[1])
  1003. return dt.replace(year=year, month=month, day=day)
  1004. date_list = []
  1005. begin_date = datetime.datetime.strptime(begin_date, "%Y-%m-%d")
  1006. end_date = (
  1007. datetime.datetime.strptime(end_date, "%Y-%m-%d")
  1008. if end_date
  1009. else datetime.datetime.strptime(
  1010. time.strftime("%Y-%m-%d", time.localtime(time.time())), "%Y-%m-%d"
  1011. )
  1012. )
  1013. while begin_date <= end_date:
  1014. date_str = begin_date.strftime("%Y-%m")
  1015. date_list.append(date_str)
  1016. begin_date = add_months(begin_date, 1)
  1017. return date_list
  1018. def get_today_of_day(day_offset=0):
  1019. return str(datetime.date.today() + datetime.timedelta(days=day_offset))
  1020. def get_days_of_month(year, month):
  1021. """
  1022. 返回天数
  1023. """
  1024. return calendar.monthrange(year, month)[1]
  1025. def get_firstday_of_month(date):
  1026. """''
  1027. date format = "YYYY-MM-DD"
  1028. """
  1029. year, month, day = date.split("-")
  1030. year, month, day = int(year), int(month), int(day)
  1031. days = "01"
  1032. if int(month) < 10:
  1033. month = "0" + str(int(month))
  1034. arr = (year, month, days)
  1035. return "-".join("%s" % i for i in arr)
  1036. def get_lastday_of_month(date):
  1037. """''
  1038. get the last day of month
  1039. date format = "YYYY-MM-DD"
  1040. """
  1041. year, month, day = date.split("-")
  1042. year, month, day = int(year), int(month), int(day)
  1043. days = calendar.monthrange(year, month)[1]
  1044. month = add_zero(month)
  1045. arr = (year, month, days)
  1046. return "-".join("%s" % i for i in arr)
  1047. def get_firstday_month(month_offset=0):
  1048. """''
  1049. get the first day of month from today
  1050. month_offset is how many months
  1051. """
  1052. (y, m, d) = get_year_month_and_days(month_offset)
  1053. d = "01"
  1054. arr = (y, m, d)
  1055. return "-".join("%s" % i for i in arr)
  1056. def get_lastday_month(month_offset=0):
  1057. """''
  1058. get the last day of month from today
  1059. month_offset is how many months
  1060. """
  1061. return "-".join("%s" % i for i in get_year_month_and_days(month_offset))
  1062. def get_last_month(month_offset=0):
  1063. """''
  1064. get the last day of month from today
  1065. month_offset is how many months
  1066. """
  1067. return "-".join("%s" % i for i in get_year_month_and_days(month_offset)[:2])
  1068. def get_year_month_and_days(month_offset=0):
  1069. """
  1070. @summary:
  1071. ---------
  1072. @param month_offset: 月份偏移量
  1073. ---------
  1074. @result: ('2019', '04', '30')
  1075. """
  1076. today = datetime.datetime.now()
  1077. year, month = today.year, today.month
  1078. this_year = int(year)
  1079. this_month = int(month)
  1080. total_month = this_month + month_offset
  1081. if month_offset >= 0:
  1082. if total_month <= 12:
  1083. days = str(get_days_of_month(this_year, total_month))
  1084. total_month = add_zero(total_month)
  1085. return (year, total_month, days)
  1086. else:
  1087. i = total_month // 12
  1088. j = total_month % 12
  1089. if j == 0:
  1090. i -= 1
  1091. j = 12
  1092. this_year += i
  1093. days = str(get_days_of_month(this_year, j))
  1094. j = add_zero(j)
  1095. return (str(this_year), str(j), days)
  1096. else:
  1097. if (total_month > 0) and (total_month < 12):
  1098. days = str(get_days_of_month(this_year, total_month))
  1099. total_month = add_zero(total_month)
  1100. return (year, total_month, days)
  1101. else:
  1102. i = total_month // 12
  1103. j = total_month % 12
  1104. if j == 0:
  1105. i -= 1
  1106. j = 12
  1107. this_year += i
  1108. days = str(get_days_of_month(this_year, j))
  1109. j = add_zero(j)
  1110. return (str(this_year), str(j), days)
  1111. def add_zero(n):
  1112. return "%02d" % n
  1113. def get_month(month_offset=0):
  1114. """''
  1115. 获取当前日期前后N月的日期
  1116. if month_offset>0, 获取当前日期前N月的日期
  1117. if month_offset<0, 获取当前日期后N月的日期
  1118. date format = "YYYY-MM-DD"
  1119. """
  1120. today = datetime.datetime.now()
  1121. day = add_zero(today.day)
  1122. (y, m, d) = get_year_month_and_days(month_offset)
  1123. arr = (y, m, d)
  1124. if int(day) < int(d):
  1125. arr = (y, m, day)
  1126. return "-".join("%s" % i for i in arr)
  1127. @run_safe_model("format_date")
  1128. def format_date(date, old_format="", new_format="%Y-%m-%d %H:%M:%S"):
  1129. """
  1130. @summary: 格式化日期格式
  1131. ---------
  1132. @param date: 日期 eg:2017年4月17日 3时27分12秒
  1133. @param old_format: 原来的日期格式 如 '%Y年%m月%d日 %H时%M分%S秒'
  1134. %y 两位数的年份表示(00-99)
  1135. %Y 四位数的年份表示(000-9999)
  1136. %m 月份(01-12)
  1137. %d 月内中的一天(0-31)
  1138. %H 24小时制小时数(0-23)
  1139. %I 12小时制小时数(01-12)
  1140. %M 分钟数(00-59)
  1141. %S 秒(00-59)
  1142. @param new_format: 输出的日期格式
  1143. ---------
  1144. @result: 格式化后的日期,类型为字符串 如2017-4-17 03:27:12
  1145. """
  1146. if not date:
  1147. return ""
  1148. if not old_format:
  1149. regex = "(\d+)"
  1150. numbers = get_info(date, regex, allow_repeat=True)
  1151. formats = ["%Y", "%m", "%d", "%H", "%M", "%S"]
  1152. old_format = date
  1153. for i, number in enumerate(numbers[:6]):
  1154. if i == 0 and len(number) == 2: # 年份可能是两位 用小%y
  1155. old_format = old_format.replace(
  1156. number, formats[i].lower(), 1
  1157. ) # 替换一次 '2017年11月30日 11:49' 防止替换11月时,替换11小时
  1158. else:
  1159. old_format = old_format.replace(number, formats[i], 1) # 替换一次
  1160. try:
  1161. date_obj = datetime.datetime.strptime(date, old_format)
  1162. if "T" in date and "Z" in date:
  1163. date_obj += datetime.timedelta(hours=8)
  1164. date_str = date_obj.strftime("%Y-%m-%d %H:%M:%S")
  1165. else:
  1166. date_str = datetime.datetime.strftime(date_obj, new_format)
  1167. except Exception as e:
  1168. log.error("日期格式化出错,old_format = %s 不符合 %s 格式" % (old_format, date))
  1169. date_str = date
  1170. return date_str
  1171. def transform_lower_num(data_str: str):
  1172. num_map = {
  1173. "一": "1",
  1174. "二": "2",
  1175. "三": "3",
  1176. "四": "4",
  1177. "五": "5",
  1178. "六": "6",
  1179. "七": "7",
  1180. "八": "8",
  1181. "九": "9",
  1182. "十": "0",
  1183. }
  1184. pattern = f'[{"|".join(num_map.keys())}|零]'
  1185. res = re.search(pattern, data_str)
  1186. if not res:
  1187. # 如果字符串中没有包含中文数字 不做处理 直接返回
  1188. return data_str
  1189. data_str = data_str.replace("0", "零")
  1190. for n in num_map:
  1191. data_str = data_str.replace(n, num_map[n])
  1192. re_data_str = re.findall("\d+", data_str)
  1193. for i in re_data_str:
  1194. if len(i) == 3:
  1195. new_i = i.replace("0", "")
  1196. data_str = data_str.replace(i, new_i, 1)
  1197. elif len(i) == 4:
  1198. new_i = i.replace("10", "")
  1199. data_str = data_str.replace(i, new_i, 1)
  1200. elif len(i) == 2 and int(i) < 10:
  1201. new_i = int(i) + 10
  1202. data_str = data_str.replace(i, str(new_i), 1)
  1203. elif len(i) == 1 and int(i) == 0:
  1204. new_i = int(i) + 10
  1205. data_str = data_str.replace(i, str(new_i), 1)
  1206. return data_str.replace("零", "0")
  1207. @run_safe_model("format_time")
  1208. def format_time(release_time, date_format="%Y-%m-%d %H:%M:%S"):
  1209. """
  1210. >>> format_time("2个月前")
  1211. '2021-08-15 16:24:21'
  1212. >>> format_time("2月前")
  1213. '2021-08-15 16:24:36'
  1214. """
  1215. release_time = transform_lower_num(release_time)
  1216. release_time = release_time.replace("日", "天").replace("/", "-")
  1217. if "年前" in release_time:
  1218. years = re.compile("(\d+)\s*年前").findall(release_time)
  1219. years_ago = datetime.datetime.now() - datetime.timedelta(
  1220. days=int(years[0]) * 365
  1221. )
  1222. release_time = years_ago.strftime("%Y-%m-%d %H:%M:%S")
  1223. elif "月前" in release_time:
  1224. months = re.compile("(\d+)[\s个]*月前").findall(release_time)
  1225. months_ago = datetime.datetime.now() - datetime.timedelta(
  1226. days=int(months[0]) * 30
  1227. )
  1228. release_time = months_ago.strftime("%Y-%m-%d %H:%M:%S")
  1229. elif "周前" in release_time:
  1230. weeks = re.compile("(\d+)\s*周前").findall(release_time)
  1231. weeks_ago = datetime.datetime.now() - datetime.timedelta(days=int(weeks[0]) * 7)
  1232. release_time = weeks_ago.strftime("%Y-%m-%d %H:%M:%S")
  1233. elif "天前" in release_time:
  1234. ndays = re.compile("(\d+)\s*天前").findall(release_time)
  1235. days_ago = datetime.datetime.now() - datetime.timedelta(days=int(ndays[0]))
  1236. release_time = days_ago.strftime("%Y-%m-%d %H:%M:%S")
  1237. elif "小时前" in release_time:
  1238. nhours = re.compile("(\d+)\s*小时前").findall(release_time)
  1239. hours_ago = datetime.datetime.now() - datetime.timedelta(hours=int(nhours[0]))
  1240. release_time = hours_ago.strftime("%Y-%m-%d %H:%M:%S")
  1241. elif "分钟前" in release_time:
  1242. nminutes = re.compile("(\d+)\s*分钟前").findall(release_time)
  1243. minutes_ago = datetime.datetime.now() - datetime.timedelta(
  1244. minutes=int(nminutes[0])
  1245. )
  1246. release_time = minutes_ago.strftime("%Y-%m-%d %H:%M:%S")
  1247. elif "前天" in release_time:
  1248. today = datetime.date.today()
  1249. yesterday = today - datetime.timedelta(days=2)
  1250. release_time = release_time.replace("前天", str(yesterday))
  1251. elif "昨天" in release_time:
  1252. today = datetime.date.today()
  1253. yesterday = today - datetime.timedelta(days=1)
  1254. release_time = release_time.replace("昨天", str(yesterday))
  1255. elif "今天" in release_time:
  1256. release_time = release_time.replace("今天", get_current_date("%Y-%m-%d"))
  1257. elif "刚刚" in release_time:
  1258. release_time = get_current_date()
  1259. elif re.search("^\d\d:\d\d", release_time):
  1260. release_time = get_current_date("%Y-%m-%d") + " " + release_time
  1261. elif not re.compile("\d{4}").findall(release_time):
  1262. month = re.compile("\d{1,2}").findall(release_time)
  1263. if month and int(month[0]) <= int(get_current_date("%m")):
  1264. release_time = get_current_date("%Y") + "-" + release_time
  1265. else:
  1266. release_time = str(int(get_current_date("%Y")) - 1) + "-" + release_time
  1267. # 把日和小时粘在一起的拆开
  1268. template = re.compile("(\d{4}-\d{1,2}-\d{2})(\d{1,2})")
  1269. release_time = re.sub(template, r"\1 \2", release_time)
  1270. release_time = format_date(release_time, new_format=date_format)
  1271. return release_time
  1272. def to_date(date_str, date_format="%Y-%m-%d %H:%M:%S"):
  1273. return datetime.datetime.strptime(date_str, date_format)
  1274. def get_before_date(
  1275. current_date,
  1276. days,
  1277. current_date_format="%Y-%m-%d %H:%M:%S",
  1278. return_date_format="%Y-%m-%d %H:%M:%S",
  1279. ):
  1280. """
  1281. @summary: 获取之前时间
  1282. ---------
  1283. @param current_date: 当前时间 str类型
  1284. @param days: 时间间隔 -1 表示前一天 1 表示后一天
  1285. @param days: 返回的时间格式
  1286. ---------
  1287. @result: 字符串
  1288. """
  1289. current_date = to_date(current_date, current_date_format)
  1290. date_obj = current_date + datetime.timedelta(days=days)
  1291. return datetime.datetime.strftime(date_obj, return_date_format)
  1292. def get_utcnow():
  1293. """utc时间"""
  1294. return datetime.datetime.utcnow()
  1295. def delay_time(sleep_time=60):
  1296. """
  1297. @summary: 睡眠 默认1分钟
  1298. ---------
  1299. @param sleep_time: 以秒为单位
  1300. ---------
  1301. @result:
  1302. """
  1303. time.sleep(sleep_time)
  1304. def format_seconds(seconds):
  1305. """
  1306. @summary: 将秒转为时分秒
  1307. ---------
  1308. @param seconds:
  1309. ---------
  1310. @result: 2天3小时2分49秒
  1311. """
  1312. seconds = int(seconds + 0.5) # 向上取整
  1313. m, s = divmod(seconds, 60)
  1314. h, m = divmod(m, 60)
  1315. d, h = divmod(h, 24)
  1316. times = ""
  1317. if d:
  1318. times += "{}天".format(d)
  1319. if h:
  1320. times += "{}小时".format(h)
  1321. if m:
  1322. times += "{}分".format(m)
  1323. if s:
  1324. times += "{}秒".format(s)
  1325. return times
  1326. ################################################
  1327. def get_md5(*args):
  1328. """
  1329. @summary: 获取唯一的32位md5
  1330. ---------
  1331. @param *args: 参与联合去重的值
  1332. ---------
  1333. @result: 7c8684bcbdfcea6697650aa53d7b1405
  1334. """
  1335. m = hashlib.md5()
  1336. for arg in args:
  1337. m.update(str(arg).encode())
  1338. return m.hexdigest()
  1339. def get_sha1(*args):
  1340. """
  1341. @summary: 获取唯一的40位值, 用于获取唯一的id
  1342. ---------
  1343. @param *args: 参与联合去重的值
  1344. ---------
  1345. @result: ba4868b3f277c8e387b55d9e3d0be7c045cdd89e
  1346. """
  1347. sha1 = hashlib.sha1()
  1348. for arg in args:
  1349. sha1.update(str(arg).encode())
  1350. return sha1.hexdigest() # 40位
  1351. def get_base64(secret, message):
  1352. """
  1353. @summary: 数字证书签名算法是:"HMAC-SHA256"
  1354. 参考:https://www.jokecamp.com/blog/examples-of-creating-base64-hashes-using-hmac-sha256-in-different-languages/
  1355. ---------
  1356. @param secret: 秘钥
  1357. @param message: 消息
  1358. ---------
  1359. @result: 签名输出类型是:"base64"
  1360. """
  1361. import hashlib
  1362. import hmac
  1363. import base64
  1364. message = bytes(message, "utf-8")
  1365. secret = bytes(secret, "utf-8")
  1366. signature = base64.b64encode(
  1367. hmac.new(secret, message, digestmod=hashlib.sha256).digest()
  1368. ).decode("utf8")
  1369. return signature
  1370. def get_uuid(key1="", key2=""):
  1371. """
  1372. @summary: 计算uuid值
  1373. 可用于将两个字符串组成唯一的值。如可将域名和新闻标题组成uuid,形成联合索引
  1374. ---------
  1375. @param key1:str
  1376. @param key2:str
  1377. ---------
  1378. @result:
  1379. """
  1380. uuid_object = ""
  1381. if not key1 and not key2:
  1382. uuid_object = uuid.uuid1()
  1383. else:
  1384. hash = md5(bytes(key1, "utf-8") + bytes(key2, "utf-8")).digest()
  1385. uuid_object = uuid.UUID(bytes=hash[:16], version=3)
  1386. return str(uuid_object)
  1387. def get_hash(text):
  1388. return hash(text)
  1389. ##################################################
  1390. def cut_string(text, length):
  1391. """
  1392. @summary: 将文本按指定长度拆分
  1393. ---------
  1394. @param text: 文本
  1395. @param length: 拆分长度
  1396. ---------
  1397. @result: 返回按指定长度拆分后形成的list
  1398. """
  1399. text_list = re.findall(".{%d}" % length, text, re.S)
  1400. leave_text = text[len(text_list) * length :]
  1401. if leave_text:
  1402. text_list.append(leave_text)
  1403. return text_list
  1404. def get_random_string(length=1):
  1405. random_string = "".join(random.sample(string.ascii_letters + string.digits, length))
  1406. return random_string
  1407. def get_random_password(length=8, special_characters=""):
  1408. """
  1409. @summary: 创建随机密码 默认长度为8,包含大写字母、小写字母、数字
  1410. ---------
  1411. @param length: 密码长度 默认8
  1412. @param special_characters: 特殊字符
  1413. ---------
  1414. @result: 指定长度的密码
  1415. """
  1416. while True:
  1417. random_password = "".join(
  1418. random.sample(
  1419. string.ascii_letters + string.digits + special_characters, length
  1420. )
  1421. )
  1422. if (
  1423. re.search("[0-9]", random_password)
  1424. and re.search("[A-Z]", random_password)
  1425. and re.search("[a-z]", random_password)
  1426. ):
  1427. if not special_characters:
  1428. break
  1429. elif set(random_password).intersection(special_characters):
  1430. break
  1431. return random_password
  1432. def get_random_email(length=None, email_types: list = None, special_characters=""):
  1433. """
  1434. 随机生成邮箱
  1435. :param length: 邮箱长度
  1436. :param email_types: 邮箱类型
  1437. :param special_characters: 特殊字符
  1438. :return:
  1439. """
  1440. if not length:
  1441. length = random.randint(4, 12)
  1442. if not email_types:
  1443. email_types = [
  1444. "qq.com",
  1445. "163.com",
  1446. "gmail.com",
  1447. "yahoo.com",
  1448. "hotmail.com",
  1449. "yeah.net",
  1450. "126.com",
  1451. "139.com",
  1452. "sohu.com",
  1453. ]
  1454. email_body = get_random_password(length, special_characters)
  1455. email_type = random.choice(email_types)
  1456. email = email_body + "@" + email_type
  1457. return email
  1458. #################################
  1459. def dumps_obj(obj):
  1460. return pickle.dumps(obj)
  1461. def loads_obj(obj_str):
  1462. return pickle.loads(obj_str)
  1463. def get_method(obj, name):
  1464. name = str(name)
  1465. try:
  1466. return getattr(obj, name)
  1467. except AttributeError:
  1468. log.error("Method %r not found in: %s" % (name, obj))
  1469. return None
  1470. def witch_workspace(project_path):
  1471. """
  1472. @summary:
  1473. ---------
  1474. @param project_path:
  1475. ---------
  1476. @result:
  1477. """
  1478. os.chdir(project_path) # 切换工作路经
  1479. ############### 数据库相关 #######################
  1480. def format_sql_value(value):
  1481. if isinstance(value, str):
  1482. value = value.strip()
  1483. elif isinstance(value, (list, dict)):
  1484. value = dumps_json(value, indent=None)
  1485. elif isinstance(value, (datetime.date, datetime.time)):
  1486. value = str(value)
  1487. elif isinstance(value, bool):
  1488. value = int(value)
  1489. return value
  1490. def list2str(datas):
  1491. """
  1492. 列表转字符串
  1493. :param datas: [1, 2]
  1494. :return: (1, 2)
  1495. """
  1496. data_str = str(tuple(datas))
  1497. data_str = re.sub(",\)$", ")", data_str)
  1498. return data_str
  1499. def make_insert_sql(
  1500. table, data, auto_update=False, update_columns=(), insert_ignore=False
  1501. ):
  1502. """
  1503. @summary: 适用于mysql, oracle数据库时间需要to_date 处理(TODO)
  1504. ---------
  1505. @param table:
  1506. @param data: 表数据 json格式
  1507. @param auto_update: 使用的是replace into, 为完全覆盖已存在的数据
  1508. @param update_columns: 需要更新的列 默认全部,当指定值时,auto_update设置无效,当duplicate key冲突时更新指定的列
  1509. @param insert_ignore: 数据存在忽略
  1510. ---------
  1511. @result:
  1512. """
  1513. keys = ["`{}`".format(key) for key in data.keys()]
  1514. keys = list2str(keys).replace("'", "")
  1515. values = [format_sql_value(value) for value in data.values()]
  1516. values = list2str(values)
  1517. if update_columns:
  1518. if not isinstance(update_columns, (tuple, list)):
  1519. update_columns = [update_columns]
  1520. update_columns_ = ", ".join(
  1521. ["{key}=values({key})".format(key=key) for key in update_columns]
  1522. )
  1523. sql = (
  1524. "insert%s into `{table}` {keys} values {values} on duplicate key update %s"
  1525. % (" ignore" if insert_ignore else "", update_columns_)
  1526. )
  1527. elif auto_update:
  1528. sql = "replace into `{table}` {keys} values {values}"
  1529. else:
  1530. sql = "insert%s into `{table}` {keys} values {values}" % (
  1531. " ignore" if insert_ignore else ""
  1532. )
  1533. sql = sql.format(table=table, keys=keys, values=values).replace("None", "null")
  1534. return sql
  1535. def make_update_sql(table, data, condition):
  1536. """
  1537. @summary: 适用于mysql, oracle数据库时间需要to_date 处理(TODO)
  1538. ---------
  1539. @param table:
  1540. @param data: 表数据 json格式
  1541. @param condition: where 条件
  1542. ---------
  1543. @result:
  1544. """
  1545. key_values = []
  1546. for key, value in data.items():
  1547. value = format_sql_value(value)
  1548. if isinstance(value, str):
  1549. key_values.append("`{}`={}".format(key, repr(value)))
  1550. elif value is None:
  1551. key_values.append("`{}`={}".format(key, "null"))
  1552. else:
  1553. key_values.append("`{}`={}".format(key, value))
  1554. key_values = ", ".join(key_values)
  1555. sql = "update `{table}` set {key_values} where {condition}"
  1556. sql = sql.format(table=table, key_values=key_values, condition=condition)
  1557. return sql
  1558. def make_batch_sql(
  1559. table, datas, auto_update=False, update_columns=(), update_columns_value=()
  1560. ):
  1561. """
  1562. @summary: 生产批量的sql
  1563. ---------
  1564. @param table:
  1565. @param datas: 表数据 [{...}]
  1566. @param auto_update: 使用的是replace into, 为完全覆盖已存在的数据
  1567. @param update_columns: 需要更新的列 默认全部,当指定值时,auto_update设置无效,当duplicate key冲突时更新指定的列
  1568. @param update_columns_value: 需要更新的列的值 默认为datas里边对应的值, 注意 如果值为字符串类型 需要主动加单引号, 如 update_columns_value=("'test'",)
  1569. ---------
  1570. @result:
  1571. """
  1572. if not datas:
  1573. return
  1574. keys = list(datas[0].keys())
  1575. values_placeholder = ["%s"] * len(keys)
  1576. values = []
  1577. for data in datas:
  1578. value = []
  1579. for key in keys:
  1580. current_data = data.get(key)
  1581. current_data = format_sql_value(current_data)
  1582. value.append(current_data)
  1583. values.append(value)
  1584. keys = ["`{}`".format(key) for key in keys]
  1585. keys = list2str(keys).replace("'", "")
  1586. values_placeholder = list2str(values_placeholder).replace("'", "")
  1587. if update_columns:
  1588. if not isinstance(update_columns, (tuple, list)):
  1589. update_columns = [update_columns]
  1590. if update_columns_value:
  1591. update_columns_ = ", ".join(
  1592. [
  1593. "`{key}`={value}".format(key=key, value=value)
  1594. for key, value in zip(update_columns, update_columns_value)
  1595. ]
  1596. )
  1597. else:
  1598. update_columns_ = ", ".join(
  1599. ["`{key}`=values(`{key}`)".format(key=key) for key in update_columns]
  1600. )
  1601. sql = "insert into `{table}` {keys} values {values_placeholder} on duplicate key update {update_columns}".format(
  1602. table=table,
  1603. keys=keys,
  1604. values_placeholder=values_placeholder,
  1605. update_columns=update_columns_,
  1606. )
  1607. elif auto_update:
  1608. sql = "replace into `{table}` {keys} values {values_placeholder}".format(
  1609. table=table, keys=keys, values_placeholder=values_placeholder
  1610. )
  1611. else:
  1612. sql = "insert ignore into `{table}` {keys} values {values_placeholder}".format(
  1613. table=table, keys=keys, values_placeholder=values_placeholder
  1614. )
  1615. return sql, values
  1616. ############### json相关 #######################
  1617. def key2underline(key: str, strict=True):
  1618. """
  1619. >>> key2underline("HelloWord")
  1620. 'hello_word'
  1621. >>> key2underline("SHData", strict=True)
  1622. 's_h_data'
  1623. >>> key2underline("SHData", strict=False)
  1624. 'sh_data'
  1625. >>> key2underline("SHDataHi", strict=False)
  1626. 'sh_data_hi'
  1627. >>> key2underline("SHDataHi", strict=True)
  1628. 's_h_data_hi'
  1629. >>> key2underline("dataHi", strict=True)
  1630. 'data_hi'
  1631. """
  1632. regex = "[A-Z]*" if not strict else "[A-Z]"
  1633. capitals = re.findall(regex, key)
  1634. if capitals:
  1635. for capital in capitals:
  1636. if not capital:
  1637. continue
  1638. if key.startswith(capital):
  1639. if len(capital) > 1:
  1640. key = key.replace(
  1641. capital, capital[:-1].lower() + "_" + capital[-1].lower(), 1
  1642. )
  1643. else:
  1644. key = key.replace(capital, capital.lower(), 1)
  1645. else:
  1646. if len(capital) > 1:
  1647. key = key.replace(capital, "_" + capital.lower() + "_", 1)
  1648. else:
  1649. key = key.replace(capital, "_" + capital.lower(), 1)
  1650. return key.strip("_")
  1651. def key2hump(key):
  1652. """
  1653. 下划线试变成首字母大写
  1654. """
  1655. return key.title().replace("_", "")
  1656. def format_json_key(json_data):
  1657. json_data_correct = {}
  1658. for key, value in json_data.items():
  1659. key = key2underline(key)
  1660. json_data_correct[key] = value
  1661. return json_data_correct
  1662. def quick_to_json(text):
  1663. """
  1664. @summary: 可快速将浏览器上的header转为json格式
  1665. ---------
  1666. @param text:
  1667. ---------
  1668. @result:
  1669. """
  1670. contents = text.split("\n")
  1671. json = {}
  1672. for content in contents:
  1673. if content == "\n":
  1674. continue
  1675. content = content.strip()
  1676. regex = ["(:?.*?):(.*)", "(.*?):? +(.*)", "([^:]*)"]
  1677. result = get_info(content, regex)
  1678. result = result[0] if isinstance(result[0], tuple) else result
  1679. try:
  1680. json[result[0]] = eval(result[1].strip())
  1681. except:
  1682. json[result[0]] = result[1].strip()
  1683. return json
  1684. ##############################
  1685. def print_pretty(object):
  1686. pprint(object)
  1687. def print_params2json(url):
  1688. params_json = {}
  1689. params = url.split("?")[-1].split("&")
  1690. for param in params:
  1691. key_value = param.split("=", 1)
  1692. params_json[key_value[0]] = key_value[1]
  1693. print(dumps_json(params_json))
  1694. def print_cookie2json(cookie_str_or_list):
  1695. if isinstance(cookie_str_or_list, str):
  1696. cookie_json = {}
  1697. cookies = cookie_str_or_list.split("; ")
  1698. for cookie in cookies:
  1699. name, value = cookie.split("=")
  1700. cookie_json[name] = value
  1701. else:
  1702. cookie_json = get_cookies_from_selenium_cookie(cookie_str_or_list)
  1703. print(dumps_json(cookie_json))
  1704. ###############################
  1705. def flatten(x):
  1706. """flatten(sequence) -> list
  1707. Returns a single, flat list which contains all elements retrieved
  1708. from the sequence and all recursively contained sub-sequences
  1709. (iterables).
  1710. Examples:
  1711. >>> [1, 2, [3,4], (5,6)]
  1712. [1, 2, [3, 4], (5, 6)]
  1713. >>> flatten([[[1,2,3], (42,None)], [4,5], [6], 7, (8,9,10)])
  1714. [1, 2, 3, 42, None, 4, 5, 6, 7, 8, 9, 10]
  1715. >>> flatten(["foo", "bar"])
  1716. ['foo', 'bar']
  1717. >>> flatten(["foo", ["baz", 42], "bar"])
  1718. ['foo', 'baz', 42, 'bar']
  1719. """
  1720. return list(iflatten(x))
  1721. def iflatten(x):
  1722. """iflatten(sequence) -> iterator
  1723. Similar to ``.flatten()``, but returns iterator instead"""
  1724. for el in x:
  1725. if _is_listlike(el):
  1726. for el_ in flatten(el):
  1727. yield el_
  1728. else:
  1729. yield el
  1730. def _is_listlike(x):
  1731. """
  1732. >>> _is_listlike("foo")
  1733. False
  1734. >>> _is_listlike(5)
  1735. False
  1736. >>> _is_listlike(b"foo")
  1737. False
  1738. >>> _is_listlike([b"foo"])
  1739. True
  1740. >>> _is_listlike((b"foo",))
  1741. True
  1742. >>> _is_listlike({})
  1743. True
  1744. >>> _is_listlike(set())
  1745. True
  1746. >>> _is_listlike((x for x in range(3)))
  1747. True
  1748. >>> _is_listlike(six.moves.xrange(5))
  1749. True
  1750. """
  1751. return hasattr(x, "__iter__") and not isinstance(x, (six.text_type, bytes))
  1752. ###################
  1753. def re_def_supper_class(obj, supper_class):
  1754. """
  1755. 重新定义父类
  1756. @param obj: 类 如 class A: 则obj为A 或者 A的实例 a.__class__
  1757. @param supper_class: 父类
  1758. @return:
  1759. """
  1760. obj.__bases__ = (supper_class,)
  1761. ###################
  1762. freq_limit_record = {}
  1763. def reach_freq_limit(rate_limit, *key):
  1764. """
  1765. 频率限制
  1766. :param rate_limit: 限制时间 单位秒
  1767. :param key: 频率限制的key
  1768. :return: True / False
  1769. """
  1770. if rate_limit == 0:
  1771. return False
  1772. msg_md5 = get_md5(*key)
  1773. key = "rate_limit:{}".format(msg_md5)
  1774. try:
  1775. if get_redisdb().get(key):
  1776. return True
  1777. get_redisdb().set(key, time.time(), ex=rate_limit)
  1778. except redis.exceptions.ConnectionError as e:
  1779. # 使用内存做频率限制
  1780. global freq_limit_record
  1781. if key not in freq_limit_record:
  1782. freq_limit_record[key] = time.time()
  1783. return False
  1784. if time.time() - freq_limit_record.get(key) < rate_limit:
  1785. return True
  1786. else:
  1787. freq_limit_record[key] = time.time()
  1788. return False
  1789. def wechat_warning(
  1790. message,
  1791. message_prefix=None,
  1792. rate_limit=None,
  1793. url=None,
  1794. user_phone=None,
  1795. all_users: bool = None,
  1796. ):
  1797. """企业微信报警"""
  1798. # 为了加载最新的配置
  1799. rate_limit = rate_limit if rate_limit is not None else setting.WARNING_INTERVAL
  1800. url = url or setting.WECHAT_WARNING_URL
  1801. user_phone = user_phone or setting.WECHAT_WARNING_PHONE
  1802. all_users = all_users if all_users is not None else setting.WECHAT_WARNING_ALL
  1803. if isinstance(user_phone, str):
  1804. user_phone = [user_phone] if user_phone else []
  1805. if all_users is True or not user_phone:
  1806. user_phone = ["@all"]
  1807. if not all([url, message]):
  1808. return
  1809. if reach_freq_limit(rate_limit, url, user_phone, message_prefix or message):
  1810. log.info("报警时间间隔过短,此次报警忽略。 内容 {}".format(message))
  1811. return
  1812. data = {
  1813. "msgtype": "text",
  1814. "text": {"content": message, "mentioned_mobile_list": user_phone},
  1815. }
  1816. headers = {"Content-Type": "application/json"}
  1817. try:
  1818. response = requests.post(
  1819. url, headers=headers, data=json.dumps(data).encode("utf8")
  1820. )
  1821. result = response.json()
  1822. response.close()
  1823. if result.get("errcode") == 0:
  1824. return True
  1825. else:
  1826. raise Exception(result.get("errmsg"))
  1827. except Exception as e:
  1828. log.error("报警发送失败。 报警内容 {}, error: {}".format(message, e))
  1829. return False
  1830. ###################
  1831. def make_item(cls, data: dict):
  1832. """提供Item类与原数据,快速构建Item实例
  1833. :param cls: Item类
  1834. :param data: 字典格式的数据
  1835. """
  1836. item = cls()
  1837. for key, val in data.items():
  1838. setattr(item, key, val)
  1839. return item
  1840. ###################
  1841. def aio_wrap(loop=None, executor=None):
  1842. """
  1843. wrap a normal sync version of a function to an async version
  1844. """
  1845. outer_loop = loop
  1846. outer_executor = executor
  1847. def wrap(fn):
  1848. @wraps(fn)
  1849. async def run(*args, loop=None, executor=None, **kwargs):
  1850. if loop is None:
  1851. if outer_loop is None:
  1852. loop = asyncio.get_event_loop()
  1853. else:
  1854. loop = outer_loop
  1855. if executor is None:
  1856. executor = outer_executor
  1857. pfunc = partial(fn, *args, **kwargs)
  1858. return await loop.run_in_executor(executor, pfunc)
  1859. return run
  1860. return wrap
  1861. ######### number ##########
  1862. def ensure_int(n):
  1863. """
  1864. >>> ensure_int(None)
  1865. 0
  1866. >>> ensure_int(False)
  1867. 0
  1868. >>> ensure_int(12)
  1869. 12
  1870. >>> ensure_int("72")
  1871. 72
  1872. >>> ensure_int('')
  1873. 0
  1874. >>> ensure_int('1')
  1875. 1
  1876. """
  1877. if not n:
  1878. return 0
  1879. return int(n)
  1880. def ensure_float(n):
  1881. """
  1882. >>> ensure_float(None)
  1883. 0.0
  1884. >>> ensure_float(False)
  1885. 0.0
  1886. >>> ensure_float(12)
  1887. 12.0
  1888. >>> ensure_float("72")
  1889. 72.0
  1890. """
  1891. if not n:
  1892. return 0.0
  1893. return float(n)
  1894. def ensure_int64(n):
  1895. """
  1896. >>> ensure_int64(None)
  1897. 0
  1898. >>> ensure_float(False)
  1899. 0
  1900. >>> ensure_float(12)
  1901. 12
  1902. >>> ensure_float("72")
  1903. 72
  1904. """
  1905. if not n:
  1906. return bson.int64.Int64(0)
  1907. return bson.int64.Int64(n)
  1908. def import_cls(cls_info):
  1909. module, class_name = cls_info.rsplit(".", 1)
  1910. cls = importlib.import_module(module).__getattribute__(class_name)
  1911. return cls