Beispiel #1
0
	def post(self):
		try:
			result = None               
			logging.info("EANHotelRequest")
			config_properties = configparsers.loadPropertyFile('config')
			
			memcacheExpires = config_properties.getfloat('Env', 'memcache_expires')
			
			arrivalDateRaw = self.request.get('arrivalDate')
			numberOfNights = self.request.get('nights')
			priceSort = self.request.get("priceSort")
			ratingSort = self.request.get("ratingSort")
			city = self.request.get('city')
			hotelBrand = self.request.get('brand')
			
			arrivalDateList = arrivalDateRaw.split('-')
			arrivalDate = None
			departureDate = None
			price = None
			priceRaw = self.request.get("priceMax")
			if priceRaw is not None and priceRaw != '':
				price = float(priceRaw)
				
			global_mashup = {}
			
			destination = re.sub(r'(<|>|\s)', '', city)
			destination = destination.lower()
			global_mashup['destination'] = destination
			
			logging.debug(self.request.arguments())
			
			try:
				arrivalDate = datetime.datetime(int(arrivalDateList[2]), int(arrivalDateList[1]), int(arrivalDateList[0]))
				departureDateTimeDelta = datetime.timedelta(days=int(numberOfNights))
				departureDate = arrivalDate + departureDateTimeDelta
			except ValueError, e:
				logging.exception(e)
				logging.exception("EANHotelRequest : Invalid date values or date format")
			
			if arrivalDate is not None and departureDate is not None:
				# Memcache Key convention:
				# CITY:MAX_PRICE:ARRIVAL_DATE:DEPARTURE_DATE:BRAND
				#memcacheKey = str(city)+":"+str(price)+":"+str(arrivalDate.date().isoformat())+":"+str(departureDate.date().isoformat())+":"+str(priceSort)+":"+str(ratingSort)+":"+str(hotelBrand)
				memcacheKey = str(city)+":"+str(arrivalDate.date().isoformat())+":"+str(departureDate.date().isoformat())+":"+str(hotelBrand)
				logging.debug(memcacheKey)
				memcachedHotels = memcache.get(key=memcacheKey, namespace='ean')
				logging.info("Looking up MEMCACHE for : "+memcacheKey)
				
				if memcachedHotels is not None:
					result = memcachedHotels
					logging.debug("Got hotels from memcache")
					
				else:	
					logging.debug("Memcache empty, requesting hotels")
					destination = city.lower()
					if destination == 'europe':
						hotelsData = datastore.get_hotels_by_region(destination, None)
						logging.info(hotelsData)
					else:

						requestArgs = utils.ean_get_hotel_list_url(arrivalDate.date().isoformat(), departureDate.date().isoformat(), city, hotelBrand, self.request)
						logging.info('EAN Hotel request args')
						logging.info(requestArgs)

						try: 
							requestServiceURL = config_properties.get('EAN', 'xml_url_hotellist')
							f = urllib.urlopen(""+requestServiceURL+"%s" % requestArgs)
							response = f.read()
							logging.info('EAN service reponse body')
							logging.info(response)
							response = response.replace('&gt;','>')
							response = response.replace('&lt;','<')
							
						except (apiproxy_errors.ApplicationError, DeadlineExceededError), e:
							logging.exception("EANHotelRequest : DeadlineExceededError error")
							logging.exception(e) 
							global_mashup['name'] = city
							path = os.path.join(os.path.dirname(__file__),'templates/version3/includes/service-error.html')
							self.response.out.write(template.render(path, global_mashup))
							return
				
						try:
							jsonLoadResponse = json.loads(response)	
						except Exception, e:
							logging.exception(e)
							raise e
						
						logging.info('jsonLoadResponse')
						logging.info(jsonLoadResponse)
						
						global_mashup['name'] = city
						if utils.destination_display_names.has_key(city):
							global_mashup['name'] = utils.destination_display_names[city]

						if jsonLoadResponse['HotelListResponse'] is not None:
							if jsonLoadResponse['HotelListResponse'].has_key('HotelList'):
								if jsonLoadResponse['HotelListResponse']['HotelList']['HotelSummary'] is not None:
									result = jsonLoadResponse['HotelListResponse']['HotelList']['HotelSummary']
									if isinstance(result, list):
										for hotel in result:
											if hotel.has_key('thumbNailUrl'):
												hotel['mainImageUrl'] = hotel['thumbNailUrl'].replace('_t', '_b')
									elif isinstance(result, dict):
										tempResult = list()
										tempResult.append(result)
										result = tempResult
										for hotel in result:
											if hotel.has_key('thumbNailUrl'):
												hotel['mainImageUrl'] = hotel['thumbNailUrl'].replace('_t', '_b')
					
						if result is not None:
							# Add the datastore write to the taskqueue
							for hotel in result:
								existingHotel = datamodel.EANHotel.get_by_key_name(str(hotel['hotelId']))
								if existingHotel is None:
									logging.info("EANHotelRequest() : Hotel with hotelid "+str(hotel['hotelId'])+" DOES NOT exist. Assigning task to queue")
									taskqueue.add(queue_name='eanhotelsqueue', url='/eanhotelsworker', params={'hotel':json.dumps(hotel)})
								else: 
									logging.info("EANHotelRequest() : Hotel with location id "+str(hotel['hotelId'])+" DOES exist. No task queue necessary")
								# Add the new price data for this hotel
								taskqueue.add(queue_name='eanhotelspricequeue', url='/eanhotelspriceworker', params={'hotel':json.dumps(hotel), 'arrivalDate':str(arrivalDate.date().isoformat()), 'departureDate':str(departureDate.date().isoformat())})
			
								# Add Hotel details
								#taskqueue.add(queue_name='eanhoteldetailsqueue', url='/eanhoteldetailsworker', params={'hotelid':str(hotel['hotelId'])})
							
								# Get Geonames Wikipedia Data
								
								#wikipediaData = geonames.geonames_find_nearby_wikipedia('en', hotel['latitude'], hotel['longitude'], 10, 5, 'us')
								#hotel['geonames'] = wikipediaData
							# Add the hotel results to Memcache
							memcache.set(key=memcacheKey, value=result, time=memcacheExpires, namespace='ean')
