예제 #1
0
파일: lostab.py 프로젝트: lostab/log
	def post(self):
		key = self.request.get('key')
		if users.is_current_user_admin() and key:
			try:
				post = Post.all().order("-__key__").filter('__key__ =', db.Key(key)).get()
				if post:
					title = self.request.get('title').strip()
					content = self.request.get('content').strip()
					if content:
						post.title = title
						post.content = content
						post.put()
						mempost = memcache.get("post-" + key)
						if mempost is not None:
							memcache.replace("post-" + key, post)
						memposts = memcache.get("posts")
						if memposts is not None:
							for item in memposts:
								if item.key().__str__() == key:
									item.title = title
									item.content = content
							memcache.replace("posts", memposts)
					self.redirect('/post/' + key)
				else:
					self.redirect('/')
			except:
				self.redirect('/')
		else:
			self.redirect('/')
예제 #2
0
파일: app.py 프로젝트: rodaebel/sillyswarm
    def post(self, path):
        """Sends the HANDSHAKE_RECEIVED state to the particular user."""

        message = websocket.Message(self.request.POST)

        players = memcache.get(PLAYERS_INDEX_KEY)

        present_players = []

        if players:
            present_players = players[:]
            players.append(path)
            memcache.replace(PLAYERS_INDEX_KEY, players)
        else:
            players = [path]
            memcache.set(PLAYERS_INDEX_KEY, players)

        memcache.set(path, [])

        response = {'state': HANDSHAKE_RECEIVED, 'player': path}
        websocket.send_message([message.socket], simplejson.dumps(response))

        player_data = memcache.get_multi(present_players)

        for player in player_data:
            if not player_data[player]:
                continue

            x, y = player_data[player]
            response = {'state': PLAYER_MOVED, 'player': player, 'x': x, 'y': y}

            websocket.send_message([message.socket], simplejson.dumps(response))
예제 #3
0
def set(path, body, content_type, indexed=True, **kwargs):
  """Sets the StaticContent for the provided path.
  
  Args:
    path: The path to store the content against.
    body: The data to serve for that path.
    content_type: The MIME type to serve the content as.
    indexed: Index this page in the sitemap?
    **kwargs: Additional arguments to be passed to the StaticContent constructor
  Returns:
    A StaticContent object.
  """
  content = StaticContent(
      key_name=path,
      body=body,
      content_type=content_type,
      indexed=indexed,
      **kwargs)
  content.put()
  memcache.replace(path, db.model_to_protobuf(content).Encode())
  try:
    now = datetime.datetime.now().replace(second=0, microsecond=0)
    eta = now.replace(second=0, microsecond=0) + datetime.timedelta(seconds=65)
    if indexed:
      deferred.defer(
          utils._regenerate_sitemap,
          _name='sitemap-%s' % (now.strftime('%Y%m%d%H%M'),),
          _eta=eta)
  except (taskqueue.TaskAlreadyExistsError, taskqueue.TombstonedTaskError), e:
    pass
예제 #4
0
파일: static.py 프로젝트: detro/bloggart
def set(path, body, content_type, indexed=True, last_modified=None, type=TYPE_POST, **kwargs):
  import static
  """Sets the StaticContent for the provided path.

  Args:
    path: The path to store the content against.
    body: The data to serve for that path.
    content_type: The MIME type to serve the content as.
    indexed: Index this page in the sitemap?
    type: The type of StaticContent (a post? a page? an index?...).
    **kwargs: Additional arguments to be passed to the StaticContent constructor
  Returns:
    A StaticContent object.
  """
  if last_modified is None:
    last_modified = datetime.datetime.now(utils.tzinfo()).replace(second=0, microsecond=0)
  defaults = {
    "last_modified": last_modified,
  }
  defaults.update(kwargs)
  content = StaticContent(
      key_name = path,
      body = body,
      content_type = content_type,
      indexed = indexed,
      type = static.TYPE_HOME if path == '/' else type,
      **defaults);
  content.put()
  memcache.replace(path, db.model_to_protobuf(content).Encode())

  if indexed:
    regenerate_sitemap()

  return content
예제 #5
0
파일: base.py 프로젝트: NeoRazorX/pystream
 def put_machine(self, machine, ip6 = False, upnp = False):
     if machine != '':
         os = 'unknown'
         for aux in ['bsd', 'darwin', 'mac', 'iphone', 'ipad', 'ipod', 'windows', 'linux', 'android']:
             if machine.lower().find( aux ) != -1:
                 os = aux
         if self.machines is None:
             self.machines = [[os, 1, 0, 0, 0]]
             if ip6:
                 self.machines[0][2] += 1
             elif upnp:
                 self.machines[0][3] += 1
             memcache.add('all_pystream_machines', self.machines)
         else:
             found = False
             for m in self.machines:
                 if m[0] == os:
                     m[1] += 1
                     if ip6:
                         m[2] += 1
                     elif upnp:
                         m[3] += 1
                     found = True
             if not found:
                 self.machines = [[os, 1, 0, 0, 0]]
                 if ip6:
                     self.machines[0][2] += 1
                 elif upnp:
                     self.machines[0][3] += 1
             memcache.replace('all_pystream_machines', self.machines)
