1,747
社区成员
发帖
与我相关
我的任务
分享
# -*-coding:utf-8 -*-
from datetime import datetime,timedelta, date
from pymongo import MongoClient
class MongoCache:
def __init__(self,client=None,expires=timedelta(days=30)):
self.client=MongoClient('localhost',27017) if client is None else client
self.db=client.cache#这个位置出错啊!!!!!
self.db.webpage.create_index('timestamp',expiresAfterSeconds=expires.total_seconds())
print expires.total_seconds()
def __getitem__(self,url):
record=self.db.webpage.find_one({'id':url})
if record:
return record['result']
else:
raise KeyError(url+' doed not exit')
def __setitem__(self,url,result):
record={'result':result,'timestamp':datetime.utcnow()}
self.db.webpage.update({'_id':url},{'$set':record},upsert=True)
if __name__=='__main__':
url='http://baidu.com'
cache=MongoCache(expires=timedelta())
result={'html':'test test test!!!'}
cache[url]=result
print cache[url]
Traceback (most recent call last):
File "D:\Project\core3\src\coremongotest1.py", line 25, in <module>
cache=MongoCache(expires=timedelta())
File "D:\Project\core3\src\coremongotest1.py", line 8, in __init__
self.db=client.cache
AttributeError: 'NoneType' object has no attribute 'cache'