Пример #1
0
    def get(self):
        """Popula os objetos Hash para os pontos de uma linha"""
        self.response.headers['Content-Type'] = 'text/plain'
        key = self.request.get("key")
        linha = Linha.get(db.Key(key))
        self.response.out.write('Linha: %s\n' % linha.nome)
        # Percorre os pontos dessa linha, processando os hashes dos segmentos
        nearhashAnterior = ""
        for ponto in linha.pontos:
            if ponto.nearhash:
                if ponto.nearhash == nearhashAnterior:
                    self.response.out.write('hash repetido, pulando %s\n' % ponto.nearhash)
                    continue       
                nearhashAnterior = ponto.nearhash     
#                if len(ponto.nearhash) != 6:
#                    self.response.out.write('hash curto, pulando %s\n' % ponto.nearhash)
                # Se ja existe objeto para o hash, pega ele, senao cria um novo
                hashLista = Hash.all().filter("hash =", ponto.nearhash).fetch(1)
                if hashLista:
                    self.response.out.write('Hash: %s ja existia \n' % ponto.nearhash)
                    hash = hashLista[0]
                else:
                    self.response.out.write('Hash: %s criado \n' % ponto.nearhash)
                    hash = Hash(hash=ponto.nearhash)
                    
                # Se a linha ainda nao esta associada ao objeto-hash, associa
                if str(linha.key()) not in hash.linhas:
                    self.response.out.write('Linha adicionada a lista\n')
                    hash.linhas.append(str(linha.key()))
                    hash.put()
Пример #2
0
def shortener():
    shortener_form = ShortenerForm(request.form)
    short_url = ''
    if request.method == 'POST' and shortener_form.validate():
        full_url = shortener_form.full_url.data
        logged_in = session.has_key('login') and session['login']
        if logged_in:
            url_hash = make_hash(full_url + session['login'])
        else:
            url_hash = make_hash(full_url)
        short_url = make_short_url(app.config['HOST'], app.config['PORT'],
                                   url_hash)
        if Hash.query.filter_by(url_hash=url_hash).first() == None:
            if logged_in:
                user = User.query.filter_by(login=session['login']).first()
                hash_obj = Hash(url_hash, full_url)
                user.hashes.append(hash_obj)
                db.session.commit()
            else:
                user = User.query.filter_by(login='******').first()
                if not user:
                    user = User('not_registered', 'pass')
                    db.session.add(user)
                hash_obj = Hash(url_hash, full_url)
                user.hashes.append(hash_obj)
                db.session.commit()

    return render_template('shortener.html',
                           short_url=short_url,
                           form=shortener_form)
Пример #3
0
 def put_hash(self, hash, linhas):
     """Atualiza um hash no banco (mesmo vazio) e anula seu cache.
        Retorna mensagem consumível pelo sptscraper"""
     try:
         self.cache.delete("linhas_por_hash_" + hash)
         hash_obj = Hash.all().filter("hash =", hash).fetch(1)
         if hash_obj:
             hash_obj = hash_obj[0]
             hash_obj.linhas = linhas
         else:
             hash_obj = Hash(hash=hash, linhas=linhas)
         hash_obj.put()
         return "OK HASH UPLOAD %s " % id
     except:
         return "ERRO HASH: %s" % sys.exc_info()[1]
Пример #4
0
 def put_hash(self, hash, linhas):        
     """Atualiza um hash no banco (mesmo vazio) e anula seu cache.
        Retorna mensagem consumível pelo sptscraper"""
     try:
         self.cache.delete("linhas_por_hash_" + hash)
         hash_obj = Hash.all().filter("hash =", hash).fetch(1)
         if hash_obj:
             hash_obj = hash_obj[0]
             hash_obj.linhas = linhas
         else:
             hash_obj = Hash(hash = hash, linhas = linhas)
         hash_obj.put()
         return "OK HASH UPLOAD %s " % id
     except:
         return "ERRO HASH: %s" % sys.exc_info()[1]
