def getResults( attribute, search ): #attribute = if it is a holiday, cusine, or ingredient #search = their actual input #need to take into account if their search is not a real holiday url = "" if attribute == "holiday": url = "http://api.yummly.com/v1/api/recipes?maxResult=100&_app_id=dd74dd78&_app_key=992e5769b7da1040ad87d47328a4182e&q=&allowedHoliday[]=holiday^holiday-" + search.lower() elif attribute == "cuisine": '''American, Italian, Asian, Mexican, Southern & Soul Food, French, Southwestern, Barbecue, Indian, Chinese, Cajun & Creole, English, Mediterranean, Greek, Spanish, German, Thai, Moroccan, Irish, Japanese, Cuban, Hawaiin, Swedish, Hungarian, Portugese ''' url = "http://api.yummly.com/v1/api/recipes?maxResult=100&_app_id=dd74dd78&_app_key=992e5769b7da1040ad87d47328a4182e&q=&allowedCuisine[]=cuisine^cuisine-" + search.lower() else: url = "http://api.yummly.com/v1/api/recipes?maxResult=100&_app_id=dd74dd78&_app_key=992e5769b7da1040ad87d47328a4182e&q=" search = search.split(",") for ingredient in search: url += "&allowedIngredient[]=" + ingredient.lower() request = urllib2.urlopen(url) result = request.read() d = json.loads(result) results=d["matches"] #print url return json.loads( result )
def answer(word): """ gets word that user entered in home page and uses etymology api to display its etymology """ key="a2a73e7b926c924fad7001ca3111acd55af2ffabf50eb4ae5" url="http://api.wordnik.com:80/v4/word.json/%s/etymologies?useCanonical=true&api_key=%s" #print "\n\n\n\nWAKAKA " + word + " AKAKAW\n\n\n\n" try: url = url%(word,key) request = urllib2.urlopen(url) result = request.read() r = json.loads(result) x = r[0][38:] print x x = x.replace("<ety>","") x = x.replace("</ety>","") x = x.replace("<ets>","") x = x.replace("</ets>","") x = x.replace("[","") x = x.replace("]","") x = x.replace("<er>","") x = x.replace("</er>","") x = x.replace("fr.","//from") x = x.replace("cf.","//-//cf.") x = x.replace("Cf.","//-//cf.") d = x.split("//") print str(d) return render_template("answer.html",word=word, etymology=d, error=False) except: return render_template("answer.html",error=True, word="bad word", etymology=["no etymology for that word, try again"])
def nameTo(add): #add = "1600+Amphitheatre+Parkway,+Mountain+View,+CA" add = add.replace(" ", "+") print add key = "AIzaSyC1HeKfjwS4x0KYw_Wgl5-IxLBELfa4oO0" query = "https://maps.googleapis.com/maps/api/geocode/json?address=%s&key=%s" % ( add, key) print query #%s&go=&qs=n&sk=&sc=8-13&first=%s' % (quoted_query, page) request = urllib2.urlopen(query) result = request.read() result = json.loads(result) dict = {} if (result["status"] != "OK"): dict["ERROR"] = result["status"] else: lat = result["results"][0]["geometry"]["location"]["lat"] lng = result["results"][0]["geometry"]["location"]["lng"] full_address = result["results"][0]["formatted_address"] dict["lat"] = lat dict["long"] = lng dict["add"] = full_address dict["ERROR"] = "NO" #return jsonify(result) return dict
def config_check_update(): release_url = y['Git']['git_url_release'] print "Start getting latest release from Github: " + release_url try: request = urllib.urlopen(release_url) response = request.read() data = json.loads(response) if 200 == request.getcode(): return json.dumps({'results': 'true', 'msg': data['tag_name']}) else: return json.dumps({ 'results': 'false', 'msg': 'Connection issue: ' + str(request.getcode()) + "<br />" + data['message'] }) except Exception as e: print return json.dumps({ 'results': 'false', 'msg': "Network connection issue: <br />" + str(e) })
def getdict(): crowded_list=[] final_dict=[] final_dict2=[] url=geturl() request=urllib2.urlopen(url) result=request.read() d=json.loads(result) # extra_data=d['data'] data=extra_data['results'] for key in data: crowded_list.append(key) x=0 for value_dict in crowded_list: for value in value_dict: if value=='title': #or value=='prices': final_dict.append(value_dict[value]) x=x+1 for value_dict in crowded_list: for value in value_dict: if value=='prices': #or value=='prices': final_dict2.append(value_dict[value]) x=x+1 m = zip(final_dict,final_dict2) k= dict(m) return k
def getData(address): address = urllib2.quote(address, safe="%/:=&?~#+!$,;'@()*[]") url = "https://maps.googleapis.com/maps/api/geocode/json?address="+address+"&"+components+"&"+"sensor=false"+"&"+"key="+API_KEY request = urllib2.urlopen(url) #result = json.load(request) return request.read()
def nameTo(add): #add = "1600+Amphitheatre+Parkway,+Mountain+View,+CA" add = add.replace(" ","+") print add key = "AIzaSyC1HeKfjwS4x0KYw_Wgl5-IxLBELfa4oO0" query = "https://maps.googleapis.com/maps/api/geocode/json?address=%s&key=%s" % (add, key) print query #%s&go=&qs=n&sk=&sc=8-13&first=%s' % (quoted_query, page) request = urllib2.urlopen(query) result = request.read() result = json.loads(result) dict = {} if (result["status"] != "OK"): dict["ERROR"] = result["status"] else: lat = result["results"][0]["geometry"]["location"]["lat"] lng = result["results"][0]["geometry"]["location"]["lng"] full_address = result["results"][0]["formatted_address"] dict["lat"] = lat dict["long"] = lng dict["add"] = full_address dict["ERROR"] = "NO" #return jsonify(result) return dict
def t(): key="6qjbDDaQ4vUogvpFIZ2UoaHuo6ykn1vMpjRYOdYOPCQI6dBw4K" uri="https://api.tumblr.com/v2/tagged?tag=%s&api_key=%s" url1 = uri%("insect",key) request = urllib2.urlopen(url1) result = request.read() r = json.loads(result) url2 = uri%("animal",key) request2 = urllib2.urlopen(url2) result2 = request2.read() r2 = json.loads(result2) #r['response'][0]['photos'][0]['original_size']['url'] photos1=[] for item in r['response']: try: newphoto1 = item['photos'][0]['original_size']['url'] photos1.append(newphoto1) except: pass photos2=[] for item in r2['response']: try: newphoto2 = item['photos'][0]['original_size']['url'] photos2.append(newphoto2) except: pass return render_template("tagged.html",urls1=photos1,urls2=photos2)
def topRated(): key = "bb8c8b5dede831baad7b87391d01d20c" uri = "https://api.themoviedb.org/3/movie/top_rated?api_key=%s" url = uri%(key) request = urllib2.urlopen(url) result = request.read() r = json.loads(result) topRated = [] ids = [] for item in r['results']: topRated.append(item['title']) ids.append(item['id']) #solely for aesthetic purposes to separate into two columbs firstHalf = [] firstHalfIDs = [] secondHalf = [] secondHalfIDs = [] count = 0 for item in topRated: if count < 10: firstHalf.append(topRated[count]) firstHalfIDs.append(ids[count]) else: secondHalf.append(topRated[count]) secondHalfIDs.append(ids[count]) count += 1 return render_template("topmovies.html", firstTopMovies = firstHalf, secondTopMovies = secondHalf, firstIDs = firstHalfIDs, secondIDs = secondHalfIDs )
def post(self): logging.info("Calling external R process...") data = request.read() query = json.loads(data) if self.IDS in query: ids = query[self.IDS] else: # Invalid query invalid_input = { "message": "List of Entrez Gene ID is required for this service." } return invalid_input, 400 # Write IDs to temp file # Call R script as subprocess subprocess.call(['R', 'CMD', 'BATCH', './R/run.R']) logging.warn("Done! ================") result_msg = {"message": 'Done analysis'} return result_msg
def topRated(): key = "bb8c8b5dede831baad7b87391d01d20c" uri = "https://api.themoviedb.org/3/movie/top_rated?api_key=%s" url = uri % (key) request = urllib2.urlopen(url) result = request.read() r = json.loads(result) topRated = [] ids = [] for item in r['results']: topRated.append(item['title']) ids.append(item['id']) #solely for aesthetic purposes to separate into two columbs firstHalf = [] firstHalfIDs = [] secondHalf = [] secondHalfIDs = [] count = 0 for item in topRated: if count < 10: firstHalf.append(topRated[count]) firstHalfIDs.append(ids[count]) else: secondHalf.append(topRated[count]) secondHalfIDs.append(ids[count]) count += 1 return render_template("topmovies.html", firstTopMovies=firstHalf, secondTopMovies=secondHalf, firstIDs=firstHalfIDs, secondIDs=secondHalfIDs)
def tag(tag=""): try: url="http://vimeo.com/api/v2/channel/%s/videos.json" url = url%(tag) request = urllib2.urlopen(url) resultstring = request.read() result = json.loads(resultstring) titles = [] url = [] thumbnails = [] i = 0 while i < len(result): titles.append( result[i]["title"]) url.append(result[i]["url"]) thumbnails.append(result[i]["thumbnail_medium"]) i=i+1 print (titles) return render_template("search.html", titles = titles, url = url, thumbnails = thumbnails, all = result) except (urllib2.URLError): return('Sorry, that is not a valid channel.')
def t(): key = "6qjbDDaQ4vUogvpFIZ2UoaHuo6ykn1vMpjRYOdYOPCQI6dBw4K" uri = "https://api.tumblr.com/v2/tagged?tag=%s&api_key=%s" url1 = uri % ("insect", key) request = urllib2.urlopen(url1) result = request.read() r = json.loads(result) url2 = uri % ("animal", key) request2 = urllib2.urlopen(url2) result2 = request2.read() r2 = json.loads(result2) #r['response'][0]['photos'][0]['original_size']['url'] photos1 = [] for item in r['response']: try: newphoto1 = item['photos'][0]['original_size']['url'] photos1.append(newphoto1) except: pass photos2 = [] for item in r2['response']: try: newphoto2 = item['photos'][0]['original_size']['url'] photos2.append(newphoto2) except: pass return render_template("tagged.html", urls1=photos1, urls2=photos2)
def getResults(attribute, search): #attribute = if it is a holiday, cusine, or ingredient #search = their actual input #need to take into account if their search is not a real holiday url = "" if attribute == "holiday": url = "http://api.yummly.com/v1/api/recipes?maxResult=100&_app_id=dd74dd78&_app_key=992e5769b7da1040ad87d47328a4182e&q=&allowedHoliday[]=holiday^holiday-" + search.lower( ) elif attribute == "cuisine": '''American, Italian, Asian, Mexican, Southern & Soul Food, French, Southwestern, Barbecue, Indian, Chinese, Cajun & Creole, English, Mediterranean, Greek, Spanish, German, Thai, Moroccan, Irish, Japanese, Cuban, Hawaiin, Swedish, Hungarian, Portugese ''' url = "http://api.yummly.com/v1/api/recipes?maxResult=100&_app_id=dd74dd78&_app_key=992e5769b7da1040ad87d47328a4182e&q=&allowedCuisine[]=cuisine^cuisine-" + search.lower( ) else: url = "http://api.yummly.com/v1/api/recipes?maxResult=100&_app_id=dd74dd78&_app_key=992e5769b7da1040ad87d47328a4182e&q=" search = search.split(",") for ingredient in search: url += "&allowedIngredient[]=" + ingredient.lower() request = urllib2.urlopen(url) result = request.read() d = json.loads(result) results = d["matches"] #print url return json.loads(result)
def nameToNumbers(): add = "1600+Amphitheatre+Parkway,+Mountain+View,+CA" key = "AIzaSyC1HeKfjwS4x0KYw_Wgl5-IxLBELfa4oO0" query = "https://www.maps.googleapis.com/maps/api/geocode/json?address="+add+"&key="+key request = urllib2.urlopen(query) result = request.read() result = json.loads(result) return jsonify(result)
def tag(tag=""): url="http://api.tumblr.com/v2/tagged?tag=%s&api_key=aTQcvkZkpZbz7ILTsi8ekrUFE0maSPweft6mM1yyJhQBdnV5eb" url = url%(tag) request = urllib2.urlopen(url) resultstring = request.read() result = json.loads(resultstring) s = "" #semi-related tags rtags = {} for item in result['response']: # s = s + str(item) + "<br>" try: s+="<img src=%s>"%item['photos'][0]['original_size']['url'] t = item['tags'][0] if(t!="pokemon" or t!="Pokemon"): rtags[item['tags'][0]]="" except: pass #something weird where it goes through more tags and finds more things p="" for t in rtags.keys(): url="http://api.tumblr.com/v2/tagged?tag=%s&api_key=aTQcvkZkpZbz7ILTsi8ekrUFE0maSPweft6mM1yyJhQBdnV5eb" url = url%(t) # print url try: request = urllib2.urlopen(url) resultstring = request.read() result = json.loads(resultstring) p+="<br><br>"+t+"<br>" for item in result['response']: try: p += "<img src=%s>"%item['photos'][0]['original_size']['url'] except: pass except: print t if (s==""): print "hello" return redirect("/error") s += "<br><br><h3>Related Tags</h3><br>" + p return render_template("tag.html",body=s)
def getData(address): addArr = address.split(",",3); address = addArr[0]; url = "https://maps.googleapis.com/maps/api/geocode/json?address="+address+"&"+components+"&"+"sensor=false"+"&"+"key="+API_KEY request = urllib2.urlopen(url) #result = json.load(request) return request.read()
def getCitiJSON(): # returns a dictionary of Citibike station information url = "http://www.citibikenyc.com/stations/json" request = urllib2.urlopen(url) result = request.read() d = json.loads(result) rlist = d['stationBeanList'] return rlist
def root(): request = urlopen( 'https://api.nasa.gov/planetary/apod?api_key=YZpRGglnNl1Ud54e7aCcFRuPvAMrtgG3NYcEw5UB' ) response = request.read() data = json.loads(response) print(data) return render_template("index.html", pic=data)
def getAlbums(info): returndata = [] urlstring = base_url+'album.search&album='+info+api_base print urlstring request = urllib.urlopen(urlstring) result = json.loads(request.read()) for tmp in result['results']['albummatches']['album']: returndata.append(tmp['name']+' by '+ tmp['artist']) return returndata
def getSimilarTrack(info): similar = [] tmp = recoverTrackInfo(info) urlstring = base_url+'track.getSimilar&artist='+tmp[0]+'&track='+tmp[1]+api_base request = urllib.urlopen(urlstring) result = json.loads(request.read()) for item in results['similartracks']: similar.append([item['name'],item['artist']]) return similar
def artistTopTrack(info): title = '' urlstring = base_url+'artist.gettoptracks&artist='+info+api_base request = urllib.urlopen(urlstring) result = json.loads(request.read()) for item in result['toptracks']['track']: title = item['name'] break return title
def root(): request = urllib.request.urlopen( "https://api.nasa.gov/planetary/apod?api_key=anvhiZGKBhZdJmFMCGBAmH7lDGCGkR9fl56lkAoV" ) response = request.read() data = json.loads(response) return render_template("index.html", explanation=data['explanation'], pic=data['url'])
def example(): url = "http://api.openweathermap.org/data/2.5/weather?q=NYC&appid=ecdb9f3fb43f5f8663867db2633c7638&units=imperial" request = urllib2.urlopen(url) result = request.read() r = json.loads(result) temp = r['main']['temp'] name = r['name'] #return name + ", " + str(temp) return jsonify(r)
def example(): url="http://api.openweathermap.org/data/2.5/weather?q=NYC&appid=ecdb9f3fb43f5f8663867db2633c7638&units=imperial" request = urllib2.urlopen(url) result = request.read() r = json.loads(result) temp = r['main']['temp'] name = r['name'] #return name + ", " + str(temp) return jsonify(r)
def reverse_geo(ldic): googleurl = "https://maps.googleapis.com/maps/api/geocode/json?latlng=%s,%s&key=%s" % ( ldic['lat'], ldic['lng'], key) request = urllib2.urlopen(googleurl) result = request.read() d = json.loads(result) rdic = d['results'][0] address = rdic['formatted_address'] address = urllib.quote_plus(address) return address
def main(bbox, q): url = 'http://nominatim.openstreetmap.org/search/' + q + \ '?format=json&limit=1&viewbox=' + bbox + '&[email protected]' try: request = urllib2.urlopen(url) return request.read() except: return '[]'
def moreInfo(id): #might get an error if invalid recipe-id try: url = "http://api.yummly.com/v1/api/recipe/"+id+"?_app_id="+appid+"&_app_key="+appkey request = urllib2.urlopen(url) res_string = request.read() d = json.loads(res_string) #keys:totalTime,ingredientLines,attribution,name,rating,numberOfServings,yield,nutritionEstimates,source,flavors,images,attributes,id,totalTimeInSeconds return d; except: return False
def encode(image): """Base64 encode an external image resource.""" request = urlopen(image) size = request.headers.get('Content-Length') if int(size) > 900000: return 'That image is way too big.' encoding = request.headers.get('Content-Type').replace(' ', '') data_type = "data:%s;base64," % encoding data = base64.encodestring(request.read()).replace('\n', '') return data_type + data
def findFoods(tag): url = "http://api.yummly.com/v1/api/recipes?_app_id="+appid+"&_app_key="+appkey+"%s" url = url%(tag) request = urllib2.urlopen(url) res_string = request.read() d = json.loads(res_string) #This fixes an error where it would crash if no images were found,replace this with a better one if you want for x in d['matches']: if 'smallImageUrls' not in x.keys(): x['smallImageUrls']= "http://www.woodus.com/den/gallery/graphics/dqm4ds/monster/nopic.png" return d
def location_lookup(latitude, longitude): url='http://congress.api.sunlightfoundation.com/legislators/locate?apikey=ee03d2ba64534625b16f2b58662bc6cb&latitude=%s&longitude=%s&fields=last_name,first_name,bioguide_id,chamber'%(latitude, longitude) request = urllib2.urlopen(url) result = request.read() d = json.loads(result) try: # f = first, l = last # 0 - (0 - fn, 1 - ln, 2 - fn, 3 - ln, 4 - fn, 5 - ln ) 1 - (0 - sbio_id, 1 - hbio_id, 0 - hbio_id) 2 - (1 - chamber, 2 - chamber, 3 - chamber) return [ [ d['results'][0]['first_name'], d['results'][0]['last_name'], d['results'][1]['first_name'], d['results'][1]['last_name'], d['results'][2]['first_name'], d['results'][2]['last_name'] ], [ d['results'][0]['bioguide_id'], d['results'][1]['bioguide_id'], d['results'][2]['bioguide_id'] ], [ d['results'][0]['chamber'], d['results'][1]['chamber'], d['results'][2]['chamber'] ] ] except IndexError: return None
def vote_history(bioguide_id): url = 'http://congress.api.sunlightfoundation.com/votes?voter_ids.%s__exists=true&bill__exists=true&apikey=ee03d2ba64534625b16f2b58662bc6cb&fields=result,bill.short_title,bill.official_title,voters.%s,source'%(bioguide_id,bioguide_id) print url request = urllib2.urlopen(url) result = request.read() d = json.loads(result) past_votes = [] for i in d['results']: # 0 - bill name, 1 - abbreviated name, 2 - result, 3 - source, 4 - vote, 5 - website past_votes.append([ str(i['bill']['official_title']), str(i['bill']['short_title']), str(i['result']), str(i['source']), str(i['voters'][bioguide_id]['vote']), str(i['voters'][bioguide_id]['voter']['website']) ]) return past_votes
def t(tag="Narwhal"): url = "http://api.tumblr.com/v2/tagged?tag=%s&api_key=6qjbDDaQ4vUogvpFIZ2UoaHuo6ykn1vMpjRYOdYOPCQI6dBw4K" url = url%(tag) request = urllib2.urlopen(url) res_string = request.read() d = json.loads(res_string) page = "" for r in d['response']: if 'photos' in r.keys(): page = page +"<img height=200 src=y%s>"%(r['photos'][0]['original_size']['url']) return page
def reverse_geo(latlong): googleurl = "https://maps.googleapis.com/maps/api/geocode/json?latlng=%s,%s&key=%s" % ( latlong.split(",")[0], latlong.split(",")[1], 'AIzaSyBun2m9jaQTFGb0qtR7Shh7inqFhzKbLL4') request = urllib2.urlopen(googleurl) result = request.read() d = json.loads(result) rdic = d['results'][0] address = rdic['formatted_address'] address = urllib.quote_plus(address) return address
def get_remote(url, attempt=0): try: print('Attempt ' + str(attempt)) request = urllib.urlopen(url) response = request.read() return response except (urllib2.HTTPError, error): if error.code in (403, 404): if attempt < 5: return get_remote(url, attempt=attempt + 1) raise
def input_field_page(): # Please be responsible with my public key :) request = urllib.request.urlopen( 'https://api.nasa.gov/planetary/apod?api_key=E5cEaWdPE4Edf7N0luy673hxUFYvIJCAAPcGmPQN' ) data = json.loads(request.read()) videoUrl = data['url'] explanation = data['explanation'] return render_template('NASAPage.html', youTubeVideoSource=videoUrl, explanationText=explanation)
def input_field_page(): searchQuery = "Batman" pageNumber = 1 request = urllib.request.urlopen('http://www.omdbapi.com/?s=' + searchQuery + '&page=' + str(pageNumber) + '&apikey=42175782') data = json.loads(request.read()) # print(data['Search']) return render_template('OMDbAPI.html', query=searchQuery, pageNum=pageNumber, movies=data['Search'])
def t(tag="Narwhal"): url = "http://api.tumblr.com/v2/tagged?tag=%s&api_key=6qjbDDaQ4vUogvpFIZ2UoaHuo6ykn1vMpjRYOdYOPCQI6dBw4K" url = url % (tag) request = urllib2.urlopen(url) res_string = request.read() d = json.loads(res_string) page = "" for r in d['response']: if 'photos' in r.keys(): page = page + "<img height=200 src=y%s>" % ( r['photos'][0]['original_size']['url']) return page
def latlong(address): address = urllib2.quote(address) google_geocode_api_key = os.environ['google_geocode_api_key'] key = urllib2.quote(google_geocode_api_key) geocodeURL = "https://maps.googleapis.com/maps/api/geocode/json?address=%s&key=%s" % (address, key) request = urllib2.urlopen(geocodeURL) jsonResponse = json.loads(request.read()) data = jsonResponse[jsonResponse.keys()[1]] df = pd.DataFrame.from_dict(data) lat = df.geometry[0]['location']['lat'] lng = df.geometry[0]['location']['lng'] return lat, lng
def home(): url="http://api.openweathermap.org/data/2.5/weather?q=10000&appid=ecdb9f3fb43f5f8663867db2633c7638&units=imperial" request = urllib2.urlopen(url) result = request.read() r = json.loads(result) temp = r['main']['temp'] name = r['name'] #print r #print "__________________" #print result #print "-------------------" #return jsonify(r) return render_template("home.html", temp=temp, place=r['name'], maxTemp=r['main']['temp_max'], minTemp=r['main']['temp_min'])
def input_field_page(): dogPicURL = '' while (dogPicURL[-3:].lower() != 'png'): request = urllib.request.urlopen('https://random.dog/woof.json') data = json.loads(request.read()) dogPicURL = data["url"] request = urllib.request.urlopen('https://aws.random.cat/meow') data = json.loads(request.read()) catPicURL = data["file"] print("--------------------------") print(catPicURL) print("--------------------------") request = urllib.request.urlopen('https://catfact.ninja/facts') data = json.loads(request.read()) # print("--------------------------") # print(data["data"][0]["fact"]) # print("--------------------------") catFact = data["data"][0]["fact"] return render_template('API-template.html', dogPicURL = dogPicURL, catPicURL = catPicURL, catFact = catFact.lower()[0:-1])
def latlong(address): address = urllib2.quote(address) google_geocode_api_key = os.environ['google_geocode_api_key'] key = urllib2.quote(google_geocode_api_key) geocodeURL = "https://maps.googleapis.com/maps/api/geocode/json?address=%s&key=%s" % ( address, key) request = urllib2.urlopen(geocodeURL) jsonResponse = json.loads(request.read()) data = jsonResponse[jsonResponse.keys()[1]] df = pd.DataFrame.from_dict(data) lat = df.geometry[0]['location']['lat'] lng = df.geometry[0]['location']['lng'] return lat, lng
def getInfo(query): #currently not in used #unfixed #this will return a dict of 'loc = "Latitude: "+str(lat)+" Longitude: "+str(long), lat = stuff["lat"], lng = stuff["long"], add = stuff["add"]' request = urllib2.urlopen(query) result = request.read() result = json.loads(result) lat = result["results"][0]["geometry"]["location"]["lat"] lng = result["results"][0]["geometry"]["location"]["lng"] full_address = result["results"][0]["formatted_address"] dict = {} dict["lat"] = lat dict["long"] = lng dict["add"] = full_address return dict
def byPlaceID(ID): query = "https://maps.googleapis.com/maps/api/place/details/json?placeid="+ID+"&key=AIzaSyC1HeKfjwS4x0KYw_Wgl5-IxLBELfa4oO0" #https://developers.google.com/places/place-id request = urllib2.urlopen(query) result = request.read() result = json.loads(result) #print result full_address = result["result"]["formatted_address"] #dict = {} #dict["add"] = full_address return full_address
def byPlaceID(ID): query = "https://maps.googleapis.com/maps/api/place/details/json?placeid=" + ID + "&key=AIzaSyC1HeKfjwS4x0KYw_Wgl5-IxLBELfa4oO0" #https://developers.google.com/places/place-id request = urllib2.urlopen(query) result = request.read() result = json.loads(result) #print result full_address = result["result"]["formatted_address"] #dict = {} #dict["add"] = full_address return full_address
def callRestAPI(self, url_string): success = False try: request = urllib2.urlopen(self.arduino_url + "/" + url_string, timeout=5) response = request.read() print "~~~ArduinoManagement~~~ rest api " + url_string + " response: " + response success = True except OSError as e: print "~~~ArduinoManagement~~~: REST API failed: {}".format(str(e)) except Exception as e: print "~~~ArduinoManagement~~~: REST API failed: {}".format(str(e)) return success
def getData(place): country = 'uk' locationParameter = '' if isinstance(place, Boundaries): locationParameter = '&place_name=' + place.locationName elif isinstance(place, CircleArea): locationParameter = '¢re_point=' + place.center[0] + ',' + place.center[1] if place.radius > 0: locationParameter += ',' + place.radius + place.radiusFormat #elif isinstance(place, ) area, not admitted here url = "http://api.nestoria.co.uk/api?listing_type=buy&country=" + country + "&action=search_listings&encoding=json&pretty=1" + locationParameter request = urllib2.urlopen(url) return request.read()
def geocode(location_string, region): """ Löst eine Straßen- und optional PLZ-Angabe zu einer Geo-Postion auf. Beispiel: "Straßenname (12345)" """ if region != app.config['region_default']: location_string += ' ' + app.config['regions'][region]['name'] address = location_string.encode('utf-8') # Filter Postalcode in Brackets from Selection postalre = re.compile(r'(.+), ([0-9]{5}) (.+)') postal_matching = re.match(postalre, address) postal = None if postal_matching is not None: postal = postal_matching.group(2) url = 'http://open.mapquestapi.com/nominatim/v1/search.php' params = { 'format': 'json', # json 'q': address, 'addressdetails': 1, 'accept-language': 'de_DE', 'countrycodes': 'DE' } request = urllib2.urlopen(url + '?' + urllib.urlencode(params)) response = request.read() addresses = json.loads(response) addresses_out = [] for n in range(len(addresses)): for key in addresses[n].keys(): if key in ['address', 'boundingbox', 'lat', 'lon', 'osm_id']: continue del addresses[n][key] # skip if no road contained if 'road' not in addresses[n]['address']: continue # skip if not in correct county if 'county' not in addresses[n]['address']: continue # TODO: Filter for County #if addresses[n]['address']['county'] != app.config['GEOCODING_FILTER_COUNTY']: # continue if postal is not None: if 'postcode' in addresses[n]['address'] and addresses[n][ 'address']['postcode'] == postal: addresses_out.append(addresses[n]) else: addresses_out.append(addresses[n]) return addresses_out
def tag(tag="narwhal"): url="http://api.tumblr.com/v2/tagged?tag=%s&api_key=6qjbDDaQ4vUogvpFIZ2UoaHuo6ykn1vMpjRYOdYOPCQI6dBw4K" url = url%(tag) request = urllib2.urlopen(url) resultstring = request.read() result = json.loads(resultstring) s = "" for item in result['response']: print item try: s= s + "<img src=%s>"%(item['photos'][0]['original_size']['url']) print s except: pass return s
def tag(tag=""): url="http://api.tumblr.com/v2/tagged?tag=%s&api_key=aTQcvkZkpZbz7ILTsi8ekrUFE0maSPweft6mM1yyJhQBdnV5eb" url = url%(tag) request = urllib2.urlopen(url) resultstring = request.read() result = json.loads(resultstring) s = "" for item in result['response']: print item try: s= s + "<img src=%s>"%(item['photos'][0]['original_size']['url']) print s except: pass return s
def geo_loc(location): #finds the longitude and latitude of a given location parameter using Google's Geocode API #return format is a dictionary with longitude and latitude as keys loc = urllib.quote_plus(location) googleurl = "https://maps.googleapis.com/maps/api/geocode/json?address=%s&key=%s" % ( loc, "AIzaSyBun2m9jaQTFGb0qtR7Shh7inqFhzKbLL4") request = urllib2.urlopen(googleurl) results = request.read() gd = json.loads(results) #dictionary result_dic = gd['results'][ 0] #dictionary which is the first element in the results list geometry = result_dic['geometry'] #geometry is another dictionary loc = geometry['location'] #yet another dictionary retstr = str(loc["lat"]) + "," + str(loc["lng"]) return retstr
def nearHere(longi, lat): #note, some places WILL NOT WORK longi = str(longi) lat = str(lat) #query = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?address=%s&radius=500&types=food&name=cruise&key=%s" % (add, key) #query = "https://maps.googleapis.com/maps/api/place/radarsearch/json?location="+lat+","+longi+"&radius=5000&types=food|cafe&keyword=vegetarian&key=AIzaSyC1HeKfjwS4x0KYw_Wgl5-IxLBELfa4oO0" query = "https://maps.googleapis.com/maps/api/place/radarsearch/json?location="+lat+","+longi+"&radius=500&types=food|cafe&key=AIzaSyC1HeKfjwS4x0KYw_Wgl5-IxLBELfa4oO0" print query #print "ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ" #print print "Lat: "+str(lat) print "long: "+str(longi) #print "Reached here----------" request = urllib2.urlopen(query) result = request.read() result = json.loads(result) #print result dic={} if result["status"]!="OK": dic["ERROR"] = result["status"] return dic else: dic["ERROR"] = "NO" i = 0 l = [] while (i<5): #print jsonify(result) #return jsonify(result) try: placeID = result["results"][i]["place_id"] print placeID l.append(placeID) except: print "No more results" i= i+1 i = 0 while (i<5): try: dic[i] = byPlaceID(l[i]) except: print "No more results" #make this a dic instead #print l[i] i = i+1 #print result #print dic return dic
def nearHere(longi, lat): #note, some places WILL NOT WORK longi = str(longi) lat = str(lat) #query = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?address=%s&radius=500&types=food&name=cruise&key=%s" % (add, key) #query = "https://maps.googleapis.com/maps/api/place/radarsearch/json?location="+lat+","+longi+"&radius=5000&types=food|cafe&keyword=vegetarian&key=AIzaSyC1HeKfjwS4x0KYw_Wgl5-IxLBELfa4oO0" query = "https://maps.googleapis.com/maps/api/place/radarsearch/json?location=" + lat + "," + longi + "&radius=500&types=food|cafe&key=AIzaSyC1HeKfjwS4x0KYw_Wgl5-IxLBELfa4oO0" print query #print "ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ" #print print "Lat: " + str(lat) print "long: " + str(longi) #print "Reached here----------" request = urllib2.urlopen(query) result = request.read() result = json.loads(result) #print result dic = {} if result["status"] != "OK": dic["ERROR"] = result["status"] return dic else: dic["ERROR"] = "NO" i = 0 l = [] while (i < 5): #print jsonify(result) #return jsonify(result) try: placeID = result["results"][i]["place_id"] print placeID l.append(placeID) except: print "No more results" i = i + 1 i = 0 while (i < 5): try: dic[i] = byPlaceID(l[i]) except: print "No more results" #make this a dic instead #print l[i] i = i + 1 #print result #print dic return dic
def refresh_image(self): if self.last_refresh_attempt + self.refresh_interval > datetime.datetime.now( ): print "+++ImageUpdater+++: Skipping this update" # Return right away if we need to wait longer return self.last_refresh_attempt = datetime.datetime.now() attempt_num = 0 max_attempts = 3 success = False while attempt_num < max_attempts and success == False: attempt_num += 1 try: # Grab the latest frame from the camera print "+++ImageUpdater+++: Opening request" request = urllib2.urlopen(self.camera_server + "/photo.jpg", timeout=3) print "+++ImageUpdater+++: Reading request" data = request.read() print "+++ImageUpdater+++: Encoding request" encoded_str = base64.b64encode(data) print "+++ImageUpdater+++: Closing request" request.close() success = True except OSError as e: print "+++ImageUpdater+++: Image read attempt {} failed: ".format( attempt_num) + str(e) except Exception as e: print "+++ImageUpdater+++: Image read attempt {} failed: ".format( attempt_num) + str(e) if not success: print "+++ImageUpdater+++: Failed to read new image" else: try: # Upload the image to the cloud print "+++ImageUpdater+++: Uploading request" upload_result = upload("data:image/jpg;base64," + encoded_str) print "+++ImageUpdater+++: upload returned" if upload_result: # If the upload was successful, save the result in last_image_url self.last_image_url = upload_result['url'] self.last_update_time = datetime.datetime.now().strftime( '%H:%M:%S') except Exception as e: print "+++ImageUpdater+++: Failed to upload image to cloud: " + str( e) success = False return success
def geocode(location_string, region): """ Löst eine Straßen- und optional PLZ-Angabe zu einer Geo-Postion auf. Beispiel: "Straßenname (12345)" """ if region != app.config["region_default"]: location_string += " " + app.config["regions"][region]["name"] address = location_string.encode("utf-8") # Filter Postalcode in Brackets from Selection postalre = re.compile(r"(.+), ([0-9]{5}) (.+)") postal_matching = re.match(postalre, address) postal = None if postal_matching is not None: postal = postal_matching.group(2) url = "http://open.mapquestapi.com/nominatim/v1/search.php" params = { "format": "json", # json "q": address, "addressdetails": 1, "accept-language": "de_DE", "countrycodes": "DE", } request = urllib2.urlopen(url + "?" + urllib.urlencode(params)) response = request.read() addresses = json.loads(response) addresses_out = [] for n in range(len(addresses)): for key in addresses[n].keys(): if key in ["address", "boundingbox", "lat", "lon", "osm_id"]: continue del addresses[n][key] # skip if no road contained if "road" not in addresses[n]["address"]: continue # skip if not in correct county if "county" not in addresses[n]["address"]: continue # TODO: Filter for County # if addresses[n]['address']['county'] != app.config['GEOCODING_FILTER_COUNTY']: # continue if postal is not None: if "postcode" in addresses[n]["address"] and addresses[n]["address"]["postcode"] == postal: addresses_out.append(addresses[n]) else: addresses_out.append(addresses[n]) return addresses_out
def fetch_logs(link, time = False): logs = [] while link: q = Request(link, headers = {'Authorization': 'Token ' + AUTH_TOKEN}) request = urlopen(q) result = json.loads(request.read().decode()) logs.append(result['result']) link = result.get('next_link', '') articleIDs = [str(x['event']['article-id']) for log in logs for x in log] userIDs = [str(x['user-id'] or x['ip-address']) for log in logs for x in log] ratings = [VIEW_WEIGHT for log in logs for _ in range(len(log))] if time: timestamps = [(datetime.datetime.utcnow() - datetime.datetime.strptime(x['time-stamp'], '%Y-%m-%d %H:%M:%S')).days for log in logs for x in log] return articleIDs, userIDs, ratings, timestamps return articleIDs, userIDs, ratings