예제 #6
0
파일: tasks.py 프로젝트: mayanks/smstweet
  def fetch_status(self,type,key_name, url):
    phone = self.request.get('phone')    
    tuser = TwitterUser.get_by_phonenumber(phone)
    if tuser == None:
      logging.warning("Could not fetch tuser based on phone number %s",phone)
      return

    since_id = memcache.get("%s%s" % (key_name,tuser.user))
    if not since_id:
      since_id = -1
      memcache.add("%s%s" % (key_name,tuser.user), since_id)

    client = OAuthClient('twitter', self)
    try:
      info = client.get(url, 'GET', (200,401,403), tuser, since_id=since_id, count = 10)
      if 'error' in info:
        logging.warning("%s Fetch failed for %s because of %s" % (type,tuser.user, info['error']))
      elif len(info) > 0:
        logging.debug("fetched %d %s's for %s" % (len(info), type,tuser.user))
        memcache.replace("%s%s" % (key_name,tuser.user), info[0]['id'])
        if type == 'DM':
          for dm in info: TweetDM.create(dm['sender_screen_name'],tuser.user, dm['text'], dm['created_at'], dm['id'])
        else:
          for dm in info: TweetMention.create(dm['user']['screen_name'],tuser.user, dm['text'], dm['created_at'], dm['id'])
        #endif
      #endif
    except (urlfetch.DownloadError, ValueError), e:
      logging.warning("%s: could not be fetched. %s " % (type,e))
예제 #7
0
	def post(self):
		if users.is_current_user_admin():
			title = self.request.get('title').strip()
			content = self.request.get('content').strip()
			if content:
				post = Post()
				post.title = title
				post.content = content
				post.put()

				posts = memcache.get("posts")
				if posts is not None:
					posts.insert(0, post)
					posts.pop()
					memcache.replace("posts", posts)

				recentposts = memcache.get("recentposts")
				if recentposts is not None:
					recentposts.insert(0, post)
					recentposts.pop()
					memcache.replace("recentposts", recentposts)

				key = post.key().__str__()
				self.redirect('/post/' + key)
		self.redirect('/')
예제 #8
0
파일: queue.py 프로젝트: ericof/facefriends
 def post(self):
     uid = self.request.get("user_id")
     start = self.request.get("start",0)
     end = self.request.get("end",0)
     user = FBUser.get_by_key_name(uid)
     logging.debug('User ID (%s) Start (%s) End(%s)' % (str(user.id),str(start),str(end)))
     data = memcache.get('friends_%s' % str(user.id))
     if not data:
         graph = facebook.GraphAPI(user.access_token)
         friends = graph.get_connections(user.id, "friends")
         friends = friends.get('data',[])
     else:
         friends = data
     try:
         friends = self._storeFriends(friends,int(start),int(end),user.key())
         actualFriends = user.friends
         friends = [f.key() for f in friends if f.key() not in actualFriends]
         actualFriends.extend(friends)
         user.friends = actualFriends
         user.put()
     except DeadlineExceededError:
         self.response.clear()
         self.response.set_status(500)
         self.response.out.write("This operation could not be completed in time...")
     finally:
         queues = memcache.get('queues_%s' % str(user.id))
         queues.remove((int(start),int(end)))
         if queues:
             # Ainda temos uma fila?
             memcache.replace('queues_%s' % str(user.id),queues)
         else:
             logging.debug('Adding friendsFriendsUp')
             taskqueue.add(queue_name='friendsFriendsUp' ,url='/queue/queueFriends', params={'user_id':user.id,})
예제 #9
0
파일: app.py 프로젝트: rodaebel/sillyswarm
    def post(self, path):
        """Broadcasts all moves."""

        message = websocket.Message(self.request.POST)

        data = simplejson.loads(message.body)

        state = data.get("state")
        x = data.get('x')
        y = data.get('y')

        players = memcache.get(PLAYERS_INDEX_KEY) or []

        if state == PLAYER_MOVED:
            replace = {path: [x, y]}

            if path not in players:
                players.append(path)
                replace[PLAYERS_INDEX_KEY] = players

            memcache.replace_multi(replace)
            response = {'state': PLAYER_MOVED, 'player': path, 'x': x, 'y': y}

        elif state == PLAYER_LEFT or not data:
            memcache.delete(path)

            if path in players:
                players.remove(path)
                memcache.replace(PLAYERS_INDEX_KEY, players)

            response = {'state': PLAYER_LEFT, 'player': path}

        websocket.broadcast_message(simplejson.dumps(response))
