好的,这是我的问题:
我有一个我经常调用的函数(每秒几次),以及一个应该在函数中计算的变量old_date
。
但似乎这个变量只在首次调用函数时计算一次,然后保持相同的值。
这是功能:
def can_push(date):
"""
Check if the last data was pushed more than TIMEFRAME ago
:param date: string, date of the new data
TIMEFRAME = datetime.timedelta(seconds=1)
DB = MongoClient(HOST, PORT).database
DATE_FMT = '%Y-%m-%dT%H:%M:%S.%fZ'
"""
# If collection doesn't exist, we create it and return True
out = False
# Get MongoDB collection
coll = DB.coll
# Date of the new data (got through websocket)
new_date = datetime.strptime(date, DATE_FMT)
# Date of the last data pushed in DB
cursor = coll.find().sort('{date:-1}').limit(1)
old_date = cursor[0]['date']
print old_date # Format is okay, but date is too old
if (new_date - old_date) > TIMEFRAME:
out = True
# gc.collect()
del old_date
return out
我尝试del old_date
,但它似乎无法运作。
阅读this后,我尝试使用gc.collect()
,但我对Python不是很熟悉,所以我不确定它的真正用途(并且它不会似乎也有效。)
如果我连接到MongoDB shell,我实际上可以检查数据库中推送的最后数据是否比old_date
显示的更年轻。
有没有人知道在功能结束时强行删除old_date
的其他方法?
Python版本:2.7.12
内核:Ubuntu 16.04
答案 0 :(得分:0)
好的,错误是错字,我的错。
应该是:
cursor = coll.find().sort("date", -1).limit(1)
我确信我的请求是正确的,因为它在MongoDB shell中有效。
很抱歉花时间感谢您的帮助!