python验证数据的一些工具函数

2010-12-14 14:12:19

为了用于icokou对于表单提交数据的验证上,单独封装了一些函数便于使用

#! /usr/bin/env python
#coding=utf-8
import types
import re


"""
验证所有表单提交的数据
"""

#判断是否为整数 15
def IsNumber(varObj):

    return type(varObj) is types.IntType

#判断是否为字符串 string
def IsString(varObj):

    return type(varObj) is types.StringType

#判断是否为浮点数 1.324
def IsFloat(varObj):
    return type(varObj) is types.FloatType

#判断是否为字典 {'a1':'1','a2':'2'}
def IsDict(varObj):

    return type(varObj) is types.DictType

#判断是否为tuple [1,2,3]
def IsTuple(varObj):

    return type(varObj) is types.TupleType

#判断是否为List [1,3,4]
def IsList(varObj):

    return type(varObj) is types.ListType

#判断是否为布尔值 True
def IsBoolean(varObj):

    return type(varObj) is types.BooleanType

#判断是否为货币型 1.32
def IsCurrency(varObj):

    #数字是否为整数或浮点数
    if IsFloat(varObj) and IsNumber(varObj):
        #数字不能为负数
        if varObj >0:
            return isNumber(currencyObj)
            return False
    return True

#判断某个变量是否为空 x
def IsEmpty(varObj):

    if len(varObj) == 0:
        return True
    return False

#判断变量是否为None None
def IsNone(varObj):

    return type(varObj) is types.NoneType# == "None" or varObj == "none":

#判断是否为日期格式,并且是否符合日历规则 2010-01-31
def IsDate(varObj):

    if len(varObj) == 10:
        rule = '(([0-9]{3}[1-9]|[0-9]{2}[1-9][0-9]{1}|[0-9]{1}[1-9][0-9]{2}|[1-9][0-9]{3})-(((0[13578]|1[02])-(0[1-9]|[12][0-9]|3[01]))|((0[469]|11)-(0[1-9]|[12][0-9]|30))|(02-(0[1-9]|[1][0-9]|2[0-8]))))|((([0-9]{2})(0[48]|[2468][048]|[13579][26])|((0[48]|[2468][048]|[3579][26])00))-02-29)$/'
        match = re.match( rule , varObj )
        if match:
            return True
        return False
    return False

#判断是否为邮件地址
def IsEmail(varObj):

    rule = '[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$'
    match = re.match( rule , varObj )

    if match:
        return True
    return False

#判断是否为中文字符串
def IsChineseCharString(varObj):

    for x in varObj:
        if (x >= u"\u4e00" and x<=u"\u9fa5") or (x >= u'\u0041' and x<=u'\u005a') or (x >= u'\u0061' and x<=u'\u007a'):
           continue
        else:
           return False
    return True


#判断是否为中文字符
def IsChineseChar(varObj):

    if varObj[0] > chr(127):
       return True
    return False

#判断帐号是否合法 字母开头,允许4-16字节,允许字母数字下划线
def IsLegalAccounts(varObj):

    rule = '[a-zA-Z][a-zA-Z0-9_]{3,15}$'
    match = re.match( rule , varObj )

    if match:
        return True
    return False

#匹配IP地址
def IsIpAddr(varObj):

    rule = '\d+\.\d+\.\d+\.\d+'
    match = re.match( rule , varObj )

    if match:
        return True
    return False



if __name__=='__main__':
    print 'IsDate:',IsDate('2010-01-31')
    print 'IsNone:',IsNone(None)
    print 'IsEmpty:',IsEmpty('1')
    print 'IsCurrency:',IsCurrency(1.32)
    print 'IsList:',IsList([1,3,4])
    print 'IsTuple:',IsTuple([1,3,4])
    print 'IsDict:',IsDict({'a1':'1','a2':'2'})
    print 'IsFloat:',IsFloat(1.2)
    print 'IsString:',IsString('string')
    print 'IsNumber:',IsNumber(15)
    print 'IsEmail:',IsEmail('sgicer@163.com')
    print 'IsChineseChar:',IsChineseChar(u'啊')
    print 'IsChineseCharString:',IsChineseCharString(u'啊倒萨')
    print 'IsLegalAccounts:',IsLegalAccounts('alan_z')
    print 'IsIpAddr:',IsIpAddr('127.1110.0.1')
    pass