예제 #10
0
파일: base.py 프로젝트: NeoRazorX/pystream
 def put_page(self, page_type, num=1):
     if self.pages is None:
         is_cached = False
         self.pages = {
             'streams': 0,
             'requests': 0,
             'comments': 0,
             'pylinks': 0
         }
     else:
         is_cached = True
     if page_type == 'stream':
         self.pages['streams'] += num
         memcache.delete('random_pages')
     elif page_type == 'request':
         self.pages['requests'] += num
         memcache.delete('random_pages')
     elif page_type == 'comment':
         self.pages['comments'] += num
     elif page_type == 'pylinks':
         self.pages['pylinks'] += num
     else:
         logging.warning('Unknown page type!')
     if is_cached:
         memcache.replace('new_pages', self.pages)
     else:
         memcache.add('new_pages', self.pages)
예제 #11
0
def set_profile(current_user, profile_options):
	profile = Profile.get_or_insert(current_user, options={"foo":"bar"})
	profile.options = profile_options
	profile.put()
	memkey = "profile:%s" % (current_user)
	memcache.replace(memkey, profile, 90000)
	return profile.options
예제 #12
0
파일: static.py 프로젝트: yesudeep/cmc
def set(path, body, content_type, indexed=True, **kwargs):
    """Sets the StaticContent for the provided path.
  
  Args:
    path: The path to store the content against.
    body: The data to serve for that path.
    content_type: The MIME type to serve the content as.
    indexed: Index this page in the sitemap?
    **kwargs: Additional arguments to be passed to the StaticContent constructor
  Returns:
    A StaticContent object.
  """

    import pickle

    if "name" in kwargs:
        kwargs["body_meta"] = pickle.dumps({"File_Name": kwargs["name"], "Content_Type": content_type})
    else:
        kwargs["body_meta"] = pickle.dumps({"Content_Type": content_type})
    content = StaticContent(key_name=path, body=body, content_type=content_type, indexed=indexed, **kwargs)
    content.put()
    memcache.replace(path, db.model_to_protobuf(content).Encode())
    # try:
    #   now = datetime.datetime.now().replace(second=0, microsecond=0)
    #   eta = now.replace(second=0, microsecond=0) + datetime.timedelta(seconds=65)
    #   #if indexed:
    #   #  deferred.defer(
    #   #      utils._regenerate_sitemap,
    #   #      _name='sitemap-%s' % (now.strftime('%Y%m%d%H%M'),),
    #   #      _eta=eta)
    # except (taskqueue.TaskAlreadyExistsError, taskqueue.TombstonedTaskError), e:
    #   pass
    return content
예제 #13
0
파일: base.py 프로젝트: NeoRazorX/pystream
 def put_search(self, query=''):
     if len(query) > 1:
         found = False
         if self.searches is None:
             self.searches = [[query.lower(), 1]]
             memcache.add('previous_searches', self.searches)
         else:
             for s in self.searches:
                 if s[0] == self.valid_tag_name(query):
                     s[1] += 1
                     found = True
             if not found:
                 self.searches.append([self.valid_tag_name(query), 1])
             # short
             if self.searches:
                 aux = []
                 elem = None
                 while self.searches != []:
                     for s in self.searches:
                         if not elem:
                             elem = s
                         elif s[1] > elem[1]:
                             elem = s
                     aux.append(elem)
                     self.searches.remove(elem)
                     elem = None
                 self.searches = aux
             memcache.replace('previous_searches', self.searches)
예제 #14
0
파일: base.py 프로젝트: NeoRazorX/pystream
 def page2search(self, link, text, page_type, date, all_tags = None):
     if all_tags is None:
         all_tags = memcache.get('previous_searches')
     found_tags = []
     if link != '' and text != '' and all_tags is not None:
         logging.info('Searching tags for link: ' + link)
         for tag in all_tags:
             if re.search('\\b'+tag[0]+'\\b', text.lower()) or re.search('\\b'+tag[0].replace('_', ' ')+'\\b', text.lower()):
                 found_tags.append(tag[0])
                 logging.info('Link: ' + link + ' found tag: ' + tag[0])
                 tag_links = memcache.get('search_' + tag[0])
                 if len(text) > 200:
                     element = [link, page_type, date, text[:200]+'...']
                 else:
                     element = [link, page_type, date, text]
                 if tag_links is None:
                     memcache.add('search_' + tag[0], [element])
                 else:
                     found = False
                     for ele in tag_links:
                         if element[0] == ele[0]:
                             ele[3] = element[3]
                             found = True
                     if not found:
                         tag_links.append(element)
                     memcache.replace('search_' + tag[0], tag_links)
     return found_tags
