common_control.py 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130
  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. cache = get_redis_connection('data')
  13. pl = cache.pipeline()
  14. class CusJSONEncoder(json.JSONEncoder):
  15. """
  16. JSONEncoder subclass that knows how to encode date/time, decimal types and UUIDs.
  17. """
  18. def default(self, o):
  19. # See "Date Time String Format" in the ECMA-262 specification.
  20. if isinstance(o, datetime.datetime):
  21. r = datetime.datetime.strftime(o,'%Y-%m-%d %H:%M:%S')
  22. return r
  23. elif isinstance(o, datetime.date):
  24. return o.isoformat()
  25. elif isinstance(o, datetime.time):
  26. if is_aware(o):
  27. raise ValueError("JSON can't represent timezone-aware times.")
  28. r = o.isoformat()
  29. if o.microsecond:
  30. r = r[:12]
  31. return r
  32. elif isinstance(o, datetime.timedelta):
  33. return duration_iso_string(o)
  34. elif isinstance(o, decimal.Decimal):
  35. return str(o)
  36. elif isinstance(o, uuid.UUID):
  37. return str(o)
  38. else:
  39. return super(JSONEncoder, self).default(o)
  40. def cache_data(timeout=60*60):
  41. def _wrapper(func):
  42. def __wrapper(*args,**kwargs):
  43. if args:
  44. key = "cdata_{}_{}".format(func.__name__,str(args))
  45. else:
  46. key = "cdata_{}".format(func.__name__)
  47. #if not kwargs.get("cache",True) or not cache.get(key):
  48. if not cache.get(key):
  49. res = func(*args,**kwargs)
  50. if res:
  51. cache.set(key,json.dumps(res,cls=CusJSONEncoder),timeout)
  52. #print u"不取缓存!!!!!!!!!"
  53. return res
  54. else:
  55. #print u"取缓存"
  56. res = cache.get(key)
  57. return json.loads(res) if res else {}
  58. return __wrapper
  59. return _wrapper
  60. def no_cache(key="*"):
  61. def _wrapper(func):
  62. def __wrapper(*args,**kwargs):
  63. res = func(*args,**kwargs)
  64. print 999999999999999
  65. print cache.delete_pattern("cdata_{}*".format(key))
  66. return res
  67. return __wrapper
  68. return _wrapper
  69. def no_cache_list(keys=[]):
  70. def _wrapper(func):
  71. def __wrapper(*args,**kwargs):
  72. res = func(*args,**kwargs)
  73. for key in keys:
  74. print cache.delete_pattern("cdata_{}*".format(key))
  75. return res
  76. return __wrapper
  77. return _wrapper
  78. def del_cache(key):
  79. """
  80. """
  81. print cache.delete(key)
  82. def get_page_qset(qset,page,page_size=20):
  83. """
  84. """
  85. count = qset.count()
  86. if page and page_size:
  87. paginator = Paginator(qset,page_size)
  88. object_list = paginator.page(page).object_list
  89. else:
  90. object_list = qset
  91. return count,object_list
  92. def upload_file(request):
  93. """
  94. """
  95. upload_file = request.FILES['file']
  96. ext = os.path.splitext(upload_file.name)[-1]
  97. timestamp = str(int(time.time()*1000))
  98. #dest = settings.STATIC_ROOT + "/upload/"+str(int(time.time()*1000)) + upload_file.name
  99. dest = settings.STATIC_ROOT + "/upload/"+ timestamp + ext
  100. with open(dest,"wb+") as f:
  101. for chunk in upload_file.chunks():
  102. f.write(chunk)
  103. f.close()
  104. url = dest.replace(settings.STATIC_ROOT,settings.HOST)
  105. rst = {"url":url,"type":request.POST.get("type"),"name":upload_file.name}
  106. #
  107. if ext == ".mp4":
  108. imgpath = settings.STATIC_ROOT + "/upload/" + timestamp + ".png"
  109. cmd = "ffmpeg -i {} -ss 1.000 -vframes 1 {}".format(dest,imgpath)
  110. os.system(cmd)
  111. imgurl = imgpath.replace(settings.STATIC_ROOT,settings.HOST)
  112. rst["imgurl"] = imgurl
  113. return rst
  114. if __name__ == "__main__":
  115. #测试
  116. print get_pparents_info(1550,[])