def get(self): cache = memcache.get('wsEmpresasBlob') if cache is None: blobs = MvBlob.all() emplist = [] outputdict = {} for blob in blobs: blob = json.loads(blob.Blob) init = blob['empresa']['nombre'].lower().replace(u'\u00e1',u'a').replace(u'\u00e9',u'e').replace(u'\u00ed',u'i').replace(u'\u00f3',u'o').replace(u'\u00fa',u'u').replace(u'\u00f1',u'n').replace(':','').replace('.','').replace(' ','').replace(',','').replace('(','').replace('{','').replace('[','')[0] empresadict = {'id': blob['empresa']['id'], 'nombre': blob['empresa']['nombre']} exists = False for emp in emplist: if emp == empresadict['id']: exists = True if not exists: emplist.append(empresadict['id']) try: outputdict[init].append(empresadict) outputdict[init] = sorted(outputdict[init], key=lambda k: k['nombre'].lower().replace(u'\u00e1',u'a').replace(u'\u00e9',u'e').replace(u'\u00ed',u'i').replace(u'\u00f3',u'o').replace(u'\u00fa',u'u').replace(u'\u00f1',u'n').replace(':','').replace('.','')) except KeyError: outputdict[init] = [] outputdict[init].append(empresadict) memcache.add('wsEmpresasBlob', json.dumps(outputdict), 86400) else: outputdict = json.loads(cache) self.response.headers['Content-Type'] = 'text/plain' self.response.out.write(json.dumps({'empresa_participantes': outputdict}))
def get(self): self.response.headers['Content-Type'] = 'text/plain' timestamp = self.request.get('timestamp') horas = self.request.get('horas') if not timestamp or not horas or timestamp == None or horas == None or timestamp == '' or horas == '': errordict = {'error': -1, 'message': 'Must specify variables in GET method (i.e. /db?timestamp=<YYYYMMDDHH24>&horas=<int>)'} self.response.out.write(json.dumps(errordict)) elif len(timestamp) != 10: errordict = {'error': -2, 'message': 'timestamp must be 10 chars long: YYYYMMDDHH24'} self.response.out.write(json.dumps(errordict)) else: try: fechastr = timestamp[0:8] timestamp = datetime.strptime(timestamp,'%Y%m%d%H') timestampdia = datetime.strptime(fechastr, '%Y%m%d') horas = int(horas) timestampend = timestamp + timedelta(hours = horas) except ValueError: errordict = {'error': -2, 'message': 'Value Error. Timestamp must be YYYYMMDDHH24 and horas is an integer'} self.response.out.write(json.dumps(errordict)) if horas > 24: errordict = {'error': -2, 'message': 'Horas must be <= 24'} self.response.out.write(json.dumps(errordict)) else: mvblobs = MvBlob.all().filter("FechaHora >=", timestamp).filter("FechaHora <=", timestampend) outputlist = [] for mvblob in mvblobs.run(): outputlist.append(json.loads(mvblob.Blob)) self.response.out.write(json.dumps(outputlist))
def get(self): #count = Sucursal.all().count() count = memcache.get('MvBlobCount') if count is None: count = 0 suc = Sucursal.all() for b in MvBlob.all().order ("-FechaHora").run(limit=1): suc.filter("FechaHora >", b.FechaHora) for s in suc.run(batch_size=30000): count += 1 memcache.add('MvBlobCount', count, 3600) else: count = int(count) logging.info('MvBlob: loading ' + str(count) + ' Sucursales.') batchsize = 50 batchnumber = 0 while count > 0: logging.info('Batch ' + str(batchnumber)) taskqueue.add(url='/mvblob/generate/run', params={'batchsize': batchsize, 'batchnumber': batchnumber}) batchnumber += 1 count -= batchsize
def post(self): self.response.headers['Content-Type'] = 'text/plain' try: batchsize = int(self.request.get('batchsize')) batchnumber = int(self.request.get('batchnumber')) if batchsize is None: batchsize = 10 if batchnumber is None: batchnumber = 0 except ValueError: batchsize = 10 batchnumber = 0 offset = batchnumber * batchsize sucs = Sucursal.all() for b in MvBlob.all().order ("-FechaHora").run(limit=1): sucs.filter("FechaHora >", b.FechaHora) sucs.order("FechaHora")#[offset:offset + batchsize] logging.info('MvBlob generation, batchsize: ' + str(batchsize) + ',batchnumber: ' + str(batchnumber) + '. [' + str(offset) + ':' + str(offset + batchsize) + ']') for suc in sucs.run(offset=offset, limit=batchsize): HasOferta = False olist = [] OSs = OfertaSucursal.all().filter("IdSuc =", suc.IdSuc) for OS in OSs: HasOferta = True olist.append(OS.IdOft) if HasOferta: als = MvBlob.all().filter("IdSuc =", suc.IdSuc) for al in als: db.delete(al) sucdict = {'id': suc.IdSuc, 'nombre': suc.Nombre, 'lat': suc.Geo1, 'long': suc.Geo2, 'fechamod': str(suc.FechaHora)} ent = None entidades = Entidad.all().filter("CveEnt =", suc.DirEnt) for entidad in entidades: ent = entidad.Entidad mun = None municipios = Municipio.all().filter("CveEnt =", suc.DirEnt).filter("CveMun =", suc.DirMun) for municipio in municipios: mun = municipio.Municipio sucdict['direccion'] = {'calle': suc.DirCalle, 'colonia': suc.DirCol, 'cp': suc.DirCp,'entidad_id': suc.DirEnt, 'entidad': ent,'municipio_id': suc.DirMun, 'municipio': mun} empresas = Empresa.all().filter("IdEmp = ", suc.IdEmp) for empresa in empresas.run(limit=1): empresadict = {'id': empresa.IdEmp, 'nombre': empresa.Nombre, 'url': empresa.Url, 'url_logo': ''} sucdict['empresa'] = empresadict urllogo = 'http://www.elbuenfin.org/imgs/imageDefault.png' ofertaslist = [] for o in olist: ofertas = Oferta.all().filter("IdOft =", o).run() for oferta in ofertas: url = 'http://www.elbuenfin.org/imgs/imageDefault.png' try: if oferta.Codigo and oferta.Codigo.replace('https://','http://')[0:7] == 'http://': url = oferta.Codigo except AttributeError: err = 'logourl' try: if oferta.Codigo is None and oferta.BlobKey and oferta.BlobKey != None and oferta.BlobKey.key() != 'none': url = 'http://' + APPID + '/ofimg?id=' + str(oferta.BlobKey.key()) except AttributeError: err = 'logourl' if url == 'http://www.elbuenfin.org/imgs/imageDefault.png' and oferta.Promocion is not None and oferta.Promocion != '': url = oferta.Promocion if oferta.Promocion is not None and oferta.Promocion != '': urllogo = oferta.Promocion ofertadict = {'id': oferta.IdOft, 'oferta': oferta.Oferta, 'descripcion': oferta.Descripcion, 'descuento': oferta.Descuento, 'promocion': oferta.Promocion, 'enlinea': oferta.Enlinea, 'precio': oferta.Precio, 'url': oferta.Url, 'url_logo': url, 'fechapub': str(oferta.FechaHoraPub.strftime('%Y-%m-%d'))} palabraslist = [] palabras = OfertaPalabra.all().filter("IdOft =", oferta.IdOft) for palabra in palabras: palabraslist.append(palabra.Palabra) ofertadict['palabras'] = palabraslist cat = None categorias = Categoria.all().filter("IdCat =", oferta.IdCat) for categoria in categorias: cat = categoria.Categoria ofertadict['categoria_id'] = oferta.IdCat ofertadict['categoria'] = cat ofertaslist.append(ofertadict) sucdict['ofertas'] = ofertaslist sucdict['empresa']['url_logo'] = urllogo mvblob = MvBlob() mvblob.FechaHora = suc.FechaHora mvblob.IdSuc = suc.IdSuc mvblob.Blob = json.dumps(sucdict) mvblob.put() else: pass