Ejemplo n.º 1
0
def request_accepted_counter():
    try:
        if Counter:
            counterval = client.get(session['insta_username']) 
			# Counter.query.filter_by(insta_username=session['insta_username']).first()
    except:
        time.sleep(0.10)
        ctr = "0"
    # except sqlite3.OperationalError as e:
    #     print('[-] Sqlite operational error: {} Retrying...'.format(e))
    #     ctr = "0"
    # except sqlite3.InterfaceError as e:
    #     print('[-] Sqlite interface error: {} Retrying...'.format(e))
    #     ctr = "0"
    # except sqlite3.Error:
    #     # time.sleep(0.10)
    #     ctr = "0"  # str(session["request_accepted_counter_demo"])

    if counterval is not None:
        ctr = client.get(session['insta_username']) 
		# str(counterval.counts)

    counterval = None
#    client = memcache.Client([('127.0.0.1', 11211)])
    ctr = client.get(session['insta_username'])

    if ctr == None:
        ctr = "0"
    print("counter: ", ctr)
    return ctr
Ejemplo n.º 2
0
 def drill(self, path, choices, complete=False):
   '''Perform a data item drilldown.
   
   If all necessary choices are specified, returns the UID of the data item;
   otherwise, returns the next choice that needs to be made in the form of a dict
   with keys "name" and "choices". (The "choices" item is an array of permitted
   values.)
   
   If the "complete" argument is true, we raise an Error if the specified choices
   are incomplete. In this case the return value will always be the UID.
   
   Results are cached using memcache.
   
   Typical applications will not call this method directly: it is used internally
   by Profile.create_item(s). You could call it directly if you wanted to allow
   a user to specify data items interactively one choice at a time.
   '''
   choices_string = urllib.urlencode(choices)
   memcache_key = ";".join((self.server, path, choices_string, str(complete)))
   cached_result = memcache.get(memcache_key, namespace=MEMCACHE_NAMESPACE)
   if cached_result is not None:
     return cached_result
   
   result = self._drill(path, choices_string, complete)
   memcache.set(memcache_key, result, namespace=MEMCACHE_NAMESPACE)
   return result
Ejemplo n.º 3
0
 def get_user_cache(key):
   u = memcache.get(key)
   if u:
     user_id, last_login = u
   else:
     user_id, last_login = None, None
   return user_id, last_login
Ejemplo n.º 4
0
    def get(self, dive_id):
        dive = Dive.get_by_id(int(dive_id))
        if dive is None:
            error(self.response, 404)
            return

        # Cache stuff
        key = '%s-%d-%s' % (dive_id, len(dive.photos), dive.userid)
        self.response.etag = key
        request_etag = self.request.headers.get('If-None-Match', '""')[1:-1]
        if request_etag == key:
            self.response.status = 304
            return

        def response():
            related = dive.get_related()

            #TODO maybe other perks for different gasses?
            nitrox = len(filter(lambda x: x.get('O2','Air') not in ('Air', '--'), dive.dive_data['Cylinders'])) != 0
            template_values = {
                'nitrox': nitrox,
                'dive': dive,
                'related': related,
                'description': dive.dive_data['notes'].split('<br>')[0],
                'fake_thumb': html.random_image(),
                'profile': draw_profile(dive.dive_data.get('samples', []), 600, 400),
            }
            template = templater.get_template('templates/dive.html')
            return template.render(template_values)

        self.response.write(memcache.get(key, response))
Ejemplo n.º 5
0
 def get_user_cache(key):
     u = memcache.get(key)
     if u:
         user_id, last_login = u
     else:
         user_id, last_login = None, None
     return user_id, last_login
Ejemplo n.º 6
0
 def get_by_slug_querier(self, slug, querier):
     '''
     Obtiene un evento por su id, COMPRUEBA VISIBILIDAD, solo obtiene los publicos
     '''
     suggestion = memcache.deserialize_instances(memcache.get(
         '%sEVENT%s' % (memcache.version, slug)),
                                                 _search_class=self._klass)
     if suggestion is None:
         suggestion = self._klass.all().filter('slug =', slug).get()
         if suggestion is None:
             try:
                 suggestion = self.get_by_id(slug)
             except:
                 return None
         if suggestion is not None:
             if suggestion._is_private():
                 if not querier.is_authenticated():
                     return None
                 if suggestion.__class__.user.get_value_for_datastore(
                         suggestion) == querier.key():
                     return None
             elif suggestion._is_shared():
                 if not querier.is_authenticated():
                     return None
                 if not suggestion.user_invited(querier):
                     return None
             memcache.set('%sEVENT%s' % (memcache.version, slug),
                          memcache.serialize_instances(suggestion), 300)
             return suggestion
     return suggestion
