| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172 |
- # coding:utf-8
- import os,time,datetime
- import sys
- import django
- import json
- #from django.core.cache import cache
- from django.core.paginator import Paginator
- from django.conf import settings
- from django_redis import get_redis_connection
- import common.models as cm
- import common.common_functions as ccf
- from utils.upload_to_oss import hnoss
- import redis_lock
- cache = get_redis_connection('data')
- pl = cache.pipeline()
- #redis_lock.reset_all(cache)
- class CusJSONEncoder(json.JSONEncoder):
- """
- JSONEncoder subclass that knows how to encode date/time, decimal types and UUIDs.
- """
- def default(self, o):
- # See "Date Time String Format" in the ECMA-262 specification.
- if isinstance(o, datetime.datetime):
- r = datetime.datetime.strftime(o,'%Y-%m-%d %H:%M:%S')
- return r
- elif isinstance(o, datetime.date):
- return o.isoformat()
- elif isinstance(o, datetime.time):
- if is_aware(o):
- raise ValueError("JSON can't represent timezone-aware times.")
- r = o.isoformat()
- if o.microsecond:
- r = r[:12]
- return r
- elif isinstance(o, datetime.timedelta):
- return duration_iso_string(o)
- elif isinstance(o, decimal.Decimal):
- return str(o)
- elif isinstance(o, uuid.UUID):
- return str(o)
- else:
- return super(JSONEncoder, self).default(o)
- def cache_data(timeout=60*60):
- def _wrapper(func):
- def __wrapper(*args,**kwargs):
- if args:
- key = "cdata_{}_{}".format(func.__name__,str(args))
- else:
- key = "cdata_{}".format(func.__name__)
- #if not kwargs.get("cache",True) or not cache.get(key):
- if not cache.get(key):
- res = func(*args,**kwargs)
- if res:
- cache.set(key,json.dumps(res,cls=CusJSONEncoder),timeout)
- #print u"不取缓存!!!!!!!!!"
- return res
- else:
- #print u"取缓存"
- res = cache.get(key)
- return json.loads(res) if res else {}
- return __wrapper
- return _wrapper
- def no_cache(key="*"):
- def _wrapper(func):
- def __wrapper(*args,**kwargs):
- res = func(*args,**kwargs)
- print cache.delete_pattern("cdata_{}*".format(key))
- return res
- return __wrapper
- return _wrapper
- def no_cache_list(keys=[]):
- def _wrapper(func):
- def __wrapper(*args,**kwargs):
- res = func(*args,**kwargs)
- for key in keys:
- print cache.delete_pattern("cdata_{}*".format(key))
- return res
- return __wrapper
- return _wrapper
- def del_cache(key):
- """
- """
- print cache.delete(key)
- def get_page_qset(qset,page,page_size=20):
- """
- """
- count = qset.count()
- if page and page_size:
- paginator = Paginator(qset,page_size)
- object_list = paginator.page(page).object_list
- else:
- object_list = qset
- return count,object_list
- def upload_file(request):
- """
- """
- upload_file = request.FILES['file']
- ext = os.path.splitext(upload_file.name)[-1]
- timestamp = str(int(time.time()*1000))
- #dest = settings.STATIC_ROOT + "/upload/"+str(int(time.time()*1000)) + upload_file.name
-
- ossfile = timestamp + ext
- content = upload_file.read()
- watermark = request.json.get("watermark")
- url = hnoss.upload_from_str(content,ossfile,watermark)
- rst = {"url":url,"type":request.POST.get("type"),"name":upload_file.name}
- return rst
- dest = settings.STATIC_ROOT + "/upload/"+ timestamp + ext
- with open(dest,"wb+") as f:
- for chunk in upload_file.chunks():
- f.write(chunk)
- f.close()
- url = dest.replace(settings.STATIC_ROOT,settings.HOST)
- rst = {"url":url,"type":request.POST.get("type"),"name":upload_file.name}
- #
- if ext == ".mp4":
- imgpath = settings.STATIC_ROOT + "/upload/" + timestamp + ".png"
- cmd = "ffmpeg -i {} -ss 1.000 -vframes 1 {}".format(dest,imgpath)
- os.system(cmd)
- imgurl = imgpath.replace(settings.STATIC_ROOT,settings.HOST)
- rst["imgurl"] = imgurl
- return rst
- def get_cur_match():
- """获取当前赛事
- """
- now = datetime.datetime.now().strftime("%Y-%m-%d")
- #cur_match = cm.Match.objects.filter(start_time__lte=now,end_time__gte=now).order_by("-id").first()
- cur_match = cm.Match.objects.filter(match_status=3).order_by("-id").first()
- return cur_match
- def get_signup_match():
- """获取报名赛事
- """
- now = datetime.datetime.now().strftime("%Y-%m-%d")
- #先查询开始报名的赛事
- cur_match = cm.Match.objects.filter(match_status=2).order_by("-id").first()
- if not cur_match:
- cur_match = cm.Match.objects.filter(match_status=3).order_by("-id").first()
- return cur_match
- def ueditor_to_oss(request):
- """
- """
- upload_file = request.FILES['upfile']
- ext = os.path.splitext(upload_file.name)[-1]
- timestamp = str(int(time.time()*1000))
- dest = "upload/"+ timestamp + ext
- #from utils.upload_to_oss import TedOSS
- #tedoss = TedOSS()
- url = hnoss.upload_from_str(upload_file.chunks(),dest)
- print url
- return url
- if __name__ == "__main__":
- #测试
- print get_pparents_info(1550,[])
|