Beispiel #2
0
		self.response.out.write(template.render(path, global_mashup))
	else:
		
		memcacheKey = str(destination)+":"+str(price)+":"+str(startDate.date().isoformat())+":"+str(endDate.date().isoformat())
		memcachedHotels = memcache.get(key=memcacheKey, namespace='lastminute')
		logging.info("Looking up MEMCACHE for : "+memcacheKey)
		logging.info(memcachedHotels)
		if memcachedHotels is not None:
			global_mashup['hotels'] = memcachedHotels
			path = os.path.join(os.path.dirname(__file__),'templates/version3/includes/'+info_type+'.html')
			self.response.out.write(template.render(path, global_mashup))
			logging.info("AjaxAPIHandler_v3() : Retrieving Hotels from MEMCACHE for destination "+str(destination))
		else:
			regions = utils.get_regions()
			if destination in regions:
				hotelsData = datastore.get_hotels_by_region(destination, price)
				logging.info(hotelsData)
				if hotelsData is None:
					logging.info("No results for "+str(destination))
					path = os.path.join(os.path.dirname(__file__),'templates/version3/includes/no-results.html')
					self.response.out.write(template.render(path, global_mashup))
					return
				logging.info("Setting hotels to MEMCACHE with key : "+memcacheKey)
				memcache.set(key=memcacheKey, value=hotelsData, time=6000, namespace='lastminute')
				global_mashup['region'] = destination
				
			else:
				# [ST]TODO: Reinstate arguments: rating
			    hotelsData = datastore.get_hotels(destination, price, startDate, endDate, None)
			
			if hotelsData is not None: