#!/usr/bin/env python 
#-*- coding: utf-8 -*- 

"""
restore memory from database, if memory failed
"""
# @author chengdujin
# @contact chengdujin@gmail.com
# @created Aug. 23, 2013


import sys 
reload(sys) 
sys.setdefaultencoding('UTF-8')
sys.path.append("..")

from bson.objectid import ObjectId
from config.settings import Collection, db
from config.settings import rclient
from datetime import datetime, timedelta
from scraper import memory

# CONSTANTS
from config.settings import MEMORY_RESTORATION_DAYS
from config.settings import LANGUAGES


def _get_expiration(updated):
    """
    Compute expiration time
    """
    if not updated:
        return 0

    deadline = datetime.utcfromtimestamp(updated) + timedelta(days=MEMORY_RESTORATION_DAYS)
    time_left = deadline - datetime.now()
    return time_left.days * 60 * 60 * 24 + time_left.seconds


def restore():
    """
    if memory failed, restore items from database
    """
    try:
        # check if redis is alive
        rclient.ping()
        # flushall existing data
        rclient.flushall()
    except ConnectionError:
        print 'Redis is down! Cannot recover memory data from database'
        return None

    print '=== RESTORE MEMORY FROM DATABASE ==='
    collection_names = db.collection_names()
    for collection_name in collection_names:
        if collection_name != 'system.indexes' and collection_name != 'feeds':
            col = Collection(db, collection_name)

            # find valid time to filter out expired items
            current_utc_time_posix = calendar.timegm(time.gmtime())
            active_datetime = datetime.utcfromtimestamp(current_utc_time_posix) - timedelta(days=MEMORY_RESTORATION_DAYS)
            active_posix = calendar.timegm(active_datetime.timetuple())

            items = col.find({'updated': {'$gte': active_posix}}).sort('updated', -1)
            for item in items:
                expiration = _get_expiration(float(item['updated']))
                memory.update(item, expiration)


if __name__ == "__main__":
    restore()

@@ -291,16 +291,32 @@
 bjectId%0A
+import calendar%0A
 from con
@@ -453,16 +453,28 @@
 t memory
+%0Aimport time
 %0A%0A# CONS
@@ -575,31 +575,24 @@
 S%0A%0A%0Adef 
-_get
 _expir
-ation
+ed
 (updated
@@ -1250,16 +1250,29 @@
 SE ==='%0A
+    try:%0A    
     coll
@@ -1308,24 +1308,28 @@
 names()%0A    
+  
+  
 for collecti
@@ -1357,16 +1357,20 @@
 _names:%0A
+    
         
@@ -1452,16 +1452,20 @@
         
+ 
+   
 col = Co
@@ -1495,16 +1495,20 @@
 _name)%0A%0A
+    
         
@@ -1569,16 +1569,20 @@
         
+    
 current_
@@ -1629,16 +1629,20 @@
 time())%0A
+    
         
@@ -1763,24 +1763,28 @@
             
+    
 active_posix
@@ -1844,16 +1844,20 @@
         
+   
+ 
 items = 
@@ -1930,24 +1930,28 @@
             
+    
 for item in 
@@ -1973,16 +1973,20 @@
         
+    
 expirati
@@ -1994,23 +1994,16 @@
 n = 
-_get
 _expir
-ation
+ed
 (flo
@@ -2023,16 +2023,20 @@
 ted'%5D))%0A
+    
         
@@ -2075,16 +2075,178 @@
 ration)%0A
+        print '=== MEMORY SUCCESSFULLY RESTORED ==='%0A    except Exception as k:%0A        print 'Memory restoring blocked due to %5B%25s%5D' %25 str(k)%0A        return None%0A
 %0A%0Aif __n

Add necessary imports and Renamed inner method name