瀏覽代碼

Add Modules

zry 8 年之前
父節點
當前提交
7645959e50

+ 56 - 0
swyzxwb_photovote/common/CalendarSys.py

@@ -0,0 +1,56 @@
+import calendar,datetime
+
+def GetNowYMD():
+	now=datetime.datetime.now()
+	nyear=now.year
+	nmonth=now.month
+	nday=now.day
+	return (nyear,nmonth,nday)
+
+def GetWeekSinceNow():
+	now=datetime.datetime.today()
+	nyear=now.year
+	nmonth=now.month
+	nday=now.day
+	return GetWeekSince(nyear,nmonth,nday)
+
+def GetWeekSince(nyear,nmonth,nday):
+	dotm=calendar.monthrange(nyear,nmonth)[1]
+	if nday + 7 <= dotm:
+		return (nyear,nmonth,0,range(nday+1,nday+8))
+	else:
+		rlist=range(nday+1,dotm+1)
+		rlist.extend(range(1,8-(dotm-nday)))
+		return (nyear,nmonth,dotm-nday,rlist)
+
+def GetBWeekSince(nyear,nmonth,nday):
+	dotm=calendar.monthrange(nyear,nmonth)[1]
+	if nday + 10 <= dotm:
+		return (nyear,nmonth,0,range(nday+1,nday+11))
+	else:
+		rlist=range(nday+1,dotm+1)
+		rlist.extend(range(1,11-(dotm-nday)))
+		return (nyear,nmonth,dotm-nday,rlist)
+
+def GetBWeekSinceYesterday():
+	now=datetime.datetime.today()-datetime.timedelta(days=1)
+	nyear=now.year
+	nmonth=now.month
+	nday=now.day
+	return GetBWeekSince(nyear,nmonth,nday)
+
+def GetTenDaysRangeSinceYesterday():
+	opdt=datetime.date.today()-datetime.timedelta(days=1)
+	eddt=datetime.date.today()+datetime.timedelta(days=9)
+	return (opdt,eddt)
+
+def GetDateoutRangeSinceYesterday():
+	opdt=datetime.date(1,1,1)
+	eddt=datetime.date.today()-datetime.timedelta(days=1)
+	return (opdt,eddt)
+
+def SafetyStrftime(datetime,fmt):
+	try:
+		return datetime.strftime(fmt)
+	except:
+		return ""

+ 256 - 0
swyzxwb_photovote/common/CommonFilter.py