예제 #15
0
def updateUserPrefs(prefs):
    logging.debug("<-------------- updateUserPrefs --------------->")

    currentUser = users.get_current_user()
    userPrefs = UserPrefs.all().filter("user = "******"datastore maintenance")
            return MAINTENANCE_MSG

    # Create a new message
    if prefs.nickname:
        msg = NICK_MSG % (getNickname(), prefs.nickname)
        chat = ChatMsg.createMsg(msg, "chat.getUsers", isAnon=True)
        sendToXmpp(chat) 
        # Update memcache
        memcache.replace(currentUser.email(), prefs.nickname, 60*60*24)
        userPrefs.nickname = prefs.nickname

    # Add the user preferences dynamically
    objEntity = Get(userPrefs.key())
    for k, v in prefs.iteritems():
        objEntity[k] = v
    Put(objEntity)
예제 #16
0
def update_successful_runtime():
    now = datetime.datetime.utcnow().replace(
        microsecond=0).isoformat()  # noqa: E501

    if memcache.get(key='last_successful_runtime'):
        memcache.replace(key='last_successful_runtime', value=now)
    else:
        memcache.add(key='last_successful_runtime', value=now)
예제 #17
0
파일: data.py 프로젝트: tobbee/skojjt
 def delete(self):
     self.key.delete()
     troopmeeting_keys = memcache.get(
         Meeting.__getMemcacheKeyString(self.troop))
     if troopmeeting_keys is not None:
         troopmeeting_keys.remove(self.key)
         memcache.replace(Meeting.__getMemcacheKeyString(self.troop),
                          troopmeeting_keys)
예제 #18
0
 def testReplaceInNamespace(self):
     """Tests replacing doesn't replace from the wrong namespace."""
     self.assertTrue(memcache.set(self.key1, self.value1, namespace='ns1'))
     self.assertTrue(
         memcache.replace(self.key1, self.value2, namespace='ns1'))
     self.assertFalse(
         memcache.replace(self.key1, self.value3, namespace='ns2'))
     self.assertEqual(self.value2, memcache.get(self.key1, namespace='ns1'))
예제 #19
0
파일: data.py 프로젝트: tobbee/skojjt
 def delete(self):
     self.key.delete()
     troopperson_keys = memcache.get(
         TroopPerson.__getMemcacheKeyString(self.troop))
     if troopperson_keys is not None:
         troopperson_keys.remove(self.key)
         memcache.replace(TroopPerson.__getMemcacheKeyString(self.troop),
                          troopperson_keys)
예제 #20
0
파일: tools.py 프로젝트: proming/gaemarks
def addSession(key, value):
  """
    Add a key's value, expiration in time
  """
  oldValue = memcache.get(key)
  if oldValue is None:
    memcache.add(key, value, timeout)
  else:
    memcache.replace(key, value, timeout)
예제 #21
0
def set_image_keys_in_memcache():
    memcache.flush_all()
    image_key_list = []
    query = ImageInfo.all(keys_only=True)
    for result in query:
        if result.name() is not None:
            image_key_list.append(result.name())
    memcache.replace(IMAGE_KEY_LIST_MEMCACHE, image_key_list)
    return image_key_list
예제 #22
0
    def voTunes_sendRegId(self, request):
        playlist = memcache.get(request.id)
        current_reg_ids = playlist.reg_ids
        if (request.reg_id not in current_reg_ids):
            current_reg_ids.append(request.reg_id)
            memcache.replace(request.id, playlist)

        #votes = memcache.get(request.id).votes
        return Place(reg_ids=current_reg_ids)
예제 #23
0
파일: load_quiz.py 프로젝트: jamslevy/PQ
	def load_quiz_items(self, profNames, token):
		self.session = self.get_quiz_session(token)
		self.load_quiz = LoadQuiz();
		proficiencies = self.get_proficiencies(profNames)
		quiz_items = self.get_quiz_items(proficiencies)
		if len(self.session['quiz_items']) < 1: return False
		else: self.session['current_item'] = self.session['quiz_items'][0]
		memcache.replace(token, self.session, 60000)
		return proficiencies
예제 #24
0
파일: load_quiz.py 프로젝트: jamslevy/PQ
	def next_quiz_item(self, token):
		self.session = self.get_quiz_session(token)
		try: 
		    next_item = self.session['quiz_items'].pop()
		    self.session['current_item'] = next_item
		    #del next_item['key'] - is this necessary?  
		except IndexError: return False #no items left
		memcache.replace(token, self.session, 60000)
		return next_item
예제 #25
0
    def testReplaceItem(self):
        """Adds and replaces a cached item."""

        first = "Little pig, little pig, let me come in!"
        second = "Not by the hair on my chinny-chin-chin!"
        memcache.set('first', first)
        assert memcache.get('first') == first
        memcache.replace('first', second)
        assert memcache.get('first') == second
예제 #26
0
    def testReplaceItem(self):
        """Adds and replaces a cached item."""

        first = "Little pig, little pig, let me come in!"
        second = "Not by the hair on my chinny-chin-chin!"
        memcache.set('first', first)
        assert memcache.get('first') == first
        memcache.replace('first', second)
        assert memcache.get('first') == second