Ejemplo n.º 7
0
def block_contacts(request):
    """
        Bloquea a un usuario para no recibirlo en la lista
        de amigos sugeridos
        
        Parametros en POST:
            userid: el id del usuario a bloquear
            
            :returns: boolean
    """
    if request.user.is_authenticated():
        userid = int(request.POST['userid'])
        if userid is not None:
            import memcache
            request.user.settings.blocked_friends_sug.append(userid)
            friends = memcache.get('%sfriends_to_%s' %
                                   (memcache.version, request.user.key()))
            if friends is not None and userid in friends:
                del friends[userid]
                memcache.set(
                    '%sfriends_to_%s' % (memcache.version, request.user.key()),
                    friends, 300)
            request.user.settings.put()
            return HttpResponse(simplejson.dumps(True),
                                mimetype="application/json")
    return HttpResponse(simplejson.dumps(True), mimetype="application/json")
Ejemplo n.º 8
0
def get_userprefs(user, clear=False):
    """
    Get the UserPrefs for the current user either from memcache or, if not
    yet cached, from the datastore and put it into memcache. Used by
    UserPrefs.from_user(user)
    """
    if not user:
        return user

    if user.federated_identity():
        key = "userprefs_fid_%s" % user.federated_identity()
    else:
        key = "userprefs_gid_%s" % user.user_id()

    # Clearing the cache does not return anything
    if clear:
        memcache.delete(key)
        logging.info("- cache cleared key: %s", key)
        return

    # Try to grab the cached UserPrefs
    prefs = memcache.get(key)
    if prefs:
        logging.info("- returning cached userprefs for key: %s", key)
        return prefs

    # If not cached, query the datastore, put into cache and return object
    prefs = models.UserPrefs._from_user(user)
    memcache.set(key, prefs)
    logging.info("cached userprefs key: %s", key)
    return prefs
Ejemplo n.º 9
0
    def get(self):
        #get 'avatar' is avatar_id
        #Add memcached here to improve the performence.
        usravatardata = memcache.get('img_useravatar' + self.request.get("avatar"))
        
        if usravatardata is not None:
            self.output_avatar(usravatardata, True)
        else:
            # Request it from BigTable
            AvatarUser = tarsusaUser.get_by_id(int(self.request.get("avatar")))          

            try:
                if AvatarUser.avatar:
                    if not memcache.set('img_useravatar' + self.request.get("avatar"), AvatarUser.avatar, 16384):
                        logging.error("Memcache set failed: When Loading avatar_image")
                    self.output_avatar(AvatarUser.avatar, False)
            except AttributeError:
                #Not found avatar in DB.
                avatardata = urlfetch.fetch("http://www.checknerds.com/img/default_avatar.jpg", headers={'Content-Type': "image/jpg"})
                if avatardata.status_code == 200:
                    avatardata = avatardata.content
                    memcache.set('img_useravatar' + self.request.get("avatar"), avatardata, 16384)
                    self.output_avatar(avatardata, False)
                else:
                    self.redirect("/img/default_avatar.jpg")
Ejemplo n.º 10
0
def videoExistsInMemcache(memcache, key):
    metadata = memcache.get('%s-metadata' % key)
    if metadata == None:
        return False
    chunkCount = struct.unpack('=L', metadata[:4])[0]
    for curChunk in xrange(chunkCount):
        if not memcache.touch('%s-%s' % (key, curChunk)):
            return False
    return True
Ejemplo n.º 11
0
 def get(cls,name):
     value = memcache.get('APP_Key_'+name)
     if not value:
         q = cls.query(cls.name == name).get()
         value = ''
         if q:
             value = q.value
         memcache.set('APP_Key_'+name,value)
     return value
Ejemplo n.º 12
0
def videoExistsInMemcache(memcache, key):
	metadata = memcache.get('%s-metadata' % key)
	if metadata == None:
		return False
	chunkCount = struct.unpack('=L', metadata[:4])[0]
	for curChunk in xrange(chunkCount):
		if not memcache.touch('%s-%s' % (key, curChunk)):
			return False
	return True
Ejemplo n.º 13
0
    def get(self):
        self.response.headers['Content-Type'] = 'text/html'
        self.response.headers['Cache-Control'] = 'max-age=259200'

        def response():
            template = templater.get_template('templates/manual_upload.html')
            return template.render({})

        self.response.write(
            memcache.get('manual_upload', response))
Ejemplo n.º 14
0
def request_accepted_count(num):
    # counter =client.get(session['insta_username'])
	# Counter.query.filter_by(insta_username=session['insta_username']).first()
    # client = memcache.Client([('127.0.0.1', 11211)])
    ctr = client.get(session['insta_username'])
    
    # if counter is not None:
    #    ctr = counter.counts 

    return render_template('request_accepted_count.html', num=ctr)
Ejemplo n.º 15
0
    def useNonce(self, server_url, timestamp, salt):
        if abs(timestamp - time.time()) > nonce.SKEW:
            return False

        key = self._nonceKey(server_url, timestamp, salt)

        result = memcache.get(key)
        if (result == None):
            return memcache.set(key, True, nonce.SKEW + 5)
        else:
            return False