@@ -0,0 +1,256 @@
+from website.common.DataConvert import Str2Date,str2int
+from django.template.loader import render_to_string
+from django.conf import settings
+
+class AddableDict(dict):
+	def __add__(d1,d2):
+		return AddableDict(d1.items()+d2.items())
+
+class FilterCondition:
+	def __init__(self):
+		self.fcd={
+			"index":[],
+			"ceq":AddableDict(),
+			"cueq":AddableDict(),
+			"cc":AddableDict(),
+			"cuc":AddableDict(),
+			"csw":AddableDict(),
+			"cew":AddableDict(),
+			"cnsw":AddableDict(),
+			"cnew":AddableDict(),
+			"deq":AddableDict(),
+			"drg":AddableDict(),
+			"neq":AddableDict(),
+			"nneq":AddableDict(),
+			"ngt":AddableDict(),
+			"nlt":AddableDict(),
+			"csc":AddableDict(),
+			"cmc":AddableDict(),
+			"sf":AddableDict(),
+		}
+	def addTextEqual(self,name,title,fieldname):
+		self.fcd['index'].append(name)
+		self.fcd['ceq'].update({name:(title,fieldname)})
+	def addTextUnequal(self,name,title,fieldname):
+		self.fcd['index'].append(name)
+		self.fcd['cueq'].update({name:(title,fieldname)})
+	def addTextContain(self,name,title,fieldname):
+		self.fcd['index'].append(name)
+		self.fcd['cc'].update({name:("*"+title+"*",fieldname)})
+	def addTextUncontain(self,name,title,fieldname):
+		self.fcd['index'].append(name)
+		self.fcd['cuc'].update({name:("*"+title+"*",fieldname)})
+	def addTextStartWith(self,name,title,fieldname):
+		self.fcd['index'].append(name)
+		self.fcd['csw'].update({name:(title+"*",fieldname)})
+	def addTextEndWith(self,name,title,fieldname):
+		self.fcd['index'].append(name)
+		self.fcd['cew'].update({name:("*"+title,fieldname)})
+	def addTextNotStartWith(self,name,title,fieldname):
+		self.fcd['index'].append(name)
+		self.fcd['cnsw'].update({name:(title+"*",fieldname)})
+	def addTextNotEndWith(self,name,title,fieldname):
+		self.fcd['index'].append(name)
+		self.fcd['cnew'].update({name:("*"+title,fieldname)})
+	def addDateEqual(self,name,title,fieldname):
+		self.fcd['index'].append(name)
+		self.fcd['deq'].update({name:(title,fieldname)})
+	def addDateRange(self,name,title,fieldname):
+		self.fcd['index'].append(name)
+		self.fcd['drg'].update({name:(title,fieldname)})
+	def addNumberEqual(self,name,title,fieldname):
+		self.fcd['index'].append(name)
+		self.fcd['neq'].update({name:(title,fieldname)})
+	def addNumberUnEqual(self,name,title,fieldname):
+		self.fcd['index'].append(name)
+		self.fcd['nneq'].update({name:(title,fieldname)})
+	def addNumberGreatThan(self,name,title,fieldname,equal):
+		self.fcd['index'].append(name)
+		self.fcd['ngt'].update({name:(title,fieldname,equal)})
+	def addNumberLessThan(self,name,title,fieldname,equal):
+		self.fcd['index'].append(name)
+		self.fcd['nlt'].update({name:(title,fieldname,equal)})
+	def addSingleChoice(self,name,title,fieldname,clist,alias=None):
+		self.fcd['index'].append(name)
+		self.fcd['csc'].update({name:(title,fieldname,clist,alias)})
+	def addMultiChoice(self,name,title,fieldname,clist,alias=None):
+		self.fcd['index'].append(name)
+		self.fcd['cmc'].update({name:(title,fieldname,clist,alias)})
+	def AddSortField(self,name,title,fieldname):
+		self.fcd['sf'].update({name:(title,fieldname)})
+	def RenderHTML(self,request):
+		def fcondget(kn):
+			try:
+				r=fcond.get(kn)
+			except:
+				r=""
+			if not r:
+				r=""
+			return r
+		fcond = request.GET
+		dtext=self.fcd['ceq']+self.fcd['cueq']+self.fcd['cc']+self.fcd['cuc']+self.fcd['csw']+self.fcd['cew']+self.fcd['cnsw']+self.fcd['cnew']
+		dval=self.fcd['neq']+self.fcd['nneq']+self.fcd['ngt']+self.fcd['nlt']
+		#dtext=self.fcd['ceq']+self.fcd['cueq']
+		iText=[]
+		iVal=[]
+		iDateE=[]
+		iDateR=[]
+		iSC=[]
+		iMC=[]
+		kl=filter(lambda x:x in dtext.keys(),self.fcd['index'])
+		for i in kl:
+			iText.append({"ctname":i,"ctid":"ipc_"+i,"title":dtext[i][0],"value":fcondget(i)})
+		kl=filter(lambda x:x in dval.keys(),self.fcd['index'])
+		for i in kl:
+			iVal.append({"ctname":i,"ctid":"ipc_"+i,"title":dval[i][0],"value":fcondget(i)})
+		kl=filter(lambda x:x in self.fcd['deq'].keys(),self.fcd['index'])
+		for i in kl:
+			iDateE.append({"ctname":i,"ctid":"ipc_"+i,"title":self.fcd['deq'][i][0],"value":fcondget(i)})
+		kl=filter(lambda x:x in self.fcd['drg'].keys(),self.fcd['index'])
+		for i in kl:
+			try:
+				vst,ved=fcond.get(i).split('~')
+			except:
+				vst,ved="",""
+			if not vst:
+				vst=""
+			if not ved:
+				ved=""
+			iDateR.append({"ctname":i,"ctid":"ipc_"+i,"title":self.fcd['drg'][i][0],"valuest":vst,"valueed":ved})
+		kl=filter(lambda x:x in self.fcd['csc'].keys(),self.fcd['index'])
+		for i in kl:
+			fc=fcondget(i)
+			if fc=="":
+				fc="all"
+			if self.fcd['csc'][i][3]:
+				iSC.append({"ctname":i,"ctid":"ipc_"+i,"title":self.fcd['csc'][i][0],"oplst":self.fcd['csc'][i][3],"value":fc})
+			else:
+				iSC.append({"ctname":i,"ctid":"ipc_"+i,"title":self.fcd['csc'][i][0],"oplst":self.fcd['csc'][i][2],"value":fc})
+		kl=filter(lambda x:x in self.fcd['cmc'].keys(),self.fcd['index'])
+		for i in kl:
+			if self.fcd['cmc'][i][3]:
+				iMC.append({"ctname":i,"ctid":"ipc_"+i,"title":self.fcd['cmc'][i][0],"oplst":self.fcd['cmc'][i][3],"value":fcondget(i)})
+			else:
+				iMC.append({"ctname":i,"ctid":"ipc_"+i,"title":self.fcd['cmc'][i][0],"oplst":self.fcd['cmc'][i][2],"value":fcondget(i)})
+		kwvars={
+			"textitems":iText,
+			"valitems":iVal,
+			"dateeqi":iDateE,
+			"datergi":iDateR,
+			"scitems":iSC,
+			"mcitems":iMC
+		}
+		return render_to_string("common/Filter/maindiv.html",kwvars)
+
+def _CommonFilter(request,fco,data):
+	fcond = request.GET
+	td=data
+	wl=filter(lambda x:x in fco.fcd['ceq'].keys(),fcond.keys())
+	if wl:
+		for i in wl:
+			argv={fco.fcd['ceq'][i][1]+"__exact":fcond[i]}
+			td=td.filter(**argv)
+	wl=filter(lambda x:x in fco.fcd['cueq'].keys(),fcond.keys())
+	if wl:
+		for i in wl:
+			argv={fco.fcd['cueq'][i][1]+"__exact":fcond[i]}
+			td=td.exclude(**argv)
+	wl=filter(lambda x:x in fco.fcd['cc'].keys(),fcond.keys())
+	if wl:
+		for i in wl:
+			argv={fco.fcd['cc'][i][1]+"__contains":fcond[i]}
+			td=td.filter(**argv)
+	wl=filter(lambda x:x in fco.fcd['cuc'].keys(),fcond.keys())
+	if wl:
+		for i in wl:
+			argv={fco.fcd['cuc'][i][1]+"__contains":fcond[i]}
+			td=td.exclude(**argv)
+	wl=filter(lambda x:x in fco.fcd['csw'].keys(),fcond.keys())
+	if wl:
+		for i in wl:
+			argv={fco.fcd['csw'][i][1]+"__startswith":fcond[i]}
+			td=td.filter(**argv)
+	wl=filter(lambda x:x in fco.fcd['cnsw'].keys(),fcond.keys())
+	if wl:
+		for i in wl:
+			argv={fco.fcd['cnsw'][i][1]+"__startswith":fcond[i]}
+			td=td.exclude(**argv)
+	wl=filter(lambda x:x in fco.fcd['cew'].keys(),fcond.keys())
+	if wl:
+		for i in wl:
+			argv={fco.fcd['cew'][i][1]+"__endswith":fcond[i]}
+			td=td.filter(**argv)
+	wl=filter(lambda x:x in fco.fcd['cnew'].keys(),fcond.keys())
+	if wl:
+		for i in wl:
+			argv={fco.fcd['cnew'][i][1]+"__endswith":fcond[i]}
+			td=td.exclude(**argv)
+	#====================
+	wl=filter(lambda x:x in fco.fcd['deq'].keys(),fcond.keys())
+	if wl:
+		for i in wl:
+			argv={fco.fcd['deq'][i][1]+"__exact":Str2Date(fcond[i])}
+			td=td.filter(**argv)
+	wl=filter(lambda x:x in fco.fcd['drg'].keys(),fcond.keys())
+	if wl:
+		for i in wl:
+			try:
+				pl=fcond[i].split("~",2)
+				argv={fco.fcd['drg'][i][1]+"__range":(Str2Date(pl[0]),Str2Date(pl[1]))}
+				td=td.filter(**argv)
+			except:
+				pass
+	#====================
+	wl=filter(lambda x:x in fco.fcd['neq'].keys(),fcond.keys())
+	if wl:
+		for i in wl:
+			argv={fco.fcd['neq'][i][1]+"__exact":str2int(fcond[i])}
+			td=td.filter(**argv)
+	wl=filter(lambda x:x in fco.fcd['nneq'].keys(),fcond.keys())
+	if wl:
+		for i in wl:
+			argv={fco.fcd['nneq'][i][1]+"__exact":str2int(fcond[i])}
+			td=td.exclude(**argv)
+
+	wl=filter(lambda x:x in fco.fcd['ngt'].keys(),fcond.keys())
+	if wl:
+		for i in wl:
+			if fco.fcd['ngt'][i][2]:
+				argv={fco.fcd['ngt'][i][1]+"__gte":str2int(fcond[i])}
+			else:
+				argv={fco.fcd['ngt'][i][1]+"__gt":str2int(fcond[i])}
+			td=td.filter(**argv)
+	wl=filter(lambda x:x in fco.fcd['nlt'].keys(),fcond.keys())
+	if wl:
+		for i in wl:
+			if fco.fcd['nlt'][i][2]:
+				argv={fco.fcd['nlt'][i][1]+"__lte":str2int(fcond[i])}
+			else:
+				argv={fco.fcd['nlt'][i][1]+"__lt":str2int(fcond[i])}
+			td=td.filter(**argv)
+	#==============================
+	wl=filter(lambda x:x in fco.fcd['csc'].keys(),fcond.keys())
+	if wl:
+		for i in wl:
+			if not fcond[i]=="all":
+				iid=str2int(fcond[i])
+				idn=fco.fcd['csc'][i][2][iid]
+				argv={fco.fcd['csc'][i][1]+"__exact":idn}
+				td=td.filter(**argv)
+	wl=filter(lambda x:x in fco.fcd['cmc'].keys(),fcond.keys())
+	if wl:
+		for i in wl:
+			idlst=fcond[i].split(',')
+			idn=map(lambda x:fco.fcd['cmc'][i][2][str2int(x)],idlst)
+			argv={fco.fcd['cmc'][i][1]+"__in":idn}
+			td=td.filter(**argv)
+	return td
+
+def CommonFilter(request,fco,data):
+	if settings.DEBUG:
+		return _CommonFilter(request,fco,data)
+	else:
+		try:
+			_CommonFilter(request,fco,data)
+		except:
+			return data

