def cargarhoteles (url, idioma, nombrehot): parser = getHotels(url) listanombre = parser.get('name') listadireccion = parser.get('address') listapagina = parser.get('web') listalatitud = [float(num) for num in parser.get('latitude')] listalongitud = [float(num) for num in parser.get('longitude')] listadescripcion = parser.get('body') listaimagenes = parser.get('images') listacategoria = parser.get('category') if not idioma: for nombre, direccion, pagina, latitud, longitud, descripcion, imagenes, categoria in itertools.izip(listanombre, listadireccion, listapagina, listalatitud, listalongitud, listadescripcion, listaimagenes, listacategoria): tipo = categoria[0] estrellas = categoria[1] hotel = Hotel(nombre=nombre, pagina=pagina, direccion=direccion, latitud=latitud, longitud=longitud, descripcion=descripcion, categoria=tipo, estrellas=estrellas) hotel.save() idhotel = Hotel.objects.get(nombre=nombre) enlaces =' '.join(imagenes) imagen = Imagen(hotel = idhotel, url = enlaces) imagen.save() else: posicion = 0 for key, value in enumerate(listanombre): if value == nombrehot: posicion = key descripcion = listadescripcion[posicion] return descripcion
def create_hotel(): if request.headers['Content-Type'] != 'application/json; charset=UTF-8': raise Exception("415 Unsupported Media Type") data = request.json hotel = Hotel(**data) hotel.put() return jsonutil.encode(hotel.key().id())
def load(hotelname, hoteladdress, hotelweb, latitude, longitude, description, imagelist, categorylist): #itertools to work with multiple lists at once for name, address, web, latit, longit, descr, category, images in itertools.izip(hotelname, hoteladdress, hotelweb, latitude, longitude, description, categorylist, imagelist): #Strip HTML tags descr = strip_tags(descr) print "Saving: " + name hotel = Hotel(name=name, web=web, body=descr, address=address, category=category[0], latitude=latit, longitude=longit, stars=category[1]) hotel.save() identifier = Hotel.objects.get(name=name) urls =' '.join(images) images = Image(hotel=identifier, url_image=urls) images.save()
def process_item(self, item, spider): new_hotel = Hotel(**item) self.session.add(new_hotel) new_hotel.rooms = self.add_rooms(item) try: self.session.commit() except IntegrityError: self.session.rollback() old_hotel = self.session.query(Hotel).filter_by( name=new_hotel.name).first() old_hotel.update(new_hotel) self.session.commit() return item
def newHotel(): """ If the user is logged in, allow the user to create a new hotel; Otherwise redirect the user to the login page. """ if 'username' not in login_session: flash("Please sign in to create new entries.") return redirect(url_for('showLogin')) if request.method == 'POST': new_hotel = Hotel( name=request.form['name'], picture=request.form['picture'], description=request.form['description'], price=request.form['price'], rating=request.form['rating'], category=request.form['category'], user_id=login_session['user_id'], ) session.add(new_hotel) try: session.commit() except: session.rollback() raise flash("Success! %s was added to the database." % new_hotel.name) return redirect(url_for('showHotels')) else: return render_template('new_hotel.html')
def edit_hotel_review(hotel_id): if request.method == 'POST': hotel = Hotel.get_by_id(hotel_id) data = request.json review = Review(**data) review.hotel = hotel review.put() return hotel_reviews(hotel_id)
def get_comments(): while True: try: url = Urls.select().where(Urls.status=='new').limit(1).get().url # print url if not url: break Urls.update(status='done').where(Urls.url==url).execute() hotel_id = url.split('/')[2].split('.')[0] comments_driver.get(base_url + url) soup = BeautifulSoup(comments_driver.page_source, 'html.parser') try: name = soup.find(attrs={'itemprop': 'name'}).text.encode('utf-8') except Exception, e: print "hotel name not found ", e name = hotel_id Hotel.create(hotel_id=hotel_id, hotel_name=name) except Exception, e: print "Insert into hotel error ", e Urls.update(status='new').where(Urls.url==url).execute() continue
def api_hotels(): """ Hotels list view. If the user is admin user, will allow to create new hotels. """ if request.method == "POST": token = request.headers["Authorization"] user = User.verify_auth_token(token) if not user.is_admin: # If the user is not admin, raise error return make_response(jsonify({"error": "Unauthorized access"}), 403) errors = {} if not request.json: return make_response(jsonify({"error": "No data found"}), 400) # Validate required fields. for field in ["name", "address", "city", "state", "country", "zipcode", "nightly_rate", "description"]: if not request.json.get(field): errors[field] = "This field is required" # Validate field value try: float(request.json["nightly_rate"]) except: errors["nightly_rate"] = "Invalid nightly rate" if errors: return make_response(jsonify({"error": errors}), 400) hotel = Hotel( request.json["name"], request.json["address"], request.json["city"], request.json["state"], request.json["country"], request.json["zipcode"], request.json["nightly_rate"], request.json["description"], ) hotel.add(hotel) return make_response(jsonify({"hotel": hotel.id}), 201) else: return json.dumps(Hotel.serialize_list(Hotel.query.all()))
def show_aloj_id(request,id): lista=Hotel.objects.get(id=id) listimages=Image.objects.filter(hid=lista.id) listauser=PagUser.objects.all() listcoms="" hoteles=Hotel.objects.filter(id=id) listahoteles=Hotel.objects.all() if request.method == 'POST' and 'like' in request.POST : print lista.puntuacion lista.puntuacion = lista.puntuacion + 1 h_megusta=Hotel(id=id,name=lista.name,url=lista.url,body=lista.body, address=lista.address,source=lista.source, stars=lista.stars,tipo=lista.tipo,puntuacion=lista.puntuacion) h_megusta.save() if request.method == 'POST' and 'quiero' in request.POST : print "aqui" h_us = HotelsUser(hotel=lista,user=request.user.username) h_us.save() if request.method =='POST' and 'comentario' in request.POST : value = request.POST.get('comentarios', "") if value !="": comment=Comment(hid=lista.id,com=lista,text=value) comment.save() listcoms=Comment.objects.filter(hid=lista.id) context = {'lista':listimages[0:5],'h':hoteles,'condicion':"",'url':lista.url,'name':lista.name, 'body':lista.body, 'address':lista.address,'comentarios':listcoms,'type':lista.tipo,'stars':lista.stars, 'puntuacion':lista.puntuacion, 'user':request.user.username,'listausers':listauser} if request.user.is_authenticated(): us=PagUser.objects.get(user=request.user.username) context = {'lista':listimages[0:5],'h':hoteles,'condicion':"",'url':lista.url,'name':lista.name, 'address':lista.address,'comentarios':listcoms,'type':lista.tipo,'stars':lista.stars, 'body':lista.body, 'color':us.color,'size':us.size,'user':request.user.username,'listausers':listauser} return render_to_response('alojid.html', context,context_instance = RequestContext(request))
def cargar(request): #ESTA COMPLETA # Load parser and driver theParser = make_parser() theHandler = myContentHandler() theParser.setContentHandler(theHandler) # Ready, set, go! url = ("http://cursosweb.github.io/etc/alojamientos_es.xml") xmlFile = urlopen(url) #xmlFile = open('/home/lucia/alojamientos_es.xml') theParser.parse(xmlFile) lista = theHandler.dameLista() for dic in lista: h = Hotel(hotel_id=dic["id"], nombre=dic["nombre"], email=dic["email"], telefono=dic["telefono"], cuerpo=dic["cuerpo"], web=dic["web"], address=dic["address"], pais=dic["pais"], latitud=dic["latitude"], longitud=dic["longitude"], subAA=dic["subAdministrativeArea"], idTipo=dic["idTipo"], Tipo=dic["Tipo"], idCategoria=dic["idCategoria"], Categoria=dic["Categoria"], idSubCategoria=dic["idSubCategoria"], subCategoria=dic["SubCategoria"], NumComentarios=0) h.save() respuesta = 'Archivos guardados correctamente' template = get_template('cargar.html') Context = RequestContext(request, {'respuesta': respuesta}) return HttpResponse(template.render(Context))
def startElement(self, name, attrs): self.theContent = name if name == 'basicData': self.record = Hotel(name="", url="", body="", address="", source="", stars="", tipo="") if name == "item": if attrs['name'] == "SubCategoria": self.is_star = True if name == "item": if attrs['name'] == "Categoria": self.is_cat = True if name == 'media': if attrs['type'] == "image": self.is_img = True self.recimg = Image(hid=0, img=self.record, url="")
def api_hotels(): """ Hotels list view. If the user is admin user, will allow to create new hotels. """ if request.method == 'POST': token = request.headers['Authorization'] user = User.verify_auth_token(token) if not user.is_admin: # If the user is not admin, raise error return make_response(jsonify({'error': 'Unauthorized access'}), 403) errors = {} if not request.json: return make_response(jsonify({'error': 'No data found'}), 400) # Validate required fields. for field in ['name', 'address', 'city', 'state', 'country', 'zipcode', 'nightly_rate', 'description']: if not request.json.get(field): errors[field] = 'This field is required' # Validate field value try: float(request.json['nightly_rate']) except: errors['nightly_rate'] = 'Invalid nightly rate' if errors: return make_response(jsonify({'error': errors}), 400) hotel = Hotel(request.json['name'], request.json['address'], request.json['city'], request.json['state'], request.json['country'], request.json['zipcode'], request.json['nightly_rate'], request.json['description']) hotel.add(hotel) return make_response(jsonify({'hotel': hotel.id}), 201) else: return json.dumps(Hotel.serialize_list(Hotel.query.all()))
def cargar(request): #ESTA COMPLETA # Load parser and driver theParser = make_parser() theHandler = myContentHandler() theParser.setContentHandler(theHandler) # Ready, set, go! url = ("http://cursosweb.github.io/etc/alojamientos_es.xml") xmlFile = urlopen(url) #xmlFile = open('/home/lucia/alojamientos_es.xml') theParser.parse(xmlFile) lista = theHandler.dameLista() for dic in lista: h = Hotel(hotel_id = dic["id"], nombre = dic["nombre"], email = dic["email"], telefono = dic["telefono"], cuerpo = dic["cuerpo"], web = dic["web"], address = dic["address"], pais = dic["pais"], latitud = dic["latitude"], longitud= dic["longitude"], subAA = dic["subAdministrativeArea"], idTipo = dic["idTipo"], Tipo = dic["Tipo"], idCategoria = dic["idCategoria"], Categoria = dic["Categoria"], idSubCategoria = dic["idSubCategoria"], subCategoria = dic["SubCategoria"], NumComentarios = 0) h.save() respuesta = 'Archivos guardados correctamente' template = get_template('cargar.html') Context = RequestContext(request, {'respuesta': respuesta}) return HttpResponse(template.render(Context))
def cargar_alojamientos(): info_hoteles = get_info_hoteles() resp = "Todos los datos se han almacenado en la base de datos!" for hotel in info_hoteles: datos_hotel = hotel nombre_hotel = datos_hotel['name'] web_hotel = datos_hotel['web'] direccion_hotel = datos_hotel['address'] categoria_hotel = datos_hotel['categoria'] subcategoria_hotel = datos_hotel['subcategoria'] imagenes_hotel = datos_hotel['url'] email_hotel = datos_hotel['email'] phone_hotel = datos_hotel['phone'] body_hotel = datos_hotel['body'] zipcode_hotel = datos_hotel['zipcode'] pais_hotel = datos_hotel['country'] latitud_hotel = datos_hotel['latitude'] longitud_hotel = datos_hotel['longitude'] cuidad_hotel = datos_hotel['subAdministrativeArea'] new_hotel = Hotel(nombre=nombre_hotel, email=email_hotel, phone=phone_hotel, body=body_hotel, web=web_hotel, direccion=direccion_hotel, zipcode=zipcode_hotel, pais=pais_hotel, latitud=latitud_hotel, longitud=longitud_hotel, cuidad=cuidad_hotel, categoria=categoria_hotel, subcategoria=subcategoria_hotel, imagenes=imagenes_hotel) new_hotel.save() return resp
def inicio(request): global longitud longitud =10 hoteles = Hotel.objects.all() if(len(hoteles) == 0): lista = {} lista = parse('es') respuesta ="" for elem in lista: #print ("prueba" + elem["name"]) try: elem["subcat"] except Exception as e: elem["subcat"] = "Undefined" object_hotel = Hotel(nombre=elem["name"],address=elem['address'], phone=elem['phone'],body=elem['body'],web=elem['web'], cat=elem['cat'],subcat=elem["subcat"],nComentario=0) object_hotel.save() idHotel = object_hotel.id for url in elem["url"]: objectImagen = Imagen(hotelId=idHotel,url=url) objectImagen.save()
def startElement (self, name, attrs): self.theContent=name if name =='basicData': self.record = Hotel(name="", url="", address="",source="",stars="",tipo="") if name =="item": if attrs['name']== "SubCategoria": self.is_star=True; if name =="item": if attrs['name']== "Categoria": self.is_cat=True; if name =='media': if attrs['type']== "image": self.is_img=True self.recimg=Imagen(hid=0,img=self.record,url="")
def startElement (self, name, attrs): #print "In startElement on myContentHandler" self.contador = self.contador + 1 print "Numero Hotel: ", self.contador self.tag = name if name == 'basicData': self.record = Hotel(nombreHotel="",email="",telefono="", descripcion="",webUrl="",direccion="",latitude="", longitude="",imageNum=0,imageUrls=[],categoria="",estrellas="",firstFoto="", numcomentarios=0) if name == "item": if attrs['name'] == "Categoria": self.tiene_categoria = True; if attrs['name'] == "SubCategoria": self.tiene_estrellas = True; if name == "media": if attrs['type'] == "image": self.tiene_imagenes = True
class myContentHandler(ContentHandler): def __init__(self): #print "In __init__ on myContentHandler" self.contador = 0 self.record = None; #La etiqueta de los diferentes campos del XML que se iran recorriendo self.tag = "" #Los campos de nuestro modelo self.nombreHotel = "" self.email = "" self.telefono = "" self.descripcion = "" self.wedUrl = "" self.direccion = "" self.latitude = "" self.longitude = "" self.imageNum = 0 self.imageUrls = [] self.firstFoto = "" #categoria y estrellas self.tipo = "" #Para buscar dentro de item self.tiene_imagenes = False self.tiene_categoria = False self.tiene_estrellas = False def startElement (self, name, attrs): #print "In startElement on myContentHandler" self.contador = self.contador + 1 print "Numero Hotel: ", self.contador self.tag = name if name == 'basicData': self.record = Hotel(nombreHotel="",email="",telefono="", descripcion="",webUrl="",direccion="",latitude="", longitude="",imageNum=0,imageUrls=[],categoria="",estrellas="",firstFoto="", numcomentarios=0) if name == "item": if attrs['name'] == "Categoria": self.tiene_categoria = True; if attrs['name'] == "SubCategoria": self.tiene_estrellas = True; if name == "media": if attrs['type'] == "image": self.tiene_imagenes = True def endElement (self, name): #print "In endElement on myContentHandler" if self.tag == 'title': self.record.nombreHotel = self.nombreHotel self.record.save() if self.tag == 'email': self.record.email = self.email self.record.save() if self.tag == 'phone': self.record.telefono = self.telefono self.record.save() if self.tag == 'body': self.record.descripcion = self.descripcion self.record.save() if self.tag == 'web': self.record.webUrl = self.webUrl self.record.save() if self.tag == 'address': self.record.direccion = self.direccion self.record.save() if self.tag == 'latitude': self.record.latitude = self.latitude self.record.save() if self.tag == 'longitude': self.record.longitude = self.longitude self.record.save() if self.tag == 'url' and self.tiene_imagenes: #print "contador: ", self.contador, self.imageUrls if self.record.firstFoto == "": self.record.firstFoto = self.imageUrls self.record.imageUrls.append(self.imageUrls) self.record.imageNum = self.record.imageNum + 1 self.record.save() if self.tag == 'item' and self.tiene_categoria: #print "JOIN TO TIENE CATEGORIA" self.record.categoria = self.tipo self.record.save() self.tiene_categoria = False if self.tag == 'item' and self.tiene_estrellas: #print "JOIN TO TIENE ESTRELLAS" self.record.estrellas = self.tipo self.record.save() self.tiene_estrellas = False self.tag = "" def characters (self, chars): #print "In characters on myContentHandler" if self.tag == 'title': self.nombreHotel = chars if self.tag == 'email': self.email = chars if self.tag == 'phone': self.telefono = chars if self.tag == 'body': self.descripcion = chars if self.tag == 'web': self.webUrl = chars if self.tag == 'address': self.direccion = chars if self.tag == 'latitude': self.latitude = chars if self.tag == 'longitude': self.longitude = chars if self.tag == 'url': self.imageUrls = chars #categoria y estrellas if self.tag == 'item': self.tipo = chars
class myContentHandler(ContentHandler): def __init__ (self): self.record=None; self.theContent = "" self.titulo="" self.url="" self.dir="" self.img="" self.tipo="" self.recimg=None self.is_star=False; self.is_img=False; self.is_cat =False; def startElement (self, name, attrs): self.theContent=name if name =='basicData': self.record = Hotel(name="", url="", address="",source="",stars="",tipo="") if name =="item": if attrs['name']== "SubCategoria": self.is_star=True; if name =="item": if attrs['name']== "Categoria": self.is_cat=True; if name =='media': if attrs['type']== "image": self.is_img=True self.recimg=Imagen(hid=0,img=self.record,url="") def endElement (self, name): if self.theContent=='item' and self.is_star: self.record.stars=self.tipo self.record.save(); self.is_star=False; if self.theContent=='item' and self.is_cat: self.record.tipo=self.tipo self.record.save(); self.is_cat=False; if self.theContent == 'url' and self.is_img: self.record.source=self.img self.recimg.img=self.record self.recimg.url=self.img; self.recimg.hid=self.record.id; self.record.save() self.recimg.save() print self.recimg.img.id print self.record.id print self.recimg.url self.is_img=False if self.theContent == 'title': self.record.name=self.titulo; self.record.save() elif self.theContent == 'web': self.record.url=self.url self.record.save() #print self.url elif self.theContent == 'address': self.record.address=self.dir self.record.save() #print self.theContent self.theContent="" #record.save() def characters (self, chars): if self.theContent == 'title': self.titulo=chars elif self.theContent == 'web': self.url=chars elif self.theContent == 'address': self.dir=chars elif self.theContent == 'url': self.img=chars elif self.theContent == 'item': self.tipo=chars
def alojamiento(request, indice): encontrado = False hoteles = Hotel.objects.all() imagenes = Imagen.objects.all() comentarios = Comentario.objects.all() listafinal = [] listaimagenes = [] listacomentarios = [] listaparaenviar = [] listahoteles = [] autenticado = False contador = 0 for hotel in hoteles: if (hotel.hotel_id == indice): totalimagenes = 0 indicecomentario = 1 encontrado = True for imagen in imagenes: if ((imagen.hotel_id == hotel.hotel_id) and (totalimagenes < 5)): totalimagenes = totalimagenes + 1 listaimagenes.append(imagen) for comentario in comentarios: if (comentario.hotel_id == hotel.hotel_id): try: comentario = comentario.Cuerpo.split("=")[1] buscar = '+' reemplazar = ' ' comentario = comentario.replace(buscar, reemplazar) listacomentarios.append(comentario) indicecomentario = indicecomentario + 1 except IndexError: listacomentarios.append(comentario.Cuerpo) indicecomentario = indicecomentario + 1 listahoteles.append(hotel) if request.user.is_authenticated() and encontrado == True: autenticado = True if request.method == 'POST': comentario = request.body if (comentario.split("=")[0] == 'mibotondeopcion'): if comentario.split("=")[1] == 'Ingl': theParser = make_parser() theHandler = myContentHandler() theParser.setContentHandler(theHandler) url = ("http://cursosweb.github.io/etc/alojamientos_en.xml") xmlFile = urlopen(url) theParser.parse(xmlFile) lista = theHandler.dameLista() for dic in lista: h = Hotel(hotel_id=dic["id"], nombre=dic["nombre"], email=dic["email"], telefono=dic["telefono"], cuerpo=dic["cuerpo"], web=dic["web"], address=dic["address"], pais=dic["pais"], latitud=dic["latitude"], longitud=dic["longitude"], subAA=dic["subAdministrativeArea"], idTipo=dic["idTipo"], Tipo=dic["Tipo"], idCategoria=dic["idCategoria"], Categoria=dic["Categoria"], idSubCategoria=dic["idSubCategoria"], subCategoria=dic["SubCategoria"], NumComentarios=0) if (h.hotel_id == indice): listahoteles.append(h) elif comentario.split("=")[1] == 'Fran': theParser = make_parser() theHandler = myContentHandler() theParser.setContentHandler(theHandler) url = ("http://cursosweb.github.io/etc/alojamientos_fr.xml") xmlFile = urlopen(url) theParser.parse(xmlFile) lista = theHandler.dameLista() for dic in lista: h = Hotel(hotel_id=dic["id"], nombre=dic["nombre"], email=dic["email"], telefono=dic["telefono"], cuerpo=dic["cuerpo"], web=dic["web"], address=dic["address"], pais=dic["pais"], latitud=dic["latitude"], longitud=dic["longitude"], subAA=dic["subAdministrativeArea"], idTipo=dic["idTipo"], Tipo=dic["Tipo"], idCategoria=dic["idCategoria"], Categoria=dic["Categoria"], idSubCategoria=dic["idSubCategoria"], subCategoria=dic["SubCategoria"], NumComentarios=0) if (h.hotel_id == indice): listahoteles.append(h) else: respuesta = respuesta elif (comentario.split("=")[0] == 'seleccion'): ahora = datetime.now() u = Elegidos(Nombre=request.user.username, Fecha=ahora, hotel_id=indice) u.save() else: for hotel in hoteles: if (hotel.hotel_id == indice): comentario = request.body.split("=")[1] buscar = '+' reemplazar = ' ' comentario = comentario.replace(buscar, reemplazar) c = Comentario(Cuerpo=comentario, hotel_id=indice) c.save() hotel.NumComentarios = hotel.NumComentarios + 1 listacomentarios.append(comentario) listafinal.append((listahoteles, listaimagenes, listacomentarios)) listaparaenviar.append((listafinal, autenticado)) template = get_template('alojamiento.html') Context = RequestContext(request, {'lista': listaparaenviar}) return HttpResponse(template.render(Context))
def list_hotels(): hotels = Hotel.all().fetch(None) return jsonutil.encode(hotels)
def hotel_reviews(hotel_id): hotel = Hotel.get_by_id(hotel_id) reviews = hotel.reviews return jsonutil.encode(reviews)
def show_hotel_by_number(number): q = Hotel.all() hotel_list = q.filter("number = ", number) return jsonutil.encode(hotel_list)
def show_hotel_by_name(name): q = Hotel.all() hotel_list = q.filter("name = ", name) return jsonutil.encode(hotel_list)
def show_aloj_id(request, id): lista = Hotel.objects.get(id=id) listimages = Image.objects.filter(hid=lista.id) listauser = PagUser.objects.all() listcoms = "" hoteles = Hotel.objects.filter(id=id) listahoteles = Hotel.objects.all() if request.method == 'POST' and 'like' in request.POST: print lista.puntuacion lista.puntuacion = lista.puntuacion + 1 h_megusta = Hotel(id=id, name=lista.name, url=lista.url, body=lista.body, address=lista.address, source=lista.source, stars=lista.stars, tipo=lista.tipo, puntuacion=lista.puntuacion) h_megusta.save() if request.method == 'POST' and 'quiero' in request.POST: print "aqui" h_us = HotelsUser(hotel=lista, user=request.user.username) h_us.save() if request.method == 'POST' and 'comentario' in request.POST: value = request.POST.get('comentarios', "") if value != "": comment = Comment(hid=lista.id, com=lista, text=value) comment.save() listcoms = Comment.objects.filter(hid=lista.id) context = { 'lista': listimages[0:5], 'h': hoteles, 'condicion': "", 'url': lista.url, 'name': lista.name, 'body': lista.body, 'address': lista.address, 'comentarios': listcoms, 'type': lista.tipo, 'stars': lista.stars, 'puntuacion': lista.puntuacion, 'user': request.user.username, 'listausers': listauser } if request.user.is_authenticated(): us = PagUser.objects.get(user=request.user.username) context = { 'lista': listimages[0:5], 'h': hoteles, 'condicion': "", 'url': lista.url, 'name': lista.name, 'address': lista.address, 'comentarios': listcoms, 'type': lista.tipo, 'stars': lista.stars, 'body': lista.body, 'color': us.color, 'size': us.size, 'user': request.user.username, 'listausers': listauser } return render_to_response('alojid.html', context, context_instance=RequestContext(request))
def show_hotel_by_id(hotel_id): hotel = Hotel.get_by_id(hotel_id) return jsonutil.encode(hotel)
class myContentHandler(ContentHandler): def __init__(self): self.record = None self.theContent = "" self.titulo = "" self.url = "" self.dir = "" self.img = "" self.tipo = "" self.body = "" self.recimg = None self.is_star = False self.is_img = False self.is_cat = False def startElement(self, name, attrs): self.theContent = name if name == 'basicData': self.record = Hotel(name="", url="", body="", address="", source="", stars="", tipo="") if name == "item": if attrs['name'] == "SubCategoria": self.is_star = True if name == "item": if attrs['name'] == "Categoria": self.is_cat = True if name == 'media': if attrs['type'] == "image": self.is_img = True self.recimg = Image(hid=0, img=self.record, url="") def endElement(self, name): if self.theContent == 'body': self.record.body = self.body self.record.save() if self.theContent == 'item' and self.is_star: self.record.stars = self.tipo self.record.save() self.is_star = False if self.theContent == 'item' and self.is_cat: self.record.tipo = self.tipo self.record.save() self.is_cat = False if self.theContent == 'url' and self.is_img: self.record.source = self.img self.recimg.img = self.record self.recimg.url = self.img self.recimg.hid = self.record.id self.record.save() self.recimg.save() print self.recimg.img.id print self.record.id print self.recimg.url self.is_img = False if self.theContent == 'title': self.record.name = self.titulo self.record.save() #print self.titulo elif self.theContent == 'web': self.record.url = self.url self.record.save() #print self.url elif self.theContent == 'address': self.record.address = self.dir self.record.save() #print self.theContent self.theContent = "" #record.save() def characters(self, chars): if self.theContent == 'body': self.body = chars if self.theContent == 'title': self.titulo = chars elif self.theContent == 'web': self.url = chars elif self.theContent == 'address': self.dir = chars elif self.theContent == 'url': self.img = chars elif self.theContent == 'item': self.tipo = chars