def get(self): key = self.request.get("key") client = memcache.Client() chave_memcache = "linha_json_" + key linha_obj = client.get(chave_memcache) if linha_obj is None: linha = Linha.get(db.Key(key)) linha_obj = { "key" : str(linha.key()), "nome" : linha.nome, "url" : linha.url, "hashes" : linha.hashes()} client.add(chave_memcache, linha_obj) self.response.out.write("gerou cache de %s " % chave_memcache) else: self.response.out.write("ja tinha cache de %s " % chave_memcache) chave_memcache = "pontos_json_" + key; pontos_json = client.get(chave_memcache) if pontos_json is None: linha = Linha.get(db.Key(key)) pontos = Ponto.all().filter("linha = ", linha).order("ordem") pontos_json = simplejson.dumps([(ponto.lat, ponto.lng) for ponto in pontos]) client.add(chave_memcache, pontos_json) self.response.out.write("gerou cache de %s " % chave_memcache) else: self.response.out.write("ja tinha cache de %s " % chave_memcache)
def put_linha(self, id, deleted, info, pontos, hashes): """Atualiza uma linha no banco (incluindo delete) e anula seu cache. O cache dos hashes não é atualizado (supõe-se que eles também serão atualizados no final). Retorna mensagem consumível pelo sptscraper""" try: id = int(id) self.cache.delete("info_por_linha_id_%s" % id) if deleted == "true": linha = Linha.all().filter("id =", id).fetch(1) if linha: db.delete(linha) return "OK LINHA DELETE %s " % id else: return "OK LINHA DELETE %s (NAO EXISTIA)" % id else: linha = Linha.all().filter("id =", id).fetch(1) if linha: linha = linha[0] linha.info = info linha.pontos = pontos linha.hashes = hashes else: linha = Linha(id = id, info = info, pontos = pontos, hashes = hashes) linha.put() return "OK LINHA UPLOAD %s " % id except: return "ERRO LINHA: %s" % sys.exc_info()[1]
def get(self): self.response.headers['Content-Type'] = 'text/plain' self.response.out.write('Apagando pontos...') while Ponto.all().fetch(1): db.delete(Ponto.all().fetch(100)) self.response.out.write('Apagando linhas...') while Linha.all().fetch(1): db.delete(Linha.all().fetch(100)) self.response.out.write('Ok')
def listar_veiculos(): '''Retorna um vetor com todos os veículos''' headers = Inthegra_API.coletar_headers() headers['X-Auth-Token'] = token req = requests.get(Inthegra_API.url_base + '/veiculos', headers = headers) veiculos = [] for registro in req.json(): linha = registro['Linha'] rota = Linha( codigo = linha.get('CodigoLinha'), nome = linha.get('Denomicao'), ponto_partida = linha.get('Origem'), ponto_retorno = linha.get('Retorno'), circular = linha.get('Circular') ) for veiculo in linha.get('Veiculos'): frota = Veiculo( codigo = veiculo.get('CodigoVeiculo'), latitude = veiculo.get('Lat'), longitude = veiculo.get('Long'), hora = veiculo.get('Hora'), linha = rota ) veiculos.append(frota) return veiculos
def procurar_parada_codigoLinha(codigo_linha): '''Retorna as paradas da linha indicada no parâmetro informado Parâmetro solicitado: string contendo o código da linha. ''' headers = Inthegra_API.coletar_headers() headers['X-Auth-Token'] = token req = requests.get(Inthegra_API.url_base + '/paradasLinha?busca=' + str(codigo_linha), headers = headers) paradas_encontradas = [] if req.status_code == 404: print('Termo informado: {}. Sem resultados para o termo informado!'.format(str(codigo_linha))) else: linha = req.json()['Linha'] rota = Linha( codigo=linha.get('CodigoLinha'), nome=linha.get('Denomicao'), ponto_partida=linha.get('Origem'), ponto_retorno=linha.get('Retorno'), circular=linha.get('Circular') ) for parada in req.json()['Paradas']: paradas = Parada( codigo = parada.get('CodigoParada'), nome = parada.get('Denomicao'), endereco = parada.get('Endereco'), latitude = parada.get('Lat'), longitude = parada.get('Long') ) paradas_encontradas.append(paradas) return paradas_encontradas
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()
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))
def HandleEntity(self, entity): linha = Linha.all().filter("nome =", entity["nome"]).fetch(1)[0] ponto = Ponto(ordem=entity["ordem"], linha=linha, lat=entity["lat"], lng=entity["lng"]) pontosAnt = Ponto.all().filter("linha =", linha).filter("ordem =", ponto.ordem - 1).fetch(1) if pontosAnt: pontoAnt = pontosAnt[0] ponto.setNearhash(pontoAnt) ponto.put() return None
def get_info_hashes_linha(self, linha_id): """Retorna objeto JSON com as infos gerais e hashes da linha""" chave_memcache = "info_por_linha_id_%s" % linha_id linha = self.cache.get(chave_memcache) if linha is None: result = Linha.all().filter("id =", int(linha_id)).fetch(1) if result: linha = '{"id":%s,"info":%s,"hashes":%s}' % (linha_id, result[0].info,result[0].hashes) self.cache.add(chave_memcache, linha) return linha
def get_pontos_linha(self, linha_id): """Retorna objeto JSON com os pontos do trajeto para cada dia e sentido""" chave_memcache = "pontos_por_linha_id_%s" % linha_id pontos = self.cache.get(chave_memcache) if pontos is None: result = Linha.all().filter("id =", int(linha_id)).fetch(1) if result: pontos = result[0].pontos self.cache.add(chave_memcache, pontos) return pontos
def get_info_hashes_linha(self, linha_id): """Retorna objeto JSON com as infos gerais e hashes da linha""" chave_memcache = "info_por_linha_id_%s" % linha_id linha = self.cache.get(chave_memcache) if linha is None: result = Linha.all().filter("id =", int(linha_id)).fetch(1) if result: linha = '{"id":%s,"info":%s,"hashes":%s}' % ( linha_id, result[0].info, result[0].hashes) self.cache.add(chave_memcache, linha) return linha
def put_linha(self, id, deleted, info, pontos, hashes): """Atualiza uma linha no banco (incluindo delete) e anula seu cache. O cache dos hashes não é atualizado (supõe-se que eles também serão atualizados no final). Retorna mensagem consumível pelo sptscraper""" try: id = int(id) self.cache.delete("info_por_linha_id_%s" % id) if deleted == "true": linha = Linha.all().filter("id =", id).fetch(1) if linha: linha.delete() return "OK LINHA DELETE %s " % id else: return "OK LINHA DELETE %s (NAO EXISTIA)" % id else: linha = Linha.all().filter("id =", id).fetch(1) if linha: linha = linha[0] linha.info = info linha.pontos = pontos linha.hashes = hashes else: linha = Linha(id=id, info=info, pontos=pontos, hashes=hashes) linha.put() return "OK LINHA UPLOAD %s " % id except: return "ERRO LINHA: %s" % sys.exc_info()[1]
def _linha_obj(self, key): """Monta info da linha no formato da resposta, usando o cache se possível""" client = memcache.Client() chave_memcache = "linha_json_" + key linha_obj = client.get(chave_memcache) if linha_obj is None: linha = Linha.get(db.Key(key)) linha_obj = { "key" : str(linha.key()), "nome" : linha.nome, "url" : linha.url, "hashes" : linha.hashes()} client.add(chave_memcache, linha_obj) return linha_obj
def get(self): self.response.headers['Content-Type'] = 'application/json' key = self.request.get("key") chave_memcache = "pontos_json_" + key; client = memcache.Client() pontos_json = client.get(chave_memcache) if pontos_json is None: linha = Linha.get(db.Key(key)) pontos = Ponto.all().filter("linha = ", linha).order("ordem") pontos_json = simplejson.dumps([(ponto.lat, ponto.lng) for ponto in pontos]) client.add(chave_memcache, pontos_json) callback = self.request.get("callback"); if callback: pontos_json = callback + "(" + pontos_json + ");" self.response.out.write(pontos_json)
def listar_linhas(): '''Retorna um vetor com todas as linhas de ônibus''' headers = Inthegra_API.coletar_headers() headers['X-Auth-Token'] = token req = requests.get(Inthegra_API.url_base + '/linhas', headers = headers) linhas = [] for linha in req.json(): rota = Linha( codigo = linha.get('CodigoLinha'), nome = linha.get('Denomicao'), ponto_partida = linha.get('Origem'), ponto_retorno = linha.get('Retorno'), circular = linha.get('Circular') ) linhas.append(rota) return linhas
def HandleEntity(self, entity): for linha in Linha.all().filter("nome =", entity["nome"]).fetch(999): for ponto in linha.pontos: ponto.delete() linha.delete() return entity
def get(self): self.response.headers['Content-Type'] = 'text/html' for linha in Linha.all(): self.response.out.write('<a href="/gerahash?key=%s">%s</a><br/>' % (str(linha.key()), linha.nome))