+ 42 - 0
swyzxwb_photovote/common/CommonPaginator.py

@@ -0,0 +1,42 @@
+#!/usr/bin/env python
+#-*- coding: utf-8 -*-
+#update:2014-09-25 by liufeily@163.com
+
+from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
+
+def SelfPaginator(request,List,Limit):
+    '''分页模块,用法:
+        1.view中引入:
+        ex:from website.common.CommonPaginator import SelfPaginator
+        
+        2.SelfPaginator需要传入三个参数
+            (1).request:获取请求数据
+            (2).List:为需要分页的数据(一般为*.objects.all()取出来数据)
+            (3).Limit:为每页显示的条数
+        ex:lst = SelfPaginator(request,mList, 5)
+        
+        3.view需要获取SelfPaginator return的lst,并把lst返回给前端模板
+        ex:kwvars = {'lPage':lst,}
+        
+        4.前端需要for循环lPage也就是lst读取每页内容
+        ex:{% for i in lPage %} ... {% endfor %}
+        
+        5.模板页引入paginator.html
+        ex:{% include "common/paginator.html" %}
+    '''
+
+    paginator = Paginator(List, int(Limit))
+
+    page = request.GET.get('page')
+    try:
+        lst = paginator.page(page)
+    except PageNotAnInteger:
+        lst = paginator.page(1)
+    except EmptyPage:
+        lst = paginator.page(paginator.num_pages)
+
+    return lst
+
+if __name__=='__main__':
+    rList = User.objects.all()
+    lst = SelfPaginator(request,rList,20)