Ejemplo n.º 16
0
 def _encode_img(self, file_path):
     """Returns image base64 string representation and makes a cache file"""
     import memcache
     filename   = file_path.rpartition(os.sep)[2]
     cache_file = "%s_cache" % file_path
     cached_image = memcache.get('%s%s' % (memcache.version, cache_file))
     if cached_image is None:
         image = open(file_path)
         cached_image = "data:image;base64,%s"%base64.b64encode(image)
         memcache.set('%s%s' % (memcache.version, cache_file), cached_image, 300)
     return cached_image
Ejemplo n.º 17
0
    def get(self):

        self.response.headers['Content-Type'] = 'text/html'
        self.response.headers['Cache-Control'] = 'max-age=14400'

        def response():
            template_values = {
                'photo_name': html.random_image(),
            }
            template = templater.get_template('templates/help.html')
            return template.render(template_values)
        self.response.write(memcache.get('help_page', response))
Ejemplo n.º 18
0
 def _encode_img(self, file_path):
     """Returns image base64 string representation and makes a cache file"""
     import memcache
     filename = file_path.rpartition(os.sep)[2]
     cache_file = "%s_cache" % file_path
     cached_image = memcache.get('%s%s' % (memcache.version, cache_file))
     if cached_image is None:
         image = open(file_path)
         cached_image = "data:image;base64,%s" % base64.b64encode(image)
         memcache.set('%s%s' % (memcache.version, cache_file), cached_image,
                      300)
     return cached_image
Ejemplo n.º 19
0
 def get_friends_to_follow(self, provider=None, rpc=False):
     import memcache
     friends = memcache.get('%sfriends_to_%s' %
                            (memcache.version, self.key()))
     if friends is None:
         friends_rpc = []  # lista de rpcs
         #RPC PARA FACEBOOK
         try:
             if provider is None or provider.lower() == 'facebook':
                 from geoauth.clients.facebook import FacebookFriendsRPC
                 fb_rpc = FacebookFriendsRPC()
                 friends_rpc.append(fb_rpc.fetch_friends(self))
         except:
             pass
         #RPC PARA TWITTER
         try:
             if provider is None or provider.lower() == 'twitter':
                 from geoauth.clients.twitter import TwitterFriendsRPC
                 tw_rpc = TwitterFriendsRPC()
                 friends_rpc.append(tw_rpc.fetch_friends(self))
         except:
             raise
             pass
         #RPC PARA GOOGLE
         try:
             if provider is None or provider.lower() == 'google':
                 from geoauth.clients.google import GoogleFriendsRPC
                 go_rpc = GoogleFriendsRPC()
                 friends_rpc.append(go_rpc.fetch_friends(self))
         except:
             pass
         friends_rpc = filter(None, friends_rpc)
         if rpc:
             return [fb_rpc, tw_rpc, go_rpc], friends_rpc
         raise NotImplementedError
         # TODO: SI NO RPC, PROCESAR TODO EN ESTA FUNCION
         for rpc in friends_rpc:
             rpc.wait()
         friends = {}  # diccionario con todos los amigos
         #los unimos en uno
         friends.update(fb_rpc.friends)
         friends.update(tw_rpc.friends)
         #friends.update(friends_google)
         if len(friends) > 0:
             if len(self.settings.blocked_friends_sug) > 0:
                 for k in friends.keys():
                     if k in self.settings.blocked_friends_sug:
                         del friends[k]
             memcache.set(
                 '%sfriends_to_%s' % (memcache.version, self.key()),
                 friends, 11235)
     return friends
Ejemplo n.º 20
0
 def get_by_id(self, id):
     import memcache
     try:
         id = long(id)
     except:
         return None
     place = memcache.deserialize_instances(memcache.get('%splace_%s' % (memcache.version, id)), _search_class=Place)
     if place is None:
         place = self._klass.get_by_id(id)
         if place is None:
             return None
         memcache.set('%splace_%s' % (memcache.version, id), memcache.serialize_instances(place), 300)
     return place
Ejemplo n.º 21
0
	def __str__(self):
		try:
			memcache_key = '%s:widget:%s:%s' % (self.handler.auth, self.gen_func_name, self.params)
			html = memcache.get(memcache_key)

			if html == None:
				html = self.gen_func(self.handler.template_values, self.params)
				if html == None:
					html = ''
				memcache.set(memcache_key, html)

			return html
		except Exception, e:
			return str(e)
Ejemplo n.º 22
0
def image_avatar(request, username):
    from georemindme.model_plus import memcache, version
    encoded_image = memcache.get('%s%s_avatarcachebase64' % (version, username))
    if encoded_image is None:
        import base64
        location = get_avatar(request, username)
        from google.appengine.api import urlfetch
        result = urlfetch.fetch(location['Location'])
        decoded_image = result.content
        encoded_image = "data:image;base64,%s" % base64.b64encode(result.content)
        memcache.set('%s%s_avatarcachebase64' % (version, username), encoded_image, 1123)
    else:
        decoded_image=base64.b64decode(encoded_image)
    return HttpResponse(decoded_image, mimetype="image/xyz")