예제 #27
0
 def addMenuId(self,id):
          rem = memcache.get("rem")
          if rem is not None :
              rem.current_model_menu_id = id
              if not memcache.add("rem",rem):
                  memcache.replace("mc_error",True)
             
          m = RestaurantEditModel.get_by_key_name(users.get_current_user().user_id())
          m.current_model_menu_id = id
          m.put()
예제 #28
0
 def addCatName(self,name):
          rem = memcache.get("rem")
          if rem is not None :
              rem.current_cat_name = name
              if not memcache.add("rem",rem) :
                  memcache.replace("mc_error",True)
                  
          m = RestaurantEditModel.get_by_key_name(users.get_current_user().user_id())
          m.current_cat_name = name
          m.put()
예제 #29
0
파일: tags.py 프로젝트: NeoRazorX/ubuntufaq
 def actualizar(self):
     for t in self.alltags:
         try:
             nume = len(self.pendientes.get(t[0], []))
             if nume > 0:
                 t[1] = nume
                 memcache.delete("busqueda_" + t[0])
         except:
             pass
     memcache.replace("all-tags", self.alltags)
예제 #30
0
def add_playlist_to_cache(request):
    temp_playlist = generatePlaylist(request.id)
    data = memcache.get(request.id)
    if data is None:
        q = gen_playlist(request.id, temp_playlist, [])
        memcache.add(request.id, q)
    else:
        q = gen_playlist(request.id, temp_playlist, data.reg_ids)
        memcache.replace(request.id, q)
    return q
예제 #31
0
 def getRestaurantEditModel(self):
   rem = memcache.get("rem")
   if rem is not None and not RestaurantEdit.mc_err(self):
          return rem
   else:
          r = RestaurantEditModel.get_by_key_name(users.get_current_user().user_id())
          if not memcache.add("rem", r):
              memcache.replace("mc_error",True)
              
   return r
예제 #32
0
파일: data.py 프로젝트: DivineAlfons/skojjt
	def create(troop_key, person_key, isLeader):
		tp = TroopPerson(id=TroopPerson.getid(troop_key, person_key),
			troop=troop_key,
			person=person_key,
			leader=isLeader)
		troopperson_keys = memcache.get(TroopPerson.__getMemcacheKeyString(troop_key))
		if troopperson_keys is not None and tp.key not in troopperson_keys:
			troopperson_keys.append(tp.key)
			memcache.replace(TroopPerson.__getMemcacheKeyString(troop_key), troopperson_keys)
		return tp
예제 #33
0
 def addRestaurantEditModel(self):
      
              rem = RestaurantEditModel(key_name= users.get_current_user().user_id())
              rem.current_model_edit_id = '0'
              rem.current_model_name = '0'
              rem.current_model_menu_id = '0'
              rem.current_model_menu_name = '0'
              rem.current_cat_id = '0'
              rem.current_cat_name = '0'
              
              
              x = memcache.get("rem")
              #set the mc_error hack
              memcache.add("mc_error",False)
              if x is not None:
                  if not memcache.replace("rem",rem) :
                      memcache.replace("cache_error_occured",True)
                      memcache.replace("mc_error",True)
              else :
                  if not memcache.add("rem",rem) :
                      memcache.replace("cache_error_occured",True)
                      memcache.replace("mc_error",True)
              
                      
              rem.put()
예제 #34
0
 def resetMenuName(self):
    rem = memcache.get("rem")
    if rem is not None and not RestaurantEdit.mc_err(self) :
        rem.current_model_menu_name = '0'
        if not memcache.replace("rem",rem) :
            memcache.replace("mc_error",True)
    
    m = RestaurantEditModel.get_by_key_name(users.get_current_user().user_id())
    if m:
        m.current_model_menu_name = '0'
        m.put()
예제 #35
0
 def voTunes_getNextSong(self, request):
     curr_playlist = memcache.get(request.id)
     currentPlace = curr_playlist.get_max_song()
     temp_playlist = generatePlaylist(request.id)
     q = gen_playlist(request.id, temp_playlist, curr_playlist.reg_ids)
     memcache.replace(request.id, q)
     reg_ids = memcache.get(request.id).reg_ids
     if (len(reg_ids) > 0):
         sendMessageToClients(messageType='Playlist-Updated',
                              registration_ids=reg_ids)
     return Song(pos=currentPlace.pos)
예제 #36
0
파일: m256.py 프로젝트: map256/map256
def downloaderror_update():
    recent = memcache.get('urlfetch_count')

    if recent is None:
        memcache.add('urlfetch_count', 1, 150)
    else:
        recent = recent + 1
        memcache.replace('urlfetch_count', recent, 150)

    if recent > 5:
        notify_admin('High error rate on URL fetches')
