def panoramio_ranking(city_id): cobj = getCityObject(id=city_id) if cobj is None: return None panoramio_resp = _open_panoramio_conn((cobj.coordinates.x,cobj.coordinates.y),1) if(panoramio_resp is None): return 0 return decimal.Decimal(str(panoramio_resp['count']))
def _getClosestAirports(dfrom): city = getCityObject(id=dfrom) if city is None: return None #return HttpResponseNotFound('City Not Found') # up to 20 airprots, with a distance <= 300 km closest_airports = Station.objects.filter( coordinates__distance_lt= (city.coordinates,D(km=300))).transform().distance(city.coordinates)[:20] # city representation jsonCity = {"name": city.name, "x" : city.coordinates.x, "y" : city.coordinates.y, "id" : city.id, "slug": city.slug} jsonSet = {"city" : jsonCity, "airports": None} jsonObj = [] minimumSelection = False minimumSelectionNum = 10 if (len(closest_airports) < minimumSelectionNum): closest_airports = Station.objects.filter(coordinates__distance_lt=(city.coordinates,D(km=500))).distance(city.coordinates) #closest_airports.sort(lambda x,y: x.distance - y.distance) minimum_selection = True for c in closest_airports: jsonElem = {'code' : c.code_alt, 'name' : unicode(urllib.quote(c.short_name.encode('utf8')," ,-")), 'distance': c.distance.km, 'x' : c.coordinates.x, 'y' : c.coordinates.y } jsonObj.append(jsonElem) jsonObj.sort(lambda x,y: int(math.floor(x['distance']-y['distance']))) if (minimumSelection): jsonObj = jsonObj[:minimumSelectionNum] jsonSet['airports'] = jsonObj #response = simplejson.dumps(jsonSet) #response = response.replace("{", "\n{") return jsonSet
def panoramio_set(city_id): cobj = getCityObject(id=city_id) if cobj is None: return None panoramio_resp = _open_panoramio_conn((cobj.coordinates.x,cobj.coordinates.y)) if(panoramio_resp is None): return None response = [] for p in panoramio_resp['photos']: this_entry = {'href': p['photo_url'], 'src' : p['photo_file_url'], 'alt' : p['photo_title'], } response.append(this_entry) return response
def _getCityFromName(dfrom): city = getCityObject(name=dfrom) response = None if city is None: return None else: jsonObject = { 'city': unicode(urllib.quote(city.name.encode('utf8')," ,-")), 'latitude': float(city.latitude), 'longitude': float(city.longitude), } #json_ser = serializers.get_serializer('json')() #json_ser.serialize(city,ensure_ascii=False) #return (json.write(jsonObject).encode("utf8")) return jsonObject
def yahootravel_ranking(city_id): cobj = getCityObject(id=city_id) query_array = cobj.name.lower().split(" ") if(cobj.region is not None): query_array.append("\""+cobj.region.name.lower()+"\"") query_array.append("\""+cobj.country.name.lower()+"\"") my_wikiname = re.sub(ur"[,\.:();]", " ", cobj.wikiname) my_wikiname = re.sub(ur" {2,}", " ", my_wikiname) query_array = query_array + my_wikiname.split(" ") yt_query = " ".join(set(query_array)) yt_url = """http://travel.yahooapis.com/TripService/V1.1/tripSearch?appid=%s&query=%s&results=%d&output=json""" % (YAHOO_DEVAPP_ID, urllib.quote(yt_query.encode('utf-8')), 10) httpsched = get_http_scheduler() httpwhat = httpsched.urlopen(service="yahootravel",url=yt_url,json=True,alt_delta=2) if (not httpwhat.has_key('ResultSet')): return None if (not httpwhat['ResultSet'].has_key('totalResultsAvailable')): return None return int(httpwhat['ResultSet']['totalResultsAvailable'])
def weather_conditions(city_id): # weather conditions by Google cobj = getCityObject(id=city_id) if cobj is None: return None weather_url = u"http://www.google.com/ig/api?weather=%s,%s&hl=en-gb" % (urllib.quote(cobj.name.encode('utf-8')), urllib.quote(cobj.country.name.encode('utf-8'))) httpresp = urllib2.urlopen(weather_url) httpcont = httpresp.read() #the usual unicode mess httpwhat = httpcont.replace('<?xml version="1.0"?>','<?xml version="1.0" encoding="ISO-8859-15"?>').decode('latin1').encode('latin1') xmlresp = minidom.parseString(httpwhat) success = xmlresp.getElementsByTagName('problem_cause') dataresp = {} if len(success) == 1: return None # unsuccessful response (city not found) current_cond = xmlresp.getElementsByTagName('current_conditions') forecast_cond = xmlresp.getElementsByTagName('forecast_conditions') if (len(current_cond) == 0 or len(forecast_cond) == 0): return None # unsuccessful response (expected data not found) base_icon_url = 'http://www.google.com' # current conditions current_cond = current_cond[0] dataresp['current'] = {'temp' : current_cond.getElementsByTagName('temp_c')[0].getAttribute('data'), 'condition': current_cond.getElementsByTagName('condition')[0].getAttribute('data'), 'icon' : base_icon_url+current_cond.getElementsByTagName('icon')[0].getAttribute('data'), } forecast_resp = [] # forecast conditions for fc in forecast_cond: this_entry = {'temp_low' : fc.getElementsByTagName('low')[0].getAttribute('data'), 'temp_high': fc.getElementsByTagName('high')[0].getAttribute('data'), 'condition': fc.getElementsByTagName('condition')[0].getAttribute('data'), 'icon' : base_icon_url+fc.getElementsByTagName('icon')[0].getAttribute('data'), 'day' : fc.getElementsByTagName('day_of_week')[0].getAttribute('data'), } forecast_resp.append(this_entry) dataresp['forecast'] = forecast_resp return dataresp
def _wikipedia_article(city_id,more='City'): if(more == 'City'): cobj = getCityObject(id=city_id) elif(more == 'Country'): cobj = Country.objects.get(id=city_id) else: cobj = None if cobj is None: return None dab_re = "{{disambig}}" #step 1: tries to access the direct page article httpwhat = None if (cobj.wikiname is not None): httpwhat = _open_wiki_url(cobj.wikiname) if (httpwhat is None): httpwhat = _open_wiki_url(cobj.name) httpwikiname = None if(httpwhat is not None and re.search(dab_re,httpwhat['content']) is None): # Apparently FOUND pass else: httpwhat = None if(cobj.local_name is not None): httpwhat = _open_wiki_url(cobj.local_name) if(httpwhat is None): query_array = [] query_array += cobj.name.split(" ") query_array += cobj.country.name.split(" ") base_url = 'http://en.wikipedia.org/w/api.php?action=query&redirects&list=search&srsearch=%s&format=json' % "+".join(query_array) httpsched = get_http_scheduler() jsonresp = httpsched.urlopen(service="wikipedia",url=base_url.encode('utf-8'),json=True) if(not jsonresp.has_key('query')): return None if(not jsonresp['query'].has_key('search')): return None if(len(jsonresp['query']['search'])==0): return None httpwhat = _open_wiki_url(jsonresp['query']['search'][0]['title']) #if (httpwhat is None): return None return httpwhat
def _getClosestCities(dfrom,more=None): #city = __getCityObjectFromName(dfrom) city = getCityObject(id=dfrom) if city is None: return None c_distance = 300 c_limit = 250 c_randomize = False c_cycle = True c_usecache = False if(more is None): pass else: if(more.has_key('distance') and more['distance'] is not None): c_distance=more['distance'] if(more.has_key('limit') and more['limit'] is not None): c_limit=more['limit'] if(more.has_key('randomize') and more['randomize'] is not None): c_randomize=more['randomize'] if(more.has_key('usecache') and more['usecache'] is True): c_usecache = True jsonObj = None if(c_usecache): # whole set of nearby cities can be cached - # they are stored purely, with no randomization or selection c_cache_key = "remote.getClosestCities[%d]" % (dfrom) c_cache_timeout = 60*60*24*5 # 5 days jsonObj = cache.get(c_cache_key) if(jsonObj is None): # nothing cached yet # the big deal - retrieving all nearby cities c_distance_base = c_distance * 0.667 while(c_cycle): closest_cities = City.objects.filter(coordinates__distance_lt=(city.coordinates,D(km=c_distance))).transform().distance(city.coordinates) if(len(closest_cities)<(c_limit+1)): c_distance = c_distance + c_distance_base else: c_cycle = False jsonObj = [] # selecting and converting to a proper format to be returned as json for c in closest_cities: if (c != city): jsonElem = {"name": c.name, "country": c.country.name, "x": c.coordinates.x, "y": c.coordinates.y, "distance": c.distance.km, "slug": c.slug, "id": c.pk } if (c.local_name is not None and c.local_name != ''): jsonElem["local_name"] = c.local_name jsonObj.append(jsonElem) jsonCity = {"name": city.name, "x": city.coordinates.x, "y": city.coordinates.y} jsonSet = {"city": jsonCity, "nearby_cities": None} if (c_usecache): cache.set(c_cache_key,jsonObj,c_cache_timeout) # store into cache if (c_randomize): random.shuffle(jsonObj) if (c_limit is not None and c_limit > 0): jsonObj = jsonObj[:c_limit] jsonObj.sort(lambda x,y: int(math.floor(x['distance']-y['distance']))) jsonSet['nearby_cities'] = jsonObj return jsonSet
def _getCityCoordinates(dfrom): city = getCityObject(name=dfrom) if city is None: return None return city.coordinates
def getCityObjectFromName(dfrom): return getCityObject(name=dfrom)