common_control.py 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  1. # coding:utf-8
  2. import os,time,datetime
  3. import sys
  4. import django
  5. import json
  6. from django.core.paginator import Paginator
  7. from django.conf import settings
  8. from django_redis import get_redis_connection
  9. import common.models as cm
  10. import common.common_functions as ccf
  11. from utils.upload_to_oss import hnoss
  12. import redis_lock
  13. cache = get_redis_connection('data')
  14. pl = cache.pipeline()
  15. class CusJSONEncoder(json.JSONEncoder):
  16. """
  17. JSONEncoder subclass that knows how to encode date/time, decimal types and UUIDs.
  18. """
  19. def default(self, o):
  20. # See "Date Time String Format" in the ECMA-262 specification.
  21. if isinstance(o, datetime.datetime):
  22. r = datetime.datetime.strftime(o,'%Y-%m-%d %H:%M:%S')
  23. return r
  24. elif isinstance(o, datetime.date):
  25. return o.isoformat()
  26. elif isinstance(o, datetime.time):
  27. if is_aware(o):
  28. raise ValueError("JSON can't represent timezone-aware times.")
  29. r = o.isoformat()
  30. if o.microsecond:
  31. r = r[:12]
  32. return r
  33. elif isinstance(o, datetime.timedelta):
  34. return duration_iso_string(o)
  35. elif isinstance(o, decimal.Decimal):
  36. return str(o)
  37. elif isinstance(o, uuid.UUID):
  38. return str(o)
  39. else:
  40. return super(JSONEncoder, self).default(o)
  41. def cache_data(timeout=60*60):
  42. def _wrapper(func):
  43. def __wrapper(*args,**kwargs):
  44. if args:
  45. key = "cdata_{}_{}".format(func.__name__,str(args))
  46. elif kwargs:
  47. kwstr = ""
  48. for k in kwargs:
  49. kstr = "{}:{};".format(k,kwargs.get(k))
  50. kwstr += kstr
  51. key = "cdata_{}_{}".format(func.__name__,kwstr)
  52. else:
  53. key = "cdata_{}".format(func.__name__)
  54. #if not kwargs.get("cache",True) or not cache.get(key):
  55. if not cache.get(key):
  56. res = func(*args,**kwargs)
  57. if res:
  58. cache.set(key,json.dumps(res,cls=CusJSONEncoder),timeout)
  59. #print u"不取缓存!!!!!!!!!"
  60. return res
  61. else:
  62. #print u"取缓存"
  63. res = cache.get(key)
  64. return json.loads(res) if res else {}
  65. return __wrapper
  66. return _wrapper
  67. def no_cache(key="*"):
  68. def _wrapper(func):
  69. def __wrapper(*args,**kwargs):
  70. res = func(*args,**kwargs)
  71. print cache.delete_pattern("cdata_{}*".format(key))
  72. return res
  73. return __wrapper
  74. return _wrapper
  75. def no_cache_list(keys=[]):
  76. def _wrapper(func):
  77. def __wrapper(*args,**kwargs):
  78. res = func(*args,**kwargs)
  79. for key in keys:
  80. print cache.delete_pattern("cdata_{}*".format(key))
  81. return res
  82. return __wrapper
  83. return _wrapper
  84. def del_cache(key):
  85. """
  86. """
  87. print cache.delete(key)
  88. def get_page_qset(qset,page,page_size=20):
  89. """
  90. """
  91. count = qset.count()
  92. if page and page_size:
  93. paginator = Paginator(qset,page_size)
  94. object_list = paginator.page(page).object_list
  95. else:
  96. object_list = qset
  97. return count,object_list
  98. def upload_file(request):
  99. """
  100. """
  101. upload_file = request.FILES['file']
  102. ext = os.path.splitext(upload_file.name)[-1]
  103. timestamp = str(int(time.time()*1000))
  104. #dest = settings.STATIC_ROOT + "/upload/"+str(int(time.time()*1000)) + upload_file.name
  105. ossfile = timestamp + ext
  106. content = upload_file.read()
  107. watermark = request.json.get("watermark")
  108. url = hnoss.upload_from_str(content,ossfile,watermark)
  109. rst = {"url":url,"type":request.POST.get("type"),"name":upload_file.name}
  110. return rst
  111. dest = settings.STATIC_ROOT + "/upload/"+ timestamp + ext
  112. with open(dest,"wb+") as f:
  113. for chunk in upload_file.chunks():
  114. f.write(chunk)
  115. f.close()
  116. url = dest.replace(settings.STATIC_ROOT,settings.HOST)
  117. rst = {"url":url,"type":request.POST.get("type"),"name":upload_file.name}
  118. #
  119. if ext == ".mp4":
  120. imgpath = settings.STATIC_ROOT + "/upload/" + timestamp + ".png"
  121. cmd = "ffmpeg -i {} -ss 1.000 -vframes 1 {}".format(dest,imgpath)
  122. os.system(cmd)
  123. imgurl = imgpath.replace(settings.STATIC_ROOT,settings.HOST)
  124. rst["imgurl"] = imgurl
  125. return rst
  126. def get_cur_match():
  127. """获取当前赛事
  128. """
  129. now = datetime.datetime.now().strftime("%Y-%m-%d")
  130. cur_match = cm.Match.objects.filter(match_status=3).order_by("-id").first()
  131. return cur_match
  132. def get_signup_match():
  133. """获取报名赛事
  134. """
  135. now = datetime.datetime.now().strftime("%Y-%m-%d")
  136. #先查询开始报名的赛事
  137. cur_match = cm.Match.objects.filter(match_status=2).order_by("-id").first()
  138. if not cur_match:
  139. cur_match = cm.Match.objects.filter(match_status=3).order_by("-id").first()
  140. return cur_match
  141. def ueditor_to_oss(request):
  142. """
  143. """
  144. upload_file = request.FILES['upfile']
  145. ext = os.path.splitext(upload_file.name)[-1]
  146. timestamp = str(int(time.time()*1000))
  147. dest = "upload/"+ timestamp + ext
  148. #from utils.upload_to_oss import TedOSS
  149. #tedoss = TedOSS()
  150. url = hnoss.upload_from_str(upload_file.chunks(),dest)
  151. print url
  152. return url
  153. @cache_data()
  154. def get_user_info(uid):
  155. user = cm.UserInfo.objects.filter(id=uid).values().first()
  156. if user:
  157. user["style"] = []
  158. if user["zq"]:
  159. user["style"].append(user["zq"])
  160. if user["cw"]:
  161. user["style"].append(user["cw"])
  162. if user["df"]:
  163. user["style"].append(user["df"])
  164. del user["phone"]
  165. return user
  166. def get_today_date():
  167. if datetime.datetime.now().strftime("%H:%M") < "15:00":
  168. if datetime.datetime.now().weekday() in [5,6]:
  169. today = cm.PlayerRecord.objects.all().order_by("-stock_date").first().stock_date
  170. else:
  171. if datetime.datetime.now().weekday()==0:
  172. today = (datetime.datetime.now()-datetime.timedelta(days=3)).strftime("%Y-%m-%d")
  173. else:
  174. today = (datetime.datetime.now()-datetime.timedelta(days=1)).strftime("%Y-%m-%d")
  175. else:
  176. if datetime.datetime.now().weekday() in [5,6]:
  177. today = cm.PlayerRecord.objects.all().order_by("-stock_date").first().stock_date
  178. else:
  179. today = datetime.datetime.now().strftime("%Y-%m-%d")
  180. return today
  181. def get_today_record(user_id,match_id,match_group,today):
  182. """
  183. """
  184. key = "%s_%s_%s_%s" % (user_id,match_id,match_group,today)
  185. today_record = cache.get(key)
  186. today_record = json.loads(today_record) if today_record else {}
  187. #if match_id and not match_id==get_cur_match().id and not today_record:
  188. # #记得这里上线后要注释掉
  189. # today_record = cm.PlayerRecord.get_db_model(match_id).objects.filter(user_id=user_id,match_id=match_id,stock_date=today)
  190. # today_record = today_record.values().first()
  191. try:
  192. if today_record:
  193. user_info = get_user_info(today_record["user_id"])
  194. if user_info:
  195. user_info.pop("id")
  196. today_record.update(user_info)
  197. #仓位
  198. today_stock_total = 0
  199. today_stock = json.loads(today_record["today_stock"]) if today_record.get("today_stock") else []
  200. for ts in today_stock:
  201. if ts["fund"]:
  202. try:
  203. today_stock_total += float(ts["fund"])
  204. except Exception as e:
  205. print e
  206. today_record["cangwei"] = "{}%".format(round(today_stock_total/today_record["today_fund"],4)*100)
  207. today_record["today_stock_total"] = today_stock_total
  208. if today_record.get("phone"):
  209. del today_record["phone"]
  210. except Exception as e:
  211. import traceback
  212. traceback.print_exc()
  213. return today_record
  214. if __name__ == "__main__":
  215. #测试
  216. print get_pparents_info(1550,[])