예제 #37
0
def Enqueue(av, str, sender):
    cachekey = 'queuestring-%s' % (av)
    cachedata = memcache.get(cachekey)
    if cachedata is not None:
        #append
        cachedata += '%s|%s\n' % (str, sender)
        memcache.replace(cachekey, cachedata, 3600, 0)
    else:
        #just set
        memcache.add(cachekey, '%s|%s\n' % (str, sender), 3600)
    cmd = QueuedCommand2(av=av, str=str, sender=sender, ts=time.time())
    cmd.put()
예제 #38
0
def Enqueue(av, str, sender):
    cachekey = 'queuestring-%s' % (av)
    cachedata = memcache.get(cachekey)
    if cachedata is not None:
        #append
        cachedata += '%s|%s\n' % (str, sender)
        memcache.replace(cachekey, cachedata, 3600, 0)
    else:
        #just set
        memcache.add(cachekey, '%s|%s\n' % (str, sender), 3600)
    cmd = QueuedCommand2(av = av, str = str, sender = sender, ts = time.time())
    cmd.put()
예제 #39
0
파일: views.py 프로젝트: T-SOP/electko
def update(request):
	info = memcache.get('news')
	news = newsInfo()
	response_data= {}
	if info is not None:
		response_data['status']= 'update'
		memcache.replace('news',news)
	else:
		response_data['status']= 'create'
		memcache.add('news',news)

	return HttpResponse(json.dumps(response_data),content_type="application/json")
예제 #40
0
	def get(self, note, index, active):
		self.response.headers.add_header("Access-Control-Allow-Origin", "*")
		
		parametro = get_param()
		music = json.loads(parametro.music)
		music[note][int(index)] = active == "1"
		parametro = Parametro.get_or_insert(key_name="PARAMETRO")
		parametro.music = json.dumps(music)
		parametro.put()
		
		memcache.replace("parametro", parametro)
		self.response.out.write("OK USER")
예제 #41
0
 def __delitem__(self, k):
     """
     Implement the 'del' keyword
     """
     self.__validate_key(k)
     sessdata = self.get(keyname = k)
     if sessdata == None:
         raise KeyError, str(k)
     db.delete(sessdata)
     if k in self.cache:
         del self.cache[k]
     if k in self.memcache:
         del self.memcache[k]
         memcache.replace("sid-"+self.sid, self.memcache, self.session_expires)
예제 #42
0
 def put(self):
     ndb.Model.put(self)
     if not memcache.replace('beevoteuser_by_id_%s' % self.key.id(),
                             self,
                             time=600):  # @UndefinedVariable
         memcache.add('beevoteuser_by_id_%s' % self.key.id(),
                      self,
                      time=600)  # @UndefinedVariable
     if not memcache.replace('beevoteuser_by_user_id_%s' % self.user_id,
                             self,
                             time=600):  # @UndefinedVariable
         memcache.add('beevoteuser_by_user_id_%s' % self.user_id,
                      self,
                      time=600)  # @UndefinedVariable
예제 #43
0
 def post(self, post):
     form = PageForm(data=self.request.POST)
     if form.is_valid():
         post = form.save(commit=False)
         post.path = utils.format_page_path(post)
         page_key = post.path[len(config.page_path):]
         """construct a new PagePost for persistence"""
         content = models.PagePost(key_name=page_key,
                                   path=post.path,
                                   title=post.title,
                                   body=post.body)
         content.put()
         memcache.replace(page_key, db.model_to_protobuf(content).Encode())
         self.render_to_response("published.html", "admin", {'post': post})
     else:
         self.render_form(form)
예제 #44
0
 def __getitem__(self, k):
     """ 
     __getitem__ is necessary for this object to emulate a container.
     """
     if k in self.cache:
         return pickle.loads(str(self.cache[k]))
     if k in self.memcache:
         return self.memcache[k]
     data = self.get(k)
     if data:
         self.cache[k] = data.content
         self.memcache[k] = pickle.loads(data.content)
         memcache.replace("sid-"+self.sid, self.memcache, self.session_expires)
         return pickle.loads(data.content)
     else:
         raise KeyError, str(k)
예제 #45
0
 def put(self, keyname = None, content = None):
     """
     put applies a keyname/value pair in SessionsData for the session.
     """
     self.__validate_key(keyname)
     if content == None:
         raise ValueError, "You must pass content for the sessions data."
     sessdata = self.get(keyname = keyname)
     if sessdata == None:
         sessdata = _AppEngineUtilities_SessionsData()
         sessdata.sid = self.ds.sid 
         sessdata.keyname = keyname 
     sessdata.content = pickle.dumps(content)
     self.cache[keyname] = pickle.dumps(content)
     self.memcache[keyname] = content
     memcache.replace("sid-"+self.sid, self.memcache, self.session_expires)
     sessdata.put()