Ejemplo n.º 23
0
def embedded_avatar(username):
    import memcache
    encoded_image = memcache.get('%s%s_avatarcachebase64' % (memcache.version, username))
    if encoded_image is None:
        from geouser.views import get_avatar
        try:
            image_url = get_avatar(None, username)
            from google.appengine.api import urlfetch
            result = urlfetch.fetch(image_url['Location'])
            encoded_image = "data:image;base64,%s" % base64.b64encode(result.content)
            memcache.set('%s%s_avatarcachebase64' % (memcache.version, username), encoded_image, 1123)
        except:
            return 'https://georemindme.appspot.com/static/facebookApp/img/no_avatar.png'
    return encoded_image
Ejemplo n.º 24
0
 def get_friends_to_follow(self, provider = None, rpc=False):
     import memcache
     friends = memcache.get('%sfriends_to_%s' % (memcache.version, self.key()))
     if friends is None:
         friends_rpc = [] # lista de rpcs
         #RPC PARA FACEBOOK
         try:
             if provider is None or provider.lower() == 'facebook':
                 from geoauth.clients.facebook import FacebookFriendsRPC
                 fb_rpc = FacebookFriendsRPC()
                 friends_rpc.append(fb_rpc.fetch_friends(self))
         except:
             pass
         #RPC PARA TWITTER
         try:
             if provider is None or provider.lower() == 'twitter':
                 from geoauth.clients.twitter import TwitterFriendsRPC
                 tw_rpc = TwitterFriendsRPC()
                 friends_rpc.append(tw_rpc.fetch_friends(self))
         except:
             raise
             pass
         #RPC PARA GOOGLE
         try:
             if provider is None or provider.lower() == 'google':
                 from geoauth.clients.google import GoogleFriendsRPC
                 go_rpc = GoogleFriendsRPC()
                 friends_rpc.append(go_rpc.fetch_friends(self))
         except:
             pass
         friends_rpc = filter(None, friends_rpc)
         if rpc:
             return [fb_rpc, tw_rpc, go_rpc], friends_rpc
         raise NotImplementedError
     # TODO: SI NO RPC, PROCESAR TODO EN ESTA FUNCION
         for rpc in friends_rpc:
             rpc.wait()
         friends = {} # diccionario con todos los amigos
         #los unimos en uno
         friends.update(fb_rpc.friends)
         friends.update(tw_rpc.friends)
         #friends.update(friends_google)
         if len(friends) > 0:
             if len(self.settings.blocked_friends_sug)>0:
                 for k in friends.keys():
                     if k in self.settings.blocked_friends_sug:
                         del friends[k]
             memcache.set('%sfriends_to_%s' % (memcache.version, self.key()), friends, 11235)
     return friends
Ejemplo n.º 25
0
def memexecute():
    limit = request.form['limit']
    cur.execute(query + limit)
    result = cur.fetchall()
    memcache.set(hash, result)
    c = 0
    for res in result:
        c = c + 1
        print(str(c) + ':' + str(res))
    starttime = time.time()
    memresult = memcache.get(hash)
    endtime = time.time()
    total = endtime - starttime
    print('Time taken by memcache ', total)
    return render_template('filehandle.html', rdstime2=total)
Ejemplo n.º 26
0
    def render(self, name, values=None):
        if values == None:
            values = self.template_values
            html = memcache.get('%s:page:%s' % (self.login_user, self.request.path_qs))

            if html == None:
                try:
                    html = template.render(name, values)
                except TemplateSyntaxError, e: # if theme files are not found, fall back to default theme
                    logging.warning(e)
                    settings.theme
                    self.redirect(settings.home_page)
                    return
                memcache.set('%s:page:%s' % (self.login_user, self.request.path_qs), html)

            self.response.out.write(html)
Ejemplo n.º 27
0
 def get_by_id(self, id):
     import memcache
     try:
         id = long(id)
     except:
         return None
     place = memcache.deserialize_instances(memcache.get(
         '%splace_%s' % (memcache.version, id)),
                                            _search_class=Place)
     if place is None:
         place = self._klass.get_by_id(id)
         if place is None:
             return None
         memcache.set('%splace_%s' % (memcache.version, id),
                      memcache.serialize_instances(place), 300)
     return place
Ejemplo n.º 28
0
def getCache(key):
    """
    Fetch an item from memcached, if running
    """
    if len(key) > 0 and len(memcache_address) > 0 and memcache:
        if len(key) > 250:
            m = md5.new()
            m.update(key)
            key = str(m.hexdigest())
        if appengine:
            item = memcache.get(key)
        else:
            mc = memcache.Client(memcache_address)
            item = mc.get(key)
        return item
    else:
        return None
