公司有一个perl脚本,通过mid获取数据库中相应的timestamp,然后在把timestamp分成年,月,日,在组成路径,获取 mid相应的email文件。由于我要开发的另一款python程序需要用到这个程序,但又不想像命令一样执行这个perl程序,所以改写成了python的类。在脚本中直接调用即可。或者在网页上操作。
这里主要用到了两个主要的技术:
1. MySQLdb模块
2. datetime模块
这两个模块在这个脚本里有一写需要注意的问题。现在写下来:
1. 如果mid在数据库中找不到,那么会返回什么值?
2. datetime有许多的类和方法,如何归类他们?
-
#!/usr/bin/env python
-
import os
-
import sys
-
import datetime
-
from getopt import getopt as argvs
-
import MySQLdb
-
-
class MSG(object):
-
def _querydb(self, table, mids):
-
query="SELECT message_id, add_timestamp FROM messages_%s WHERE message_id IN (%s)" % (table, ",".join(mids))
-
db=MySQLdb.connect(host='xxxxxx-xxxxxx.xxxxx.xxxxxxx.com',\
-
user='reader', passwd='xxxxx!t', db='xxxxxx')
-
cursor=db.cursor()
-
cursor.execute(query)
-
results=list(cursor.fetchall())
-
return results
-
-
def getPath(self, mids):
-
results=[]
-
midspath=[]
-
results.extend(self._querydb('ham', mids))
-
results.extend(self._querydb('spam', mids))
-
results.extend(self._querydb('unknown', mids))
-
# modify 'add_timestamp' and input into another list
-
for result in results:
-
# transfer timestamp to date
-
add_time=datetime.datetime.utcfromtimestamp(result[1])
-
midpath="/xxx/xxxxx/xxxxxx/xxxxxxxx/%04d/%02d/%02d/%02d/%s.abc" % (add_time.year, add_time.month, add_time.day,
-
add_time.hour, result[0])
-
midspath.append((result[0], midpath))
-
return midspath
-
-
def _usage():
-
print "mid2path.py -h mids..."
-
sys.exit()
-
-
if __name__=='__main__':
-
opts, args = argvs(sys.argv[1:], "h")
-
for m, n in opts:
-
if m=='-h':
-
_usage()
-
if not args:
-
_usage()
-
-
msg=MSG()
-
midspath=msg.getPath(args)
-
for mid, loc in midspath:
-
print mid,":",loc
阅读(7628) | 评论(0) | 转发(0) |