+ 60 - 0
swyzxwb_photovote/common/DataConvert.py

@@ -0,0 +1,60 @@
+# -*- coding: UTF-8 -*-
+import decimal,math,time,datetime
+
+def str2int(strs):
+	strr=filter(lambda x:(x.isdigit or x=='-'),str(strs))
+	if strr==None:
+		return 0
+	elif strr=='':
+		return 0
+	else:
+		return int(strr)
+
+def parseDecimal(strs,totalLen,apart):
+	apt=strs.split(".",1)
+	if len(apt) == 1:
+		return decimal.Decimal(str(str2int(strs)))
+	else:
+		ipart=str(str2int(apt[0]))
+		fpart=str(str2int(apt[1].replace('.','')))
+	if(len(fpart)>apart):
+		fptx=fpart[:apart]
+		fpi=int(fptx)
+		if(int(fpart[apart])>4):
+			fpi=fpi+1
+	else:
+		fpi=int(fpart)
+	if(len(ipart)>totalLen-apart):
+		iptx='9'*(totalLen-apart)
+		ipi=int(iptx)
+	else:
+		ipi=int(ipart)
+	return decimal.Decimal(str(ipi)+'.'+str(fpi))
+
+def CheckPOST(needlist,postkeys):
+	for i in needlist:
+		if i not in postkeys:
+			return i
+	return ""
+
+def MakeSummary(text,length):
+	# if len(text.decode('utf8','ignore'))>length:
+	# 	text=text.decode('utf8','ignore')[:length].encode("utf8")+u"..."
+	# return text
+	if len(text)>length:
+		text=text[:length]+u"..."
+	return text
+
+
+def convertBytes(bytes,lst=['字节', 'KB', 'MB', 'GB', 'TB', 'PB']):
+	i = int(math.floor(
+			 math.log(bytes, 1024)
+			))
+
+	if i >= len(lst):
+		i = len(lst) - 1
+	return ('%.2f' + " " + lst[i]) % (bytes/math.pow(1024, i))
+
+def Str2Date(strdate):
+	t = time.strptime(strdate,"%Y-%m-%d")
+	return datetime.date(t.tm_year,t.tm_mon,t.tm_mday)