浏览:351次  回复:2次 分类: python

icokou相关的一些工具代码,做个记录

2010-12-14 14:12:47

#! /usr/bin/env python
#coding=utf-8
import time
import datetime
from datetime import date

#计算生肖
def ChineseZodiac(year):
     return u'猴鸡狗猪鼠牛虎兔龙蛇马羊'[year%12]

#计算星座
def Zodiac(month, day):
    n = (u'摩羯座',u'水瓶座',u'双鱼座',u'白羊座',u'金牛座',u'双子座',u'巨蟹座',u'狮子座',u'处女座',u'天秤座',u'天蝎座',u'射手座')
    d = ((1,20),(2,19),(3,21),(4,21),(5,21),(6,22),(7,23),(8,23),(9,23),(10,23),(11,23),(12,23))
    return n[len(filter(lambda y:y<=(month,day), d))%12]

#分离文件名和扩展名
# ex071107.log.1.exe
def GetFileNameAndExt(filename):
    import os
    (filepath,tempfilename) = os.path.split(filename);
    (shotname,extension) = os.path.splitext(tempfilename);
    return shotname,extension

#获取客户端IP
def GetClientIp(requestMETA):
    return requestMETA['REMOTE_ADDR']

#获取人性化的时间:
#GetFriendlyTime(datetime)
def GetFriendlyTime(ts):
    delta = datetime.datetime.now() - ts

    dateTimeDict = {}
#    if delta.days >= 365:
#        return u'%d 年前' % (delta.days / 365)
#    elif delta.days >= 30:
        #return u'%d 个月前' % (delta.days / 30)
    if delta.days > 0:
        dateTimeDict['friendlyTime'] = False
        dateTimeDict['content'] = ts
        return dateTimeDict
    #print 'delta.days',delta.days
    elif delta.seconds < 60:
        dateTimeDict['friendlyTime'] = True
        dateTimeDict['content'] = u"%d 秒前" % delta.seconds
        return dateTimeDict
        #return u"%d 秒前!" % delta.seconds
    elif delta.seconds < 60 * 60:
        dateTimeDict['friendlyTime'] = True
        dateTimeDict['content'] = u"%d 分钟前" % (delta.seconds / 60)
        return dateTimeDict
        #return u"%d 分钟前" % (delta.seconds / 60)
    else:
        dateTimeDict['friendlyTime'] = True
        dateTimeDict['content'] = u"%d 小时前" % (delta.seconds / 60 / 60)
        return dateTimeDict

        #return u"%d 小时前" % (delta.seconds / 60 / 60)


def MakeThumb(path, sizes=(75, 32, 16)):
    """
    缩略图生成程序 by Neil Chen
    sizes 参数传递要生成的尺寸,可以生成多种尺寸
    """
    base, ext = os.path.splitext(path)
    try:
        im = Image.open(path)
    except IOError:
        return
    mode = im.mode
    if mode not in ('L', 'RGB'):
        if mode == 'RGBA':
            # 透明图片需要加白色底
            alpha = im.split()[3]
            bgmask = alpha.point(lambda x: 255-x)
            im = im.convert('RGB')
            # paste(color, box, mask)
            im.paste((255,255,255), None, bgmask)
        else:
            im = im.convert('RGB')

    width, height = im.size
    if width == height:
        region = im
    else:
        if width > height:
            delta = (width - height)/2
            box = (delta, 0, delta+height, height)
        else:
            delta = (height - width)/2
            box = (0, delta, width, delta+width)
        region = im.crop(box)

    for size in sizes:
        filename = base + "_" + "%sx%s" % (str(size), str(size)) + ".jpg"
        thumb = region.resize((size,size), Image.ANTIALIAS)
        thumb.save(filename, quality=100) # 默认 JPEG 保存质量是 75, 不太清楚。可选值(0~100)