예제 #46
0
    def auth(self):
        ret = False
        loginkey = self.request.cookies.get('loginkey', None)
        if loginkey:
            self.user_id = memcache.get(loginkey)
            ret = memcache.replace(loginkey, self.user_id, 3600 * 24)

        return ret
예제 #47
0
    def voTunes_voteForSong(self, request):
        id = request.id
        up = request.up
        down = request.down
        playlist = memcache.get(request.id)
        if (down is not None):
            playlist.votes[down] -= 1
        if up is not None:
            playlist.votes[up] += 1
        memcache.replace(id, playlist)
        android_playlist = convert_playlist(playlist.songs, playlist.votes)
        reg_ids = memcache.get(request.id).reg_ids
        if (len(reg_ids) > 0):
            sendMessageToClients(messageType='Votes-Updated',
                                 registration_ids=reg_ids)

        return android_playlist
예제 #48
0
파일: mem_cache.py 프로젝트: ankur22/here
    def update_events_cache(cls, guestbook_name):
        pages = cls.__get_from_cache(guestbook_name)
        page_count = len(pages)
        greetings = ["na"]
        total_elms = 0

        while greetings is not None and len(greetings) > 0:
            [offset, limit, total_elms] = cls.__get_limits(pages, page_count)

            greetings = dao.get_events_from_datastore(guestbook_name, offset,
                                                      limit)

            if greetings is not None and len(greetings) > 0:
                data = []
                for greeting in greetings:
                    obj = cls.__convert_to_response_ready_obj(greeting)
                    data.append(obj)

                    # Only add new values for images to memcache
                    cls.add(cls.__thumbnail_cache_name(greeting.key.urlsafe()),
                            greeting.thumbnail)
                    cls.add(cls.__photo_cache_name(greeting.key.urlsafe()),
                            greeting.photo)

                # Update existing memcache value
                if len(pages) > 0 and len(
                        pages[page_count - 1]["data"]) < ELMS_IN_PAGE:
                    pages[page_count - 1]["data"].extend(data)
                    memcache.replace(pages[page_count - 1]["page_name"],
                                     pages[page_count - 1])
                else:  # Add new memcache value
                    page = {
                        "page_name":
                        cls.__get_page_name(guestbook_name, page_count),
                        "next_page_name":
                        cls.__get_page_name(guestbook_name, page_count + 1),
                        "data":
                        data
                    }
                    page_count = page_count + 1
                    pages.append(page)
                    cls.add(page["page_name"], page)

        memcache.replace("total_elms", total_elms)
        return pages
def _Refresh(name, num_shards):
    """Transactional helper to refresh the value for a given sharded timestamp.

  Also takes a number of shards to determine which shard will be used.

  Args:
      name: The name of the timestamp.
      num_shards: How many shards to use.
  """
    index = random.randint(0, num_shards - 1)
    shard_key_string = SHARD_KEY_TEMPLATE.format(name, index)
    timestamp = GeneralTimestampShard.get_by_id(shard_key_string)
    if timestamp is None:
        timestamp = GeneralTimestampShard(id=shard_key_string)
    timestamp.timestamp = datetime.utcnow()
    timestamp.put()
    # Memcache replace does nothing if the name is not a key in memcache
    memcache.replace(name, timestamp.timestamp)
예제 #50
0
파일: base.py 프로젝트: lelecenter/pystream
 def put_firewalled_machine(self, machine):
     if machine != '':
         os = 'unknown'
         for aux in ['bsd', 'darwin', 'mac', 'iphone', 'ipad', 'ipod', 'windows', 'linux', 'android']:
             if machine.lower().find( aux ) != -1:
                 os = aux
         if self.machines is None:
             self.machines = [[os, 1, 0, 0, 1]]
             memcache.add('all_pystream_machines', self.machines)
         else:
             found = False
             for m in self.machines:
                 if m[0] == os:
                     m[4] += 1
                     found = True
             if not found:
                 self.machines = [[os, 1, 0, 0, 1]]
             memcache.replace('all_pystream_machines', self.machines)
예제 #51
0
		def replace_memFeed(self, memFeed):
				try:
						if not memcache.replace("memFeed", memFeed, time=3600):
								memcache.add("memFeed", memFeed, 3600)
						logging.info('replace the memcache now!')
						return True
				except Exception, data:
						logging.error('the memcache is not this key, and error is  %s', data)
						return False
예제 #52
0
파일: base.py 프로젝트: lelecenter/pystream
 def put_download(self, os):
     if self.downloads is None:
         self.downloads = {
             'windows': 0,
             'linux': 0,
             'mac': 0,
             'unknown': 0
         }
         is_cached = False
     else:
         is_cached = True
     if os in ['windows', 'linux', 'mac']:
         self.downloads[os] += 1
     else:
         self.downloads['unknown'] += 1
     if is_cached:
         memcache.replace('all_downloads', self.downloads)
     else:
         memcache.add('all_downloads', self.downloads)
