def test_expr(self): key = "expr" self.assertEquals(None, cache.get(key)) cache.set(key, u"ABC", 1) self.assertEquals(u"ABC", cache.get(key)) time.sleep(1.2) self.assertEquals(None, cache.get(key))
def test_incr(self): key = "inc" self.assertEquals(None, cache.get(key)) cache.set(key, 123) self.assertEquals(123, cache.get(key)) cache.incr(key) self.assertEquals(124, cache.get(key)) cache.incr(key, 10) self.assertEquals(134, cache.get(key))
def get_widget_instances(sidebar, use_cache=True): ''' Get widget instances of the given sidebar. Args: sidebar: index of the sidebar, 0-9. use_cache: True if fetch from cache first. Default to True. Returns: List of widget instances, as well as each instance has: settings: instance settings as dict, widget_class: widget class object. ''' def _load(): instances = WidgetInstance.all().filter('sidebar =', sidebar).order('display_order').fetch(100) widgets = get_installed_widgets() r = [] for instance in instances: if instance.name in widgets: instance.widget_class = widgets[instance.name] instance.settings = get_widget_instance_settings(instance, instance.widget_class) instance.widget = instance.widget_class() for k, v in instance.settings.iteritems(): instance.widget[k] = v r.append(instance) return r if use_cache: return cache.get('__widget_sidebar_%s__' % sidebar, _load) return _load()
def get_site_settings(use_cache=True): ''' Get site as a site object which has attribute of 'title', 'subtitle', etc. Args: use_cache: True if use cache, default to True. ''' if use_cache: return cache.get(SITE_GROUP, _get_from_store, 3600) return _get_from_store()
def get_navigation(use_cache=True): ''' Get navigation as a list contains ('title', 'url'). Args: use_cache: True if use cache, default to True. ''' if use_cache: return cache.get(NAV_GROUP, _get_from_store, 3600) return _get_from_store()
def get_navigation(use_cache=True): """ Get navigation as a list contains ('title', 'url'). Args: use_cache: True if use cache, default to True. """ if use_cache: return cache.get(NAV_GROUP, _get_from_store, 3600) return _get_from_store()
def get_count(name): ''' Retrieve the value for a given sharded counter. Args: name: the name of the counter Returns: Integer value ''' total = cache.get(CACHE_KEY_PREFIX + name) if total is None: total = 0 for counter in ShardedCounter.all().filter('name =', name).fetch(1000): total += counter.count cache.set(CACHE_KEY_PREFIX + name, str(total)) return total return int(total)
def is_too_many_retweets(rt): try: tid = str(rt.retweeted_status.id) except KeyError: logging.debug('-'*80 + 'KeyError' + rt.text) tid = str(rt.id) #print '----%s----%s----%s' % (rt, rt.retweeted_status.id, (tid)) times = cache.get(tid) if times: logging.info("%s: %s times %s" % (tid, times, rt.retweeted_status.text)) if times > 20: return True else: cache.incr(tid) else: cache.set(tid, '1') return False
def test_cache(self): key1 = "key1" key2 = "key2" self.assertEquals(None, cache.get(key1)) self.assertEquals(None, cache.get(key2)) cache.set(key1, "abc") cache.set(key2, ["x", "y", "z"]) self.assertEquals("abc", cache.get(key1)) self.assertEquals(["x", "y", "z"], cache.get(key2)) cache.delete(key1) cache.delete(key2) self.assertEquals(None, cache.get(key1)) self.assertEquals(None, cache.get(key2))
def _get_weather(city): if not city: return r'{"code":"500","Message":"Missing Input: city"}' data = cache.get("city-%s" % city) if data: logging.info("got data from cache") web.header("X-Cache", "Hit from cache") return data # check city: cities = list(db.select("city", where="yahoo_code=$code", vars=dict(code=city))) if not cities: return r'{"code":"500","Message":"Invalid Input: city"}' c = cities[0] w = c.yahoo_code logging.info("fetch from yahoo weather...") url = "http://weather.yahooapis.com/forecastjson?w=%s&u=c" % w resp = urllib2.urlopen(url) if resp.code == 200: logging.info("begin fetch...") data = json.loads(resp.read()) data["city"] = c.name cond = data["forecast"][0]["condition"] codes = _get_weather_code(cond) data["forecast"][0]["code"] = codes[0] data["forecast"][0]["condition"] = codes[1] data["forecast"][0]["image"] = codes[2] cond = data["forecast"][1]["condition"] codes = _get_weather_code(cond) data["forecast"][1]["code"] = codes[0] data["forecast"][1]["condition"] = codes[1] data["forecast"][1]["image"] = codes[2] # cache it, but first calculate expires time: now = datetime.now() t = datetime(now.year, now.month, now.day) delta = now - t exp = 86400 - delta.seconds # makes it expires in midnight (24:00) if exp > 3600: exp = 3600 logging.info("fetched and cache for %d seconds." % exp) json_data = json.dumps(data) cache.set("city-%s" % city, json_data, exp) web.header("X-Cache", "Miss from cache") return json_data return None
def GET(self): # 获取URL参数: oauth_token = web.input().get('oauth_token') oauth_verifier = web.input().get('oauth_verifier') # 使用oauth_token查表获取上一步保存的oauth_token_secret: oauth_token_secret = cache.get(oauth_token.encode('ascii')) # 构造完整的request token: request_token = OAuthToken(oauth_token, oauth_token_secret, oauth_verifier) # 用request token获取access token: client = APIClient(app_key=APP_KEY, app_secret=APP_SECRET, token=request_token) access_token = client.get_access_token() # 通过access token调用一个API获取用户uid信息: client = APIClient(APP_KEY, APP_SECRET, access_token) account = client.account__verify_credentials() uid = str(account.id) # 保存uid和access token以后使用: self.save_access_token_to_db(uid, access_token.oauth_token, access_token.oauth_token_secret) try: # 发表一条授权成功的微博 client.post.statuses__update(status="本微博帐号已成为一个基于OPENTree0应用的树洞,欢迎大家来此吐槽生活。树洞的使用方法请见OPENTree0主页:http://opentree0.sinaapp.com/") except HTTPError: logging.error("重复发送微博。") raise web.found('/success')