Пример #5
0
 def __init__(self, nome, descricao, preco, codigo_evento):
     self.__nome = nome
     self.__descricao = descricao
     self.__preco = preco
     self.__data = Data.getSystemData()
     self.__codigo_evento = codigo_evento
     self.__codigo_atividade = Hash.generateHash()
Пример #6
0
def post_home():
    def error():
        flash("Please post your profiler result via file or url")
        return redirect("/")

    name = Hash.make()
    r_ok = redirect("/result/" + name)

    if "post_file" in request.values:
        file = request.files["result"]
        if not file:
            return error()

        file.save(os.path.join(RESULTS_DIR, name))
        return r_ok

    elif "post_url" in request.values:
        url = request.values["url"]
        if not url:
            return error()

        response = urllib2.urlopen(url)
        content = response.read()
        with open(RESULTS_DIR + "/" + name, "w") as f:
            f.write(content)
        return r_ok
Пример #7
0
def post_home():
	def error():
		flash("Please post your profiler result via file or url")
		return redirect("/")

	name = Hash.make()
	r_ok = redirect("/result/" + name)

	if "post_file" in request.values:
		file = request.files["result"]
		if not file:
			return error()

		file.save(os.path.join(RESULTS_DIR, name))
		return r_ok

	elif "post_url" in request.values:
		url = request.values["url"]
		if not url:
			return error()

		response = urllib2.urlopen(url)
		content = response.read()
		with open(RESULTS_DIR + "/" + name, "w") as f:
			f.write(content)
		return r_ok
Пример #8
0
 def get(self):
     self.response.headers['Content-Type'] = 'text/html'
     if self.request.get("hashes"):
         for hash in Hash.all():
             self.response.out.write('<a href="/cachehash?hash=%s">%s</a><br/>' % (hash.hash, hash.hash))
     else:
         for linha in Linha.all():
             self.response.out.write('<a href="/cachelinha?key=%s">%s</a><br/>' % (str(linha.key()), linha.nome))
Пример #9
0
def hashes2links(request):
    if request.raw_post_data:
        hashes = json.loads(request.raw_post_data)
        result = {}
        for h in hashes:
            result[h] = Hash.hash2link(h)
        return HttpResponse(json.dumps(result))
    else:
        return HttpResponse(json.dumps({}))
Пример #10
0
 def get_info_hashes_linhas(self, lat, lng):
     """Retorna array JSON com as infos e hashes das linhas que passam num ponto"""
     hash = str(Geohash((lng, lat)))[0:6]
     chave_memcache = "linhas_por_hash_%s" % hash;
     linhas_ids = self.cache.get(chave_memcache)
     if linhas_ids is None:
         result = Hash.all().filter("hash =", hash).fetch(1)
         linhas_ids = json.loads(result[0].linhas) if result else []
         self.cache.add(chave_memcache, linhas_ids)        
     return json.dumps([json.loads(self.get_info_hashes_linha(linha)) for linha in linhas_ids], separators=(',',':'))
Пример #11
0
	def __init__(self,nome,descricao,usuario,data_inicio,data_fim):
		self.__nome = nome
		self.__descricao = descricao
		self.__usuario = usuario
		self.__codigo = Hash.generateHash()
		self.__data_inicio = data_inicio
		self.__data_fim = data_fim
		self.__data_criacao = Data.getSystemData()
		self.__estado_atual = 1
		self.__interesses ["None"]
Пример #12
0
 def get(self):
     hash = self.request.get("hash")
     chave_memcache = "hash_linhas_keys_" + hash
     client = memcache.Client()
     linhas_keys = client.get(chave_memcache)
     if linhas_keys is None:
         result = Hash.all().filter("hash =", hash).fetch(999)
         self.response.out.write("count %d " % len(result))
         linhas_keys = result[0].linhas if result else []
         client.add(chave_memcache, linhas_keys)   
         self.response.out.write("gerou cache de %s " % chave_memcache)
     else:
         self.response.out.write("ja tinha cache de %s " % chave_memcache)