if __name__=='__main__':

    birthday = date(1985, 11, 10)
    print 'ChineseZodiac:',ChineseZodiac(birthday.year)
    print 'Zodiac:',Zodiac(birthday.month,birthday.day)
    print 'GetFileNameAndExt:',GetFileNameAndExt('ex071107.log.1.exe')

浏览:156次  回复:0次 分类: python django

用python让qq2010和360和平共处,原理不多说,看代码

2010-11-4 11:11:21

#! /usr/bin/env python
#coding=utf-8
import os
import time
import shutil
import stat

#获取系统环境变量
def GetLocalAppDataPath():
    if os.environ['APPDATA']:
        return os.environ['APPDATA']
    if os.environ['LOCALAPPDATA']:
    #系统环境变量
        return os.environ['LOCALAPPDATA'].replace('\\Local','')

#获取操作系统类型 很弱智
def GetOsType(appDataPath):

    if appDataPath[1:8] == ':\Users':
        return 'win7'
    else:
        return 'winxp'

def CopyFolderOs(sFolder,tFolder):
    sourcePath = sFolder
    destPath = tFolder
    for root, dirs, files in os.walk(sourcePath):

        #figure out where we're going
        dest = destPath + root.replace(sourcePath, '')

        #if we're in a directory that doesn't exist in the destination folder
        #then create a new folder
        if not os.path.isdir(dest):
            os.mkdir(dest)
            print 'Directory created at: ' + dest

        #loop through all files in the directory
        for f in files:

            #compute current (old) & new file locations
            oldLoc = root + '\\' + f
            newLoc = dest + '\\' + f

            if not os.path.isfile(newLoc):
                try:
                    shutil.copy2(oldLoc, newLoc)
                    print 'File ' + f + ' copied.'
                except IOError:
                    print 'file "' + f + '" already exists'

def RemoveFolderOs(sourceDir,localAppDataPath):
    for root, dirs, files in os.walk(sourceDir):
        for f in files:
            os.unlink(os.path.join(root, f))
        for d in dirs:
            shutil.rmtree(os.path.join(root, d))

    os.chdir(localAppDataPath)
    os.system(r'rd SafeBase /Q')





if __name__ == '__main__':

    #本地应用程序数据路径
    localAppDataPath = GetLocalAppDataPath()
    #获取操作系统类型
    osType = GetOsType(localAppDataPath)
    if osType == 'win7':
        localAppDataPath += '\Roaming\Tencent\QQ'
    if osType == 'winxp':
        localAppDataPath += '\Tencent\QQ'
    print localAppDataPath
    sourceDir = localAppDataPath + '\SafeBase'
    targetDir = localAppDataPath + '\SafeBaseBak'
    if os.path.exists(targetDir) == False:
        os.mkdir(targetDir)

    CopyFolderOs(sourceDir,targetDir)
    print u'bakup files Successful!'
    os.chdir(sourceDir)
    print os.getcwd()

    #os.system(r'attrib %s\*.* -r -a -s -h  /S /D'%sourceDir)
    #os.system(r'cd %s'%sourceDir)
    oscmd = r'attrib -r -a -s -h *.* /S /D'
    os.system(oscmd)
    print oscmd
    RemoveFolderOs(sourceDir,localAppDataPath)
    #RemoveFolderOs(sourceDir)
    print u'delete SafeBase Successful!'
    f = file(localAppDataPath+'\SafeBase', 'w') # open for 'w'riting
    f.write(u'sb 360,qq!\n') # write text to file
    f.close() # close the file
    print u'all Successful!'

浏览:221次  回复:0次 Tags: python qq 360 分类: python

django 1.2开启CsrfViewMiddleware之后 提交数据 IO Error解决一例

2010-10-1 00:10:37