예제 #53
0
    def post(self):
        if users.is_current_user_admin():
            title = self.request.get('title').strip()
            content = self.request.get('content').strip()
            if content:
                post = Post()
                post.title = title
                post.content = content
                post.put()

                posts = memcache.get("posts")
                if posts is not None:
                    posts.insert(0, post)
                    posts.pop()
                    memcache.replace("posts", posts)

                key = post.key().__str__()
                self.redirect('/post/' + key)
        self.redirect('/')
예제 #54
0
파일: data.py 프로젝트: DivineAlfons/skojjt
	def getOrCreate(troop_key, name, datetime, duration):
		m = Meeting.get_by_id(Meeting.getId(datetime, troop_key), use_memcache=True)
		if m != None:
			if m.name != name or m.duration != duration:
				m.name = name
				m.duration = duration
				m.put()
		else:
			m = Meeting(id=Meeting.getId(datetime, troop_key),
				datetime=datetime,
				name=name,
				troop=troop_key,
				duration=duration
				)
		troopmeeting_keys = memcache.get(Meeting.__getMemcacheKeyString(troop_key))
		if troopmeeting_keys is not None and m.key not in troopmeeting_keys:
			troopmeeting_keys.append(m.key)
			memcache.replace(Meeting.__getMemcacheKeyString(troop_key), troopmeeting_keys)
		return m
예제 #55
0
    def StoreOrUpdateInCache(self, filename, data):
        """Store data in the cache.

    Store a piece of data in the memcache. Memcache has a maximum item size of
    1*10^6 bytes. If the data is too large, fail, but log the failure. Future
    work will consider compressing the data before storing or chunking it

    Args:
      filename: the name of the file to store
      data: the data of the file

    Returns:
      None
    """
        try:
            if not memcache.add("%s%s" % (self.CACHE_PREFIX, filename), data):
                memcache.replace("%s%s" % (self.CACHE_PREFIX, filename), data)
        except (ValueError), err:
            logging.warning("Data size too large to cache\n%s" % err)
예제 #56
0
 def unregister_waiter(self, request):
     RESPONSE = Response()
     result = memcache.replace(request.restaurant, "empty")
     if result is False:
         RESPONSE.response = memcache.add(request.restaurant, "empty")
         logging.info("Instance died")
     else:
         RESPONSE.response = True
     logging.info("Token unregistered for " + request.restaurant)
     return RESPONSE
예제 #57
0
 def SetRecentPlayerList(self, list):
     list.data = json.dumps(list.obj)
     logging.debug('SetRecentPlayerList ' + list.data)
     if list.put():
         if not memcache.replace('recent_player_list', list, config.memcache['longtime']):
             logging.warning('Data set memcache for recent_player_list failed!')
         return True
     else:
         logging.warn("set db fail")
     return False
예제 #58
0
 def testSetAfterDeleteWithTimeout(self):
   """Tests that set after a delete with timeout will work."""
   self.assertFalse(memcache.set(self.key1, self.value1))
   self.assertEqual(None, memcache.get(self.key1))
   self.assertEqual(memcache.DELETE_NETWORK_FAILURE,
                    memcache.delete(self.key1, seconds=5))
   self.assertEqual(None, memcache.get(self.key1))
   self.assertFalse(memcache.add(self.key1, self.value1))
   self.assertFalse(memcache.replace(self.key1, self.value1))
   self.assertEqual(None, memcache.get(self.key1))
   self.assertFalse(memcache.set(self.key1, self.value1))
   self.assertEqual(None, memcache.get(self.key1))
예제 #59
0
 def post(self):
     greeting = self.request.get('entry')
     greetings = memcache.get('entries')
     if greetings is not None:
         greetings.append(greeting)
         if not memcache.replace('entries', greetings):
             logging.error('Memcache replace failed.')
     else:
         greetings = [greeting]
         if not memcache.set('entries', greetings):
             logging.error('Memcache set failed.')
     self.redirect('/')
예제 #60
0
파일: base.py 프로젝트: lelecenter/pystream
 def tags2cache(self, tags, all_tags = None):
     if tags:
         # first check because may be not provided
         if all_tags is None:
             all_tags = memcache.get('previous_searches')
         if all_tags is None:
             all_tags = []
             for tag in tags:
                 if len(tag) > 1:
                     all_tags.append([self.valid_tag_name(tag), 0])
             memcache.add('previous_searches', all_tags)
         else:
             for ntag in tags:
                 found = False
                 for otag in all_tags:
                     if self.valid_tag_name(ntag) == otag[0]:
                         found = True
                 if not found and len(ntag) > 1:
                     all_tags.append([self.valid_tag_name(ntag), 0])
             memcache.replace('previous_searches', all_tags)
         return all_tags
     else:
         return []