Пример #13
0
 def get_info_hashes_linhas(self, lat, lng):
     """Retorna array JSON com as infos e hashes das linhas que passam num ponto"""
     hash = str(Geohash((lng, lat)))[0:6]
     chave_memcache = "linhas_por_hash_%s" % hash
     linhas_ids = self.cache.get(chave_memcache)
     if linhas_ids is None:
         result = Hash.all().filter("hash =", hash).fetch(1)
         linhas_ids = json.loads(result[0].linhas) if result else []
         self.cache.add(chave_memcache, linhas_ids)
     return json.dumps([
         json.loads(self.get_info_hashes_linha(linha))
         for linha in linhas_ids
     ],
                       separators=(',', ':'))
Пример #14
0
 def get(self):
     self.response.headers['Content-Type'] = 'application/json'
     lat = float(self.request.get('lat'))
     lng = float(self.request.get('lng'))
     # Recupera as chaves das linhas que passam pelo geohash do ponto
     hash = models.calculaNearhash(lng, lat)
     chave_memcache = "hash_linhas_keys_" + hash;
     client = memcache.Client()
     linhas_keys = client.get(chave_memcache)
     if linhas_keys is None:
         result = Hash.all().filter("hash =", hash).fetch(1)
         linhas_keys = result[0].linhas if result else []
         client.add(chave_memcache, linhas_keys)        
     # Converte elas para objetos no formato da resposta e devolve como JSON
     linhas_obj = [self._linha_obj(key) for key in linhas_keys]
     linhas_json = simplejson.dumps(linhas_obj)
     callback = self.request.get("callback");
     if callback:
         linhas_json = callback + "(" + linhas_json + ");"
     self.response.out.write(linhas_json)
Пример #15
0
def gatraPlayer_PostHash(request):
    if request.method != 'POST':
        return HttpResponse('', status=http_NOT_ALLOWED)

    try:
        data = json.loads(request.body)
    except:
        return HttpResponse('Could not load json', status=http_BAD_REQUEST)

    if 'host' in data.keys() and 'hash' in data.keys() and 'ttl' in data.keys():
        _hash = Hash()
        _hash.valid_host = data['host']
        _hash.valid_hash = data['hash']

        if 'user_name' in data.keys():
            _hash.user_name = data['user_name']
        if 'title' in data.keys():
            _hash.title     = data['title']

        _hash.expiration = datetime.now() + timedelta(0,data['ttl'])
        _hash.save()
        return HttpResponse(data['hash'], status=http_POST_OK)

    return HttpResponse('Mandatory json value not found', status=http_BAD_REQUEST)
Пример #16
0
 def _hash_link(self, m):
     link = m.group('url')
     hashed_link = Hash.link2hash(link)
     return '<a href="#" hash-string="{0}" {1} {2} {3}>'.format(hashed_link, m.group('attr1'), m.group('attr2'), m.group('attr3'))
Пример #17
0
 def _hash_link(self, m):
     link = m.group(1)
     hashed_link = Hash.link2hash(link)
     return '<a href="#"%shash-string="%s"%s>' % (m.group(2), hashed_link, m.group(3))
Пример #18
0
 def __init__(self, codigo_evento, perc, data):
     self.__codigo_cupom = Hash.generateHash(15)
     self.__codigo_evento = codigo_evento()
     self.__percentual = perc
     self.__data_validade = data
     self.__estado = True
Пример #19
0
	def __init__(self,codigo_usuario):
		self.__codigo_inscricao = Hash.generateHash(15)
		self.__codigo_usuario = codigo_usuario
		self.__estado_atual = False
		self.__data_inscricao = Data.getSystemData()
Пример #20
0
 def __init__(self, nome, contato, data_nasc):
     self.__nome = nome
     self.__contato = contato
     self.__data_nasc = data_nasc
     self.__codigo_usuario = Hash.generateHash()
Пример #21
0
 def _hash_widget(self, m):
     widget_id = m.group(1)
     hashed_widget = Hash.widget2hash(widget_id)
     return '<div class="hashed-widget" hash-string="%s"></div>' % (hashed_widget,)