django1.2之后的版本默认开启了CSRF防护的中间件(CsrfViewMiddleware),不清楚CSRF的概念请自行了解。 我之前有写过一篇介绍应对django1.2.1默认开启CsrfViewMiddleware表单提交出现的问题,见这里http://tidepal.appspot.com/?p=10001.

最近两天在折腾icokou系统的图片上传问题,首先是头像上传,其次是得有一个支持批量图片上传的功能。

为了用户体验,肯定考虑是用AJAX提交,但是这就带来了和CSRF产生冲突的问题,昨天刚开始我用的是轻量级的jquery.ajax.upload上传文件,即出现了IO Error问题,百事不得其解,正好有人曾经推荐过uploadfly,我下载之后运行过它的php版本,确实挺不错,很适合我批量上传文件的需求。但是在将uploadify整合到django中又出现了IO Error.因为一开始我就被误导了,以为是django的media配置方面出现的问题,所以导致整合不成功,一直纠结于uploadify整合到django的细节里去了。昨天搞到4,5点,始终没有解决这个问题,没办法只有先睡觉了。

今天一起来,我考虑是不是uploadify组件本身是否存在问题,遂换了另外一个swfUpload,在公司的机器上实验,同样是整合到django里,结果是一蹴而就,没有半点波折就成功的实现了AJAX模式下的上传文件,欣喜持续到回家,在家里使用白天的成果,还是照样出现IO error。当时我就泪流满面了,回想了一下公司和家里的django环境,公司用的是1.1.1,家里用的是1.2.1,配置上区别就在于默认启用了CsrfViewMiddleware。

于是去掉了CsrfViewMiddleware配置,果然正常,但是为了系统的安全性,我不可能去掉CsrfViewMiddleware,于是继续思考解决办法。google了很多资料,最终在http://www.johnberns.com/2010/07/08/using-valums-jquery-ajax-upload-with-django-1-2/找到了答案。使用@csrf_exempt  为视图手动添加一个免除保护的装饰,测试代码如下。

from django.http import HttpResponse
from django.shortcuts import render_to_response
import time
from django.contrib.csrf.middleware import csrf_exempt

@csrf_exempt
def manual(request):
    if request.method == 'POST':
        for field_name in request.FILES:
            uploaded_file = request.FILES[field_name]
            uploadFileNameExt =  uploaded_file.name.split('.')[1]
            print uploadFileNameExt
            uploadFileName = time.strftime('%Y%m%d%H%M%S',time.localtime(time.time()))

            print uploadFileName
            fullFileName = uploadFileName+'.'+uploadFileNameExt
            destination_path = 'media/uploads/%s' % (fullFileName)
            destination = open(destination_path, 'wb+')
            for chunk in uploaded_file.chunks():
                destination.write(chunk)
            destination.close()

        # indicate that everything is OK for SWFUpload
        return HttpResponse("/site_media/uploads/%s"%fullFileName)

    else:
        # show the upload UI
        return render_to_response('swfupload/manual.html')

至此,困扰了我2天的问题得以解决,在保证开启CsrfViewMiddleware的情况下继续使用AJAX提交表单。以下是测试上传头像的效果图。

 

浏览:2264次  回复:0次 Tags: django CsrfViewMiddleware AJAX POST 分类: python django

django 对字段进行 Avg Sum Count Max Min StdDev Variance 计算

2010-09-28 01:09:20
要用到django的Sum统计某些字段的数值总和,官方文档里没找到,其实是文档太浩瀚无边了,我没找到.随即搜索类似的开源代码,找到一篇,顺手做个记录,便于查询,用到了aggregate和annotate,支持对多个字段分别进行运算,最终返回一个字典,很酷!然后,我也顺利的搜索到了django官方文档的解决方案,您为什么总是来得这么迟啊!http://docs.djangoproject.com/en/dev/topics/db/aggregation/
(..More)
浏览:520次  回复:0次 Tags: django Avg Sum Count Max Min StdDev Variance 分类: django