common_functions.py 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  1. # coding:utf-8
  2. import calendar
  3. import hashlib
  4. import datetime,time
  5. import re
  6. import M2Crypto
  7. from PIL import Image,ImageDraw
  8. import requests
  9. from pypinyin import pinyin,lazy_pinyin
  10. import common.error_info as ce
  11. def get_month_dates(month="202008"):
  12. """
  13. """
  14. dates = []
  15. now = datetime.datetime.now().date()
  16. now_date_str = now.strftime("%Y%m")
  17. day_end = calendar.monthrange(int(now_date_str[0:4]),int(now_date_str[4:6]))[1]
  18. for i in range(1,day_end):
  19. dates.append(now_date_str+"%02d" % i)
  20. return dates
  21. def check_password(new,old):
  22. """
  23. """
  24. np = hashlib.md5(new).hexdigest().upper()
  25. return np==old
  26. def make_password(pwd,isdefault=None):
  27. """
  28. """
  29. return hashlib.md5(pwd).hexdigest().upper()
  30. def addText(orgpath,string,path):
  31. img = Image.open(orgpath)
  32. size = img.size
  33. width = size[0] - 20
  34. high = size[1] - 20
  35. lenth = len(string)*3
  36. draw = ImageDraw.Draw(img)
  37. draw.text((width-lenth,high),string,fill='black')
  38. img.save(path)
  39. def list_split(items, n):
  40. return [items[i:i+n] for i in range(0, len(items), n)]
  41. def str_to_datetime(tm,format="%Y-%m-%d %H:%M:%S"):
  42. """
  43. """
  44. datetimestr = datetime.datetime.strptime(tm,format)
  45. return datetimestr
  46. def datetime_to_str(tm,format="%Y-%m-%d %H:%M:%S"):
  47. """
  48. """
  49. datetimestr = datetime.datetime.strftime(tm,format)
  50. return datetimestr
  51. def get_now_str(format="%Y-%m-%d %H:%M:%S"):
  52. """获取当前时间并转化成制定格式字符串
  53. """
  54. now = datetime.datetime.now()
  55. return datetime.datetime.strftime(now,format)
  56. def check_pub_key(pub_key):
  57. """检查证书有效性
  58. """
  59. try:
  60. pub_key = M2Crypto.X509.load_cert_string(str(pub_key))
  61. return 1
  62. except:
  63. return 0
  64. def check_priv_key(priv_key):
  65. """检查私钥有效性
  66. """
  67. try:
  68. M2Crypto.RSA.load_key_string(str(priv_key))
  69. return 1
  70. except:
  71. return 0
  72. def check_pub_priv_key(pub_key, priv_key):
  73. if len(pub_key) == 0 and len(priv_key) == 0:
  74. return 0
  75. msg = "hello"
  76. try:
  77. cert = M2Crypto.X509.load_cert_string(str(pub_key))
  78. key = M2Crypto.RSA.load_key_string(str(priv_key))
  79. encrypted = cert.get_pubkey().get_rsa().public_encrypt(msg, M2Crypto.RSA.pkcs1_padding)
  80. decrypted = key.private_decrypt(encrypted, M2Crypto.RSA.pkcs1_padding)
  81. if msg != decrypted:
  82. return 0
  83. return errno.INVALID_CERT
  84. except:
  85. return 0
  86. return errno.INVALID_CERT
  87. return 1
  88. def get_day_range(yesterday):
  89. """
  90. @attention: 获取昨天数据
  91. """
  92. sd = ed = yesterday.strftime("%Y%m%d")
  93. return sd,ed
  94. def get_week_range(yesterday):
  95. """
  96. @attention: 获取最近一周数据
  97. """
  98. ed = yesterday.strftime("%Y%m%d")
  99. sd = yesterday - datetime.timedelta(days=6)
  100. sd = sd.strftime("%Y%m%d")
  101. return sd,ed
  102. def get_month_range(yesterday,today_month,days):
  103. """
  104. @attention: 获取最近一个月数据
  105. """
  106. ed = yesterday.strftime("%Y%m%d")
  107. temp = datetime.datetime.strptime(today_month,"%Y%m")-datetime.timedelta(days=1)
  108. last_month = temp.strftime("%Y%m")
  109. sd = "%s%s"%(last_month,str(days).rjust(2,"0"))
  110. return sd,ed
  111. def list_group_by(olist,key,sort=None):
  112. """
  113. """
  114. nlist = []
  115. tmp = {}
  116. for ol in olist:
  117. kkey = ol[key]
  118. if not tmp.has_key(kkey):
  119. tmp[kkey] = [0]
  120. else:
  121. tmp[kkey].append(ol)
  122. for k,v in tmp.items():
  123. dct = {key:k,"data":v,"count":len(v)}
  124. nlist.append(dct)
  125. if sort:
  126. nlist = sorted(nlist,key=lambda x:x["count"])
  127. return nlist
  128. def get_need_params(*need_parms,**kwargs):
  129. """
  130. """
  131. newdct = {}
  132. need_parms = set(need_parms).intersection(set(kwargs.keys()))
  133. for k in need_parms:
  134. newdct[k] = kwargs.get(k)
  135. return newdct
  136. def check_params(*need_parms,**kwargs):
  137. if not set(need_parms).issubset(set(kwargs.keys())):
  138. miss = list(set(need_parms)-set(kwargs.keys()))
  139. miss = ",".join(miss)
  140. return "缺少参数:{}".format(miss)
  141. for nk in need_parms:
  142. if not kwargs.get(nk):
  143. return "缺少参数值:{}!".format(nk)
  144. return None
  145. def get_page_list(list,page,page_size=20):
  146. """
  147. """
  148. page = int(page)
  149. page_size = int(page_size)
  150. if page and page_size:
  151. start = (page - 1)*page_size
  152. end = page * page_size
  153. count = len(list)
  154. list = list[start:end]
  155. else:
  156. count = len(list)
  157. return count,list
  158. def get_ip(request):
  159. if request.META.has_key('HTTP_X_REAL_IP'):
  160. ip = request.META['HTTP_X_REAL_IP']
  161. elif request.META.has_key('HTTP_X_FORWARDED_FOR'):
  162. ip = request.META['HTTP_X_FORWARDED_FOR']
  163. else:
  164. ip = request.META['REMOTE_ADDR']
  165. return ip
  166. def get_city_from_ip(ip):
  167. url = "https://sp1.baidu.com/8aQDcjqpAAV3otqbppnN2DJv/api.php?query=%s&co=&resource_id=5809&t=%s" \
  168. % (ip,str(int(time.time()*1000)))
  169. try:
  170. result = requests.get(url).json()
  171. location = result.get("data")[0].get("location")
  172. location = location.split("省")[-1].split("市")[0]
  173. except Exception as e:
  174. print(e)
  175. location = None
  176. return location
  177. def get_name_pinyin(name):
  178. pinyin = lazy_pinyin(name)
  179. if len(pinyin)>1:
  180. return "".join([x[0] for x in pinyin]).upper()
  181. else:
  182. return pinyin[0].upper()
  183. def calc_age(birthday):
  184. """
  185. """
  186. now = datetime.datetime.now()
  187. birdate = str_to_datetime(birthday,"%Y-%m-%d")
  188. years = (now - birdate).days/365
  189. return years
  190. def check_sign(func):
  191. apikey = "9edf5d26-6907-4534-8907-e4c3f8ed53c8"
  192. def __wrapper(*args,**kwargs):
  193. print(kwargs)
  194. timestamp = kwargs.get("timestamp")
  195. #apikey = kwargs.get("apikey")
  196. sign = kwargs.get("sign")
  197. doctor_id = kwargs.get("doctor_id")
  198. hospital_id = kwargs.get("hospital_id")
  199. patient_id = kwargs.get("patient_id")
  200. if abs(time.time() - int(timestamp)) > 60*10:
  201. raise ce.TipException(u"请求超时!")
  202. sign_str = "apikey=%s;timestamp=%s" % (apikey,timestamp)
  203. if doctor_id:
  204. sign_str = "apikey=%s;doctor_id=%s;timestamp=%s" % (apikey,doctor_id,timestamp)
  205. if doctor_id and hospital_id:
  206. sign_str = "apikey=%s;doctor_id=%s;hospital_id=%s;timestamp=%s" % (apikey,doctor_id,hospital_id,timestamp)
  207. if doctor_id and hospital_id and patient_id:
  208. sign_str = "apikey=%s;doctor_id=%s;hospital_id=%s;patient_id=%s;timestamp=%s" % (apikey,doctor_id,hospital_id,patient_id,timestamp)
  209. req_sign = make_password(sign_str)
  210. print(sign_str)
  211. print(req_sign)
  212. if not (sign == req_sign):
  213. raise ce.TipException(u"签名错误!")
  214. res = func(*args,**kwargs)
  215. return res
  216. return __wrapper
  217. if __name__ == "__main__":
  218. pass
  219. print make_password("hnwz@2021")