关于mongodb创建数据库失败的问题

至尊小宝 2017-10-27 05:57:57
# -*-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]


上面的代码我是想做一个缓存机制来的,可为什么运行的时候连MongoCache对象都不能创建?
错误提示:
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'
...全文
704 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
至尊小宝 2017-10-27
  • 打赏
  • 举报
回复
还有一个问题,为什么在创建数据库对象是传入的expires=timedelta(days=30)就会在时间到了自动删除数据库记录?这个索引有什么关系?难道索引参数设置的时间就是索引的有效期吗?

1,747

社区成员

发帖
与我相关
我的任务
社区描述
MongoDB相关内容讨论区
社区管理员
  • MongoDB社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