Ejemplo n.º 29
0
def image_avatar(request, username):
    from georemindme.model_plus import memcache, version
    encoded_image = memcache.get('%s%s_avatarcachebase64' %
                                 (version, username))
    if encoded_image is None:
        import base64
        location = get_avatar(request, username)
        from google.appengine.api import urlfetch
        result = urlfetch.fetch(location['Location'])
        decoded_image = result.content
        encoded_image = "data:image;base64,%s" % base64.b64encode(
            result.content)
        memcache.set('%s%s_avatarcachebase64' % (version, username),
                     encoded_image, 1123)
    else:
        decoded_image = base64.b64decode(encoded_image)
    return HttpResponse(decoded_image, mimetype="image/xyz")
Ejemplo n.º 30
0
def token():
    token = None

    memcache = cache.get_cache()
    token = memcache.get('token')
    if token:
        LOG.debug('get token from memcache.')
        return token

    ks = keystone_client.KeystoneClient.from_url()
    token = ks.get_token()

    if token:
        memcache.set('token', token, TOKEN_CACHE_SECONDS)
        LOG.debug('get token from keystone.')
        return token
    else:
        LOG.error('get token failed both from cache and keystone')
Ejemplo n.º 31
0
def get_someitems(clear=False):
    """Boilerplate for your customization"""
    if clear:
        memcache.delete("someitems")
        return

    someitems = memcache.get("someitems")
    if someitems:
        #logging.info("return cached someitem")
        return someitems

    someitems = []
    for someitem in Someitem.all().fetch(100):
        someitems.append(someitem)

    memcache.set("someitems", someitems)
    logging.info("cached someitems")
    return someitems
Ejemplo n.º 32
0
def embedded_avatar(username):
    import memcache
    encoded_image = memcache.get('%s%s_avatarcachebase64' %
                                 (memcache.version, username))
    if encoded_image is None:
        from geouser.views import get_avatar
        try:
            image_url = get_avatar(None, username)
            from google.appengine.api import urlfetch
            result = urlfetch.fetch(image_url['Location'])
            encoded_image = "data:image;base64,%s" % base64.b64encode(
                result.content)
            memcache.set(
                '%s%s_avatarcachebase64' % (memcache.version, username),
                encoded_image, 1123)
        except:
            return 'https://georemindme.appspot.com/static/facebookApp/img/no_avatar.png'
    return encoded_image
Ejemplo n.º 33
0
    def get(self, dive_id):
        width = int(self.request.get('width', default_value=600))
        height = int(self.request.get('height', default_value=400))
        dive = Dive.get_by_id(int(dive_id))
        if dive is None:
            error(self.response, 404)
            return
        key = 'profile-%s-%d-%d' % (dive_id, width, height)
        self.response.etag = key
        request_etag = self.request.headers.get('If-None-Match', '""')[1:-1]
        if request_etag == key:
            self.response.status = 304
            return

        def response():
            return draw_profile(dive.dive_data.get('samples', []), width, height)

        self.response.write(memcache.get(key, response))
Ejemplo n.º 34
0
    def render_GET (self, request):
        params = {"id": int(request.args[b"id"][0].decode("utf-8")),
                  "width": request.args[b"width"][0].decode("utf-8"),
                  "height": request.args[b"height"][0].decode("utf-8"),
                  "format": request.args[b"format"][0].decode("utf-8"),
                  "resolution": int(request.args[b"resolution"][0].decode("utf-8"))
                 }

        series = schema.table.series
        with schema.select("series", series.id==params["id"]) as select:
            for s in select.all():

                cache_id = "spark_%s_%s_%s_%s_%s" % (params["id"], params["width"], params["height"], params["format"], params["resolution"])
                cached = memcache.get(cache_id)
                request.setHeader(b'Content-Type', b'image/png')
                if cached and cached["lm"] == s.last_modified:
                    request.write(cached["res"])
                else:
                    if params["format"] == "ohlcv":
                        data = DataFrameWrapper(s, resolution=params["resolution"])
                        if len(data.dframe) > 0 and "close" in data.dframe.columns.values:
                            plot = spark.Spark.plot(data=data.dframe["close"]
                                    , volume=data.dframe["volume"]
                                    , enable_volume=True
                                    , width=float(request.args[b"width"][0])
                                    , height=float(request.args[b"height"][0]))
                            cached = {"lm": s.last_modified, "res": plot.getvalue()}
                            memcache.set(cache_id, cached)
                            request.write(cached["res"])
                        else:
                            #request.write()
                            pass
                    elif params["format"] == "tick":
                        data = DataFrameWrapper(s, no_index=True, resolution=params["resolution"])
                        plot = spark.Spark.plot(data=data.dframe["price"]
                                , volume=0
                                , enable_volume=True
                                , width=float(request.args[b"width"][0])
                                , height=float(request.args[b"height"][0]))
                        cached = {"lm": s.last_modified, "res": plot.getvalue()}
                        memcache.set(cache_id, cached)
                        request.write(cached["res"])
                return b""
