修正 displayTime 返回 str 导致的编码错
[gaetalk.git] / utils.py
blob68527888bf2e338f9ce3aa86bf615c650e6bb760
1 #!/usr/bin/env python2
2 # vim:fileencoding=utf-8
4 import re
5 import unicodedata
6 import time
7 import config
9 from google.appengine.api import memcache
11 timeParser = re.compile(r'^(\d+)([smhd])?$')
12 linkre = re.compile(r' <https?://(?!i.imgur.com/)[^>]+>')
13 linkjsre = re.compile(r' <javascript:[^>]+>')
14 timeUnitMap = {
15 '': 1,
16 's': 1,
17 'm': 60,
18 'h': 3600,
19 'd': 86400,
21 timeZhUnitMap = (60, 60, 24, 36524)
22 timeZhUnits = (u'秒', u'分', u'小时', u'天')
24 def filesize(size):
25 '''将 数字 转化为 xxKiB 的形式'''
26 units = 'KMGT'
27 left = abs(size)
28 unit = -1
29 while left > 1100 and unit < 3:
30 left = left / 1024
31 unit += 1
32 if unit == -1:
33 return '%dB' % size
34 else:
35 if size < 0:
36 left = -left
37 return '%.1f%siB' % (left, units[unit])
39 def strftime(time, timezone, show_date=False):
40 '''将时间转换为字符串,考虑时区,可能带日期'''
41 if not show_date:
42 format = '%H:%M:%S'
43 else:
44 format = '%m-%d %H:%M:%S'
45 return (time + timezone).strftime(format)
47 def parseTime(s):
48 '''将 3s,5d,1h,6m 等转换成秒数'''
49 m = timeParser.match(s)
50 if m is None:
51 raise ValueError('not a time')
52 n = int(m.group(1))
53 u = m.group(2)
54 if u is None:
55 return n
56 else:
57 return n * timeUnitMap[u]
59 def displayTime(t):
60 '''友好地显示时间'''
61 r = []
62 for i in timeZhUnitMap:
63 r.append(t % i)
64 t = t // i
65 if t == 0:
66 break
67 return u''.join(reversed(map(lambda x, y: unicode(x)+y if x else u'', r, timeZhUnits)))
69 def checkNick(nick):
70 '''判断一个昵称是否合法'''
71 if len(nick.encode('utf-8')) > config.nick_maxlen:
72 return False
73 for i in nick:
74 if not unicodedata.category(i).startswith('L') and i not in config.allowedSymbolInNick:
75 return False
76 return True
78 def removelinks(msg):
79 '''清除多余的链接文本'''
80 links = linkre.findall(msg)
81 if len(links) != 1:
82 msg = linkre.sub('', msg)
83 msg = linkjsre.sub('', msg)
84 return msg
86 class MemLock:
87 def __init__(self, name):
88 self.name = name
90 def require(self):
91 while memcache.get(self.name):
92 time.sleep(0.001)
93 memcache.set(self.name, True)
95 def release(self):
96 memcache.set(self.name, False)