tools.py 62 KB

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