common_control.py 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172
  1. # coding:utf-8
  2. import os,time,datetime
  3. import sys
  4. import django
  5. import json
  6. #from django.core.cache import cache
  7. from django.core.paginator import Paginator
  8. from django.conf import settings
  9. from django_redis import get_redis_connection
  10. import common.models as cm
  11. import common.common_functions as ccf
  12. from utils.upload_to_oss import hnoss
  13. import redis_lock
  14. cache = get_redis_connection('data')
  15. pl = cache.pipeline()
  16. #redis_lock.reset_all(cache)
  17. class CusJSONEncoder(json.JSONEncoder):
  18. """
  19. JSONEncoder subclass that knows how to encode date/time, decimal types and UUIDs.
  20. """
  21. def default(self, o):
  22. # See "Date Time String Format" in the ECMA-262 specification.
  23. if isinstance(o, datetime.datetime):
  24. r = datetime.datetime.strftime(o,'%Y-%m-%d %H:%M:%S')
  25. return r
  26. elif isinstance(o, datetime.date):
  27. return o.isoformat()
  28. elif isinstance(o, datetime.time):
  29. if is_aware(o):
  30. raise ValueError("JSON can't represent timezone-aware times.")
  31. r = o.isoformat()
  32. if o.microsecond:
  33. r = r[:12]
  34. return r
  35. elif isinstance(o, datetime.timedelta):
  36. return duration_iso_string(o)
  37. elif isinstance(o, decimal.Decimal):
  38. return str(o)
  39. elif isinstance(o, uuid.UUID):
  40. return str(o)
  41. else:
  42. return super(JSONEncoder, self).default(o)
  43. def cache_data(timeout=60*60):
  44. def _wrapper(func):
  45. def __wrapper(*args,**kwargs):
  46. if args:
  47. key = "cdata_{}_{}".format(func.__name__,str(args))
  48. else:
  49. key = "cdata_{}".format(func.__name__)
  50. #if not kwargs.get("cache",True) or not cache.get(key):
  51. if not cache.get(key):
  52. res = func(*args,**kwargs)
  53. if res:
  54. cache.set(key,json.dumps(res,cls=CusJSONEncoder),timeout)
  55. #print u"不取缓存!!!!!!!!!"
  56. return res
  57. else:
  58. #print u"取缓存"
  59. res = cache.get(key)
  60. return json.loads(res) if res else {}
  61. return __wrapper
  62. return _wrapper
  63. def no_cache(key="*"):
  64. def _wrapper(func):
  65. def __wrapper(*args,**kwargs):
  66. res = func(*args,**kwargs)
  67. print cache.delete_pattern("cdata_{}*".format(key))
  68. return res
  69. return __wrapper
  70. return _wrapper
  71. def no_cache_list(keys=[]):
  72. def _wrapper(func):
  73. def __wrapper(*args,**kwargs):
  74. res = func(*args,**kwargs)
  75. for key in keys:
  76. print cache.delete_pattern("cdata_{}*".format(key))
  77. return res
  78. return __wrapper
  79. return _wrapper
  80. def del_cache(key):
  81. """
  82. """
  83. print cache.delete(key)
  84. def get_page_qset(qset,page,page_size=20):
  85. """
  86. """
  87. count = qset.count()
  88. if page and page_size:
  89. paginator = Paginator(qset,page_size)
  90. object_list = paginator.page(page).object_list
  91. else:
  92. object_list = qset
  93. return count,object_list
  94. def upload_file(request):
  95. """
  96. """
  97. upload_file = request.FILES['file']
  98. ext = os.path.splitext(upload_file.name)[-1]
  99. timestamp = str(int(time.time()*1000))
  100. #dest = settings.STATIC_ROOT + "/upload/"+str(int(time.time()*1000)) + upload_file.name
  101. ossfile = timestamp + ext
  102. content = upload_file.read()
  103. watermark = request.json.get("watermark")
  104. url = hnoss.upload_from_str(content,ossfile,watermark)
  105. rst = {"url":url,"type":request.POST.get("type"),"name":upload_file.name}
  106. return rst
  107. dest = settings.STATIC_ROOT + "/upload/"+ timestamp + ext
  108. with open(dest,"wb+") as f:
  109. for chunk in upload_file.chunks():
  110. f.write(chunk)
  111. f.close()
  112. url = dest.replace(settings.STATIC_ROOT,settings.HOST)
  113. rst = {"url":url,"type":request.POST.get("type"),"name":upload_file.name}
  114. #
  115. if ext == ".mp4":
  116. imgpath = settings.STATIC_ROOT + "/upload/" + timestamp + ".png"
  117. cmd = "ffmpeg -i {} -ss 1.000 -vframes 1 {}".format(dest,imgpath)
  118. os.system(cmd)
  119. imgurl = imgpath.replace(settings.STATIC_ROOT,settings.HOST)
  120. rst["imgurl"] = imgurl
  121. return rst
  122. def get_cur_match():
  123. """获取当前赛事
  124. """
  125. now = datetime.datetime.now().strftime("%Y-%m-%d")
  126. #cur_match = cm.Match.objects.filter(start_time__lte=now,end_time__gte=now).order_by("-id").first()
  127. cur_match = cm.Match.objects.filter(match_status=3).order_by("-id").first()
  128. return cur_match
  129. def get_signup_match():
  130. """获取报名赛事
  131. """
  132. now = datetime.datetime.now().strftime("%Y-%m-%d")
  133. #先查询开始报名的赛事
  134. cur_match = cm.Match.objects.filter(match_status=2).order_by("-id").first()
  135. if not cur_match:
  136. cur_match = cm.Match.objects.filter(match_status=3).order_by("-id").first()
  137. return cur_match
  138. def ueditor_to_oss(request):
  139. """
  140. """
  141. upload_file = request.FILES['upfile']
  142. ext = os.path.splitext(upload_file.name)[-1]
  143. timestamp = str(int(time.time()*1000))
  144. dest = "upload/"+ timestamp + ext
  145. #from utils.upload_to_oss import TedOSS
  146. #tedoss = TedOSS()
  147. url = hnoss.upload_from_str(upload_file.chunks(),dest)
  148. print url
  149. return url
  150. if __name__ == "__main__":
  151. #测试
  152. print get_pparents_info(1550,[])