Ejemplo n.º 35
0
    def add_following(self, followname=None, followid=None):
        '''
        Añade un usuario a la lista de personas que sigue self.
        El usuario se busca a por username o por id

            :param followname: El nombre de usuario a seguir
            :type followname: :class:`string`
            :param followid: El identificador del usuario a seguir
            :type followid: :class:`string`
        '''
        if followname is not None:
            following = User.objects.get_by_username(followname,
                                                     keys_only=True)
        elif followid is not None:
            following = User.objects.get_by_id(followid, keys_only=True)
        else:
            raise AttributeError()
        if following is not None:
            if following == self.key():
                return True
            # actualiza la cache de amigos sugeridos
            import memcache
            friends = memcache.get('%sfriends_to_%s' %
                                   (memcache.version, self.key()))
            if friends is not None and int(following.id()) in friends:
                del friends[int(following.id())]
                memcache.set(
                    '%sfriends_to_%s' % (memcache.version, self.key()),
                    friends, 300)
            # añadimos el seguidor
            from models_acc import UserFollowingIndex
            is_following = UserFollowingIndex.all().filter(
                'following =', following).ancestor(self.key()).count()
            if is_following != 0:  # en este caso, el usuario ya esta siguiendo al otro, no hacemos nada mas.
                return True
            following_result = self.following(
                async=True)  # obtiene un iterador con los UserFollowingIndex
            if self._add_follows(following_result, following):
                from signals import user_follower_new
                user_follower_new.send(sender=self, following=following)
                return True
        return False
Ejemplo n.º 36
0
 def get_by_id(self, id):
     '''
     Obtiene un evento por su id, COMPRUEBA VISIBILIDAD, solo obtiene los publicos
     '''
     try:
         id = int(id)
     except:
         raise TypeError
     event = memcache.deserialize_instances(memcache.get(
         '%sEVENT%s' % (memcache.version, id)),
                                            _search_class=self._klass)
     if event is None:
         event = self._klass.get_by_id(int(id))
         if not hasattr(event, '_vis'):
             return None
         if not event._is_public():
             return None
         memcache.set('%sEVENT%s' % (memcache.version, id),
                      memcache.serialize_instances(event), 300)
     return event
Ejemplo n.º 37
0
def verify_AppModel(apiappid, apiservicekey):
    import hashlib
    
    if apiappid == None or apiservicekey == None:
        return False
    
    #To Verify AppModel, Applications that uses CheckNerds API.
    ThisApp = AppModel.get_by_id(apiappid)
    if ThisApp == None:
        return False
    
    #At beginning, will not turn this on.
    #if ThisApp.enable == False:
    #   return False

    #Check with API Usage.
    AppApiUsage = memcache.get("appapiusage" + str(apiappid))   
    if AppApiUsage >= ThisApp.api_limit:
        #Api Limitation exceed.
        self.write('<h1>API Limitation exceed.</h1>')       
        logging.info("AppID:" + str(apiappid) + ":" + cgi.escape(ThisApp.name) + " has exceed its API limitation.")
        return False
    else:
        if hashlib.sha256(ThisApp.servicekey).hexdigest() == apiservicekey:
            #Accept this App
            #------------------------
            #Manipulating API calls count.
            if AppApiUsage == None:
                memkey = "appapiuseage" + str(apiappid)
                AppApiUsage = 0
            AppApiUsage += 1
            memcache.set_item("appapiusage", AppApiUsage, int(apiappid))
            #------------------------
            #Below line could be turned off.
            logging.info("AppID:" + str(apiappid) + ":" + cgi.escape(ThisApp.name) + " accessed via API")
            #------------------------
            return True
        else:
            #Authentication Failed.
            #Should return a status number in the future.
            return False
Ejemplo n.º 38
0
    def get(self, userid):
        user = users.get_current_user()
        authuserid = user.user_id() if user is not None else ''

        self.response.headers['Cache-Control'] = 'max-age=600'
        dives = Dive.get_same_user(userid)

        key = userid + str(authuserid == userid) + str(len(dives))
        self.response.etag = key
        request_etag = self.request.headers.get('If-None-Match', '""')[1:-1]
        if request_etag == key:
            self.response.status = 304
            return

        def response():
            template_values = {'dives': dives,
                               'authenticated': authuserid == userid,
                               'userid': userid
                               }
            template = templater.get_template('templates/my.html')
            return template.render(template_values)
        self.response.write(memcache.get(key, response))