+ 9 - 0
swyzxwb_photovote/common/JsonResponse.py

@@ -0,0 +1,9 @@
+from django.http import HttpResponse
+import json
+from django.utils.html import strip_tags as html_strip_tags
+
+def JsonResponse(datas,strip_tags=True):
+	jd=json.dumps(datas)
+	if strip_tags:
+		jd=html_strip_tags(jd)
+	return HttpResponse(jd,content_type="application/json")

+ 0 - 0
swyzxwb_photovote/common/__init__.py


+ 56 - 0
swyzxwb_photovote/common/safe_eval.py

@@ -0,0 +1,56 @@
+#encoding=utf-8
+#code by ZPCCZQ
+#2015-08-25
+
+import re
+
+def safe_eval(eval_str,**kw):
+    '''
+    安全eval,确保eval的内容是合法的,并且隔离的。
+    **kw为可定义命名空间。
+    '''
+    #callback functions
+    def start_structure(scanner, token): return "start structure", token
+    def key(scanner, token):   return "key", token
+    def value(scanner, token): 
+        #非法写法
+        if token.lower() == 'true'and token != 'True':
+            raise 'value Error "%s"'%token
+    def str_value(scanner,token):   
+        return "string value",token
+    def end_structure(scanner, token):  return "end start structure",token
+        
+    scanner = re.Scanner([
+        (r"[{\[(]", start_structure),
+        (r"[\w]+\s*:", key),
+        (r"['\"][^'\"]+['\"]",str_value),
+        (r"[\w]+", value),
+        (r"\s*,\s*",None),
+        (r"[})\]]", end_structure),
+    ])
+ 
+    tokens, remainder = scanner.scan(eval_str)
+    #make a list of safe functions
+    safe_list = ['math','acos', 'asin', 'atan', 'atan2', 'ceil', 'cos', 'cosh', 'de grees', 'e', 'exp', 'fabs', 'floor', 'fmod', 'frexp', 'hypot', 'ldexp', 'log', 'log10', 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh']
+    #use the list to filter the local namespace s
+    safe_dict = dict([ (k, locals().get(k, None)) for k in safe_list ])
+    #add any needed builtins back in.
+    #由于所有内置的对象被屏蔽 __builtins__中的所有对象不可使用,所以True、False需要单独定义
+    #加入命名空间
+    safe_dict['True'] = True
+    safe_dict['False'] = False
+    safe_dict['sum'] = sum
+    safe_dict['map'] = map
+    safe_dict['filter'] = filter
+    safe_dict['reduce'] = reduce
+    safe_dict['abs'] = abs
+    safe_dict['divmod'] = divmod
+    safe_dict['round'] = round
+    for k in kw:
+        if k not in safe_dict:
+            safe_dict[k]=kw[k]
+    return eval(eval_str,{'__builtins__':None},safe_dict)
+
+if __name__ == '__main__':
+    pass
+