# coding:utf-8 import os,time,datetime import sys import django import json 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() 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)) elif kwargs: kwstr = "" for k in kwargs: kstr = "{}:{};".format(k,kwargs.get(k)) kwstr += kstr key = "cdata_{}_{}".format(func.__name__,kwstr) 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(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 @cache_data() def get_user_info(uid): user = cm.UserInfo.objects.filter(id=uid).values().first() if user: user["style"] = [] if user["zq"]: user["style"].append(user["zq"]) if user["cw"]: user["style"].append(user["cw"]) if user["df"]: user["style"].append(user["df"]) del user["phone"] return user def get_today_date(): if datetime.datetime.now().strftime("%H:%M") < "15:00": if datetime.datetime.now().weekday() in [5,6]: today = cm.PlayerRecord.objects.all().order_by("-stock_date").first().stock_date else: if datetime.datetime.now().weekday()==0: today = (datetime.datetime.now()-datetime.timedelta(days=3)).strftime("%Y-%m-%d") else: today = (datetime.datetime.now()-datetime.timedelta(days=1)).strftime("%Y-%m-%d") else: if datetime.datetime.now().weekday() in [5,6]: today = cm.PlayerRecord.objects.all().order_by("-stock_date").first().stock_date else: today = datetime.datetime.now().strftime("%Y-%m-%d") return today def get_today_record(user_id,match_id,match_group,today): """ """ key = "%s_%s_%s_%s" % (user_id,match_id,match_group,today) today_record = cache.get(key) today_record = json.loads(today_record) if today_record else {} #if match_id and not match_id==get_cur_match().id and not today_record: # #记得这里上线后要注释掉 # today_record = cm.PlayerRecord.get_db_model(match_id).objects.filter(user_id=user_id,match_id=match_id,stock_date=today) # today_record = today_record.values().first() try: if today_record: user_info = get_user_info(today_record["user_id"]) if user_info: user_info.pop("id") today_record.update(user_info) #仓位 today_stock_total = 0 today_stock = json.loads(today_record["today_stock"]) if today_record.get("today_stock") else [] for ts in today_stock: if ts["fund"]: try: today_stock_total += float(ts["fund"]) except Exception as e: print e today_record["cangwei"] = "{}%".format(round(today_stock_total/today_record["today_fund"],4)*100) today_record["today_stock_total"] = today_stock_total if today_record.get("phone"): del today_record["phone"] except Exception as e: import traceback traceback.print_exc() return today_record if __name__ == "__main__": #测试 print get_pparents_info(1550,[])