Ejemplo n.º 39
0
def block_contacts(request):
    """
        Bloquea a un usuario para no recibirlo en la lista
        de amigos sugeridos
        
        Parametros en POST:
            userid: el id del usuario a bloquear
            
            :returns: boolean
    """
    if request.user.is_authenticated():
        userid = int(request.POST['userid'])
        if userid is not None:
            import memcache
            request.user.settings.blocked_friends_sug.append(userid)
            friends = memcache.get('%sfriends_to_%s' % (memcache.version, request.user.key()))
            if friends is not None and userid in friends:
                del friends[userid]
                memcache.set('%sfriends_to_%s' % (memcache.version, request.user.key()), friends, 300)
            request.user.settings.put()
            return HttpResponse(simplejson.dumps(True), mimetype="application/json")
    return HttpResponse(simplejson.dumps(True), mimetype="application/json")
Ejemplo n.º 40
0
    def get(self):

        self.response.headers['Content-Type'] = 'text/html'
        self.response.headers['Cache-Control'] = 'max-age=14400'

        # Cache stuff
        request_etag = float(self.request.headers.get('If-None-Match', '"0"')[1:-1])
        if time.time() - request_etag < 14400:
            self.response.status = 304
            return
        key = str(time.time())
        self.response.etag = key

        def response():
            template_values = {
                'photo_name': html.random_image(),
                'dives': Dive.get_dives(),
            }
            template = templater.get_template('templates/index.html')
            return template.render(template_values)

        self.response.write(
            memcache.get('main_page', response, time=600))
Ejemplo n.º 41
0
    def add_following(self, followname = None, followid = None):
        '''
        Añade un usuario a la lista de personas que sigue self.
        El usuario se busca a por username o por id

            :param followname: El nombre de usuario a seguir
            :type followname: :class:`string`
            :param followid: El identificador del usuario a seguir
            :type followid: :class:`string`
        '''
        if followname is not None:
            following = User.objects.get_by_username(followname, keys_only=True)
        elif followid is not None:
            following = User.objects.get_by_id(followid, keys_only=True)
        else:
            raise AttributeError()
        if following is not None:
            if following == self.key():
                return True
            # actualiza la cache de amigos sugeridos
            import memcache
            friends = memcache.get('%sfriends_to_%s' % (memcache.version, self.key()))
            if friends is not None and int(following.id()) in friends:
                del friends[int(following.id())]
                memcache.set('%sfriends_to_%s' % (memcache.version, self.key()), friends, 300)
            # añadimos el seguidor
            from models_acc import UserFollowingIndex
            is_following = UserFollowingIndex.all().filter('following =', following).ancestor(self.key()).count()
            if is_following != 0:  # en este caso, el usuario ya esta siguiendo al otro, no hacemos nada mas.
                return True
            following_result = self.following(async=True)  # obtiene un iterador con los UserFollowingIndex
            if self._add_follows(following_result, following):
                from signals import user_follower_new
                user_follower_new.send(sender=self, following=following)
                return True
        return False
Ejemplo n.º 42
0
 def removeAssociation(self, server_url, handle):
     deleted = memcache.delete(self._assocKey(server_url, handle))
     serverAssoc = memcache.get(self._serverKey(server_url))
     if serverAssoc and serverAssoc.handle == handle:
         deleted = memcache.delete(self._serverKey(server_url)) or deleted
     return deleted
Ejemplo n.º 43
0
                    session = MemcacheSession(session_id, memcache)

                    session.merge(data)

                    return session

                except Exception, e:
                    raise ServerException("Failed to load session: %s" % str(e))

        # generate a new session id
        chars = "".join((string.letters, string.digits))

        while True:
            session_id = "".join([random.choice(chars) for x in xrange(0, 25)])

            if not memcache.get("session_" + session_id):
                # session id is available
                break

        # store the initial session data
        data    = { "__is_authenticated__": False }
        session = MemcacheSession(session_id, memcache)

        memcache.set("session_" + session_id, pickle.dumps(data))

        session.merge(data)

        return session

    # ------------------------------------------------------------------------------------------------------------------
Ejemplo n.º 44
0
    tempFileName = os.path.join(tempDownloadPath, blackVideoKey + '.ts')
    cmdLine = ' '.join(
        [FFMPEG_PATH, blackTSEncodingParams,
         ' -y %s' % tempFileName])
    executeCommand(cmdLine)
    cmdLine = ' '.join(
        map(lambda x: str(x), [
            TS_PREPARER_PATH, MEMCACHE_HOST, MEMCACHE_PORT, 0, blackVideoKey,
            FFMPEG_PATH, FFPROBE_PATH, 'nocut', tempFileName
        ]))
    executeCommand(cmdLine)

# main loop
manifestStitcher = ManifestStitcher()
startTime = time.time()
while time.time() < startTime + MINIMUM_RUN_PERIOD or memcache.get(
        trackerRequiredKey):
    cycleStartTime = time.time()
    # build stitched manifest
    manifest = manifestStitcher.getUpdatedManifest(liveStreamUrl,
                                                   adPositionsKey)
    # update the last used segment in memcache
    if manifestStitcher.lastUsedSegment != None:
        # Note: there is a race here between the get & set, but it shouldn't be a problem since trackers
        #		working on the same entry will more or less synchronized, if they aren't it's a problem anyway...
        savedLastUsedSegment = memcache.get(lastUsedSegmentKey)
        if savedLastUsedSegment == None or manifestStitcher.lastUsedSegment > int(
                savedLastUsedSegment):
            writeOutput('setting last used segment to %s' %
                        manifestStitcher.lastUsedSegment)
            memcache.set(lastUsedSegmentKey,
                         str(manifestStitcher.lastUsedSegment),
Ejemplo n.º 45
0
 def getAssociation(self, server_url, handle=None):
     if handle is None:
         return memcache.get(self._serverKey(server_url))
     else:
         return memcache.get(self._assocKey(server_url, handle))
Ejemplo n.º 46
0
def dashboard(request, template='generic/dashboard.html'):
    """**Descripción**: Permite actualizar el email y la contraseña.
        
        :return: Solo devuelve errores si el proceso falla.
    """
    if not request.user.is_authenticated():  # ¡no uses el decorador!
        return login(request)
    if request.user.username is None:
        if request.user.email is None:
            from forms import SocialTwitterUserForm as formClass
        else:
            if request.user.google_user is None and request.user.facebook_user is None:
                from forms import SocialUserForm as formClass
            else:
                from forms import SocialFacebookGoogleUserForm as formClass
        if request.method == 'POST':
            f = formClass(request.POST,
                          prefix='user_set_username',
                          initial={
                              'email': request.user.email,
                              'username': request.user.username,
                          })
            if f.is_valid():
                user = f.save(request.user)
                if user:
                    request.session['user'] = user
                    request.session.put()
                    response = HttpResponseRedirect(
                        reverse('geouser.views.dashboard_contacts'))
                    # cookie de primer login
                    from time import time
                    from datetime import datetime
                    max_age = datetime.fromtimestamp(
                        time() + settings.SESSION_COOKIE_AGE * 2)
                    expires = max_age - datetime.now()
                    expires = expires.days * 86400 + expires.seconds
                    response.set_cookie('new_user_%s' % request.user.id,
                                        '',
                                        max_age=60 * 60 * 24 * 7 * 52,
                                        domain=settings.SESSION_COOKIE_DOMAIN,
                                        path=settings.SESSION_COOKIE_PATH,
                                        secure=settings.SESSION_COOKIE_SECURE)
                    return response
        else:
            f = formClass(prefix='user_set_username',
                          initial={
                              'email': request.user.email,
                              'username': request.user.username,
                          })
        return render_to_response('generic/create_social_profile.html',
                                  {'form': f},
                                  context_instance=RequestContext(request))
    #------------------------------------------------------------------------------
    import memcache
    friends = memcache.get('%sfriends_to_%s' %
                           (memcache.version, request.user.key()))
    if friends is None:  # lanzamos las peticiones asincronas
        handlers_rpcs, list_rpc = request.user.get_friends_to_follow(rpc=True)
    chronology = request.user.get_activity_timeline()
    # FIXME: CHAPUZA, LA PLANTILLA ESPERA RECIBIR EL QUERY_ID EN JSON :)
    try:
        import json as simplejson
    except:
        from django.utils import simplejson
    chronology[0] = simplejson.dumps(chronology[0])
    if friends is None:
        # usuarios con mas sugerencias
        top_users = User.objects.get_top_users()
        friends = {}
        for user in top_users:
            if not user.key() == request.user.key(
            ) and not request.user.is_following(user):
                friends[user.id] = {'username': user.username, 'id': user.id}
        # amigos de otras redes sociales
        friends = request.user._callback_get_friends_to_follow(
            handlers_rpcs, list_rpc, friends)
    return render_to_response(template, {
        'friends_to_follow': friends,
        'chronology': chronology,
    }, RequestContext(request))
Ejemplo n.º 47
0
 def get_by_key_name(key_name):
     return memcache.get(key_name)
Ejemplo n.º 48
0
	p.start()
	p.join()

#get code no from user input
parser = OptionParser()
parser.add_option("-n" , dest="codeno" , help="code no.")
(options, args) = parser.parse_args()
code_no = options.codeno

if code_no is None:
	print "No code no input."
	exit()

#try get code infomation from memcache , if they have ...
memcache = memcache.Client([ '172.17.0.46:11212' ] , debug=0)
code_info = memcache.get(code_no)


if code_info is None:
#there have no cache in memory , so try get code infomation from db 
 	print "get code info from db"
	#try connect to db server
   	db = MySQLdb.connect( 
	      host="127.0.0.1" , 
	      port=3306 , 
	      user="******" , 
	      passwd="test" , 
	      db="sooj" )
	cursor = db.cursor()
	sql = "select * from code where no=%s" % code_no
   	cursor.execute( sql )