Beispiel #1
0
def results(request):
    # Need to find the null yelp result
    # Set variables when location is based on browser detection
    if request.POST.get('location-input') is None:
        latitude = request.POST.get('coords[latitude]')
        longitude = request.POST.get('coords[longitude]')
        reverse_geocode = requests.get("https://maps.googleapis.com/maps/api/geocode/json?latlng=%s,%s" %(str(latitude), str(longitude)))

        user_street_address = reverse_geocode.json()['results'][0]['formatted_address']
        yelp_result = (yelp.search('wifi', user_street_address)['businesses'])
        
    # Set variables when location is based on user input
    if request.POST.get('location-input') is not None:
        user_street_address = request.POST.get('location-input')
        yelp_result = (yelp.search('wifi', user_street_address)['businesses'])

    # Mark_safe used to prevent unicode and HTML conversion
    safe_result = mark_safe(json.dumps(yelp_result))
    if not yelp_result:
        return HttpResponse('Something went wrong when sending Yelp your address... Try again with a different address?')
    random_result = yelp_result[random.randrange(len(yelp_result))]
    template_data = {
        'name': random_result.get('name'),
        'yelp_results': safe_result,
        'user_address': user_street_address,
        'destination_address': random_result.get('location')['address'][0],
        'city': random_result.get('location')['city']
    }

    return render(request, 'wtfsiw/results.html', template_data)
def search():
    if request.method == "GET":
	return render_template("search.html")
    keyword = request.form['keyword']
    location = request.form['location']
    session["results"] =  yelp.search(keyword, location)
    return redirect("/results")
Beispiel #3
0
def results():
    username2="";
    results={};
    error="";
    term="";
    loc="";
    loggedin=False;
    if ('username' in session and session['username'] != None):
        username2 = session ['username']
        loggedin= True;
    if request.method=='POST':
        geo = 1 == len(request.form.getlist('geo'));
        term= request.form['term'];
        if(term==""):
            flash("Please enter a term.");
            return render_template("results.html",orderid = orderid, loggedin=loggedin,username2=username2,results=results);
        if(geo):
            lat = request.form["lat"];
            lon = request.form["lon"];
            results=yelp.searchbound(term,float(lat),float(lon));
        else:
            loc = request.form["loc"];
            if(loc==""):
                flash("Please enter a location or check automatic");
                return render_template("results.html",orderid = orderid, loggedin=loggedin,username2=username2,results=results);
            results = yelp.search(term,loc);
    if(results==None):
        flash("No results came up");
    return render_template("results.html", orderid=orderid, loggedin=loggedin,username2=username2,results=results);
Beispiel #4
0
def approve(chillid):
    whats = database.get_invite_food_preferences(chillid)
    invitePref = database.get_invite_preferences(chillid)
    wheres = invitePref['location']
    for x in range(0, len(wheres)):
        if not wheres[x][-7:].isdigit():
            wheres[x] = geo_loc(wheres[x])
    peoplelist = database.get_invitees(chillid)
    people = []
    for person in peoplelist:
        people.append(database.get_user_name(person))
    restaurant_list = yelp.search(whats, wheres)
    datelist = invitePref['date']
    timelist = invitePref['time']
    needsapproval = [
        database.get_invite_title(chillid), people, restaurant_list, datelist,
        timelist
    ]
    if request.method == 'GET':
        return render_template('approve.html',
                               needsapproval=needsapproval,
                               numtimes=len(needsapproval[3]))
    else:
        rest = request.form['restRadios']
        time = request.form['timeRadios']
        restaurantname = needsapproval[2][int(rest[-1:])]['name']
        restaurantaddress = needsapproval[2][int(rest[-1:])]['address'][0]
        finaldate = needsapproval[3][int(time[-1:])]
        finaltime = needsapproval[4][int(time[-1:])]
        database.set_final_plan(chillid, restaurantaddress, finaltime,
                                finaldate)
        return redirect(url_for('index'))
Beispiel #5
0
def search():
  check_for_logged_in()
  if request.method == "POST":
    location = request.form['location']
    results = yelp.search("barber shop", location)
    return render_template('maps.html', results=json.dumps(results, ensure_ascii=False), location=location)
  url_for('static', filename="css/bootstrap.css")
#this should render the search page.
  return render_template('search.html', user=user, sign_in_url=sign_in_url, sign_out_url=sign_out_url)
def yelpPost():
    sw_latitude = request.form.get('sw_latitude', type=float)
    sw_longitude = request.form.get('sw_longitude', type=float)
    ne_latitude = request.form.get('ne_latitude', type=float)
    ne_longitude = request.form.get('ne_longitude', type=float)

    if sw_latitude is not None and sw_longitude is not None and ne_latitude is not None and ne_longitude is not None:
        return json.dumps(
            yelp.search(sw_latitude, sw_longitude, ne_latitude, ne_longitude))

    return "{error:'Invalid input'}"
Beispiel #7
0
def businesses(tag='None'):
    if request.method == 'GET':
        if tag=='None':
            return redirect('/search_businesses')
        queries = tag.split('&')
        qDict = {}
        for q in queries:
            a = q.split('=')
            if len(a) == 2:
                qDict[a[0]] = a[1]
        results = yelp.search(qDict['keyword'], qDict['limit'], qDict['sort']) #a dict
        return render_template('businesses.html', results=results, keyword=qDict['keyword'])
    else:
        button = request.form['button']
        if button == 'Search':
            return redirect('/search/'+request.form['query'])
Beispiel #8
0
def yelp_biz_search():
    # GET /yelp/v3businesses/search?term=food&location=08618&limit=10 HTTP/1.1
    # authorization: Bearer JX_3SDC9tLlj4OtGqs3jewsPWF0xV4nfrqIDdgAjKp3uLeZxDK9CZpU4K-zR9RYEgwCv8on63odsSRaobgNvO0eVdVJWCZ4IYuiCepWVFdM8m80NEtDG0KADtrGAWHYx
    # Cookie: rg_cookie_session_id=229187570
    bearer = request.headers['Authorization']
    bearer = bearer.replace('Bearer ', '')
    #pprint.pprint(request.headers)
    #EnvironHeaders([('Host', 'h4ck3rm1k3zone1.ddns.net:25000'), ('Connection', 'keep-alive'), ('Cookie', 'rg_cookie_session_id=229187570'), ('Pragma', 'no-cache'),
    #('Authorization', 'Bearer JX_3SDC9tLlj4OtGqs3jewsPWF0xV4nfrqIDdgAjKp3uLeZxDK9CZpU4K-zR9RYEgwCv8on63odsSRaobgNvO0eVdVJWCZ4IYuiCepWVFdM8m80NEtDG0KADtrGAWHYx'), ('Content-Type', ''), ('Accept', '*/*'), ('Content-Length', ''), ('User-Agent', 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.75 Safari/537.36'), ('Accept-Language', 'en-US,en;q=0.8'), ('Accept-Encoding', 'gzip, deflate, sdch'), ('Cache-Control', 'no-cache'), ('Referer', 'http://h4ck3rm1k3zone1.ddns.net:25000/yelp/')])

    #bearer_token
    term = request.args['term']
    location = request.args['location']
    res = yelp.search(bearer, term, location)
    #pprint.pprint(res)
    #return pprint.pformat(res)
    return flask.jsonify(**res)
Beispiel #9
0
def businesses(tag='None'):
    if request.method == 'GET':
        if tag == 'None':
            return redirect('/search_businesses')
        queries = tag.split('&')
        qDict = {}
        for q in queries:
            a = q.split('=')
            if len(a) == 2:
                qDict[a[0]] = a[1]
        results = yelp.search(qDict['keyword'], qDict['limit'],
                              qDict['sort'])  #a dict
        return render_template('businesses.html',
                               results=results,
                               keyword=qDict['keyword'])
    else:
        button = request.form['button']
        if button == 'Search':
            return redirect('/search/' + request.form['query'])
Beispiel #10
0
def results():
    username2 = ""
    results = {}
    error = ""
    term = ""
    loc = ""
    loggedin = False
    if ('username' in session and session['username'] != None):
        username2 = session['username']
        loggedin = True
    if request.method == 'POST':
        geo = 1 == len(request.form.getlist('geo'))
        term = request.form['term']
        if (term == ""):
            flash("Please enter a term.")
            return render_template("results.html",
                                   orderid=orderid,
                                   loggedin=loggedin,
                                   username2=username2,
                                   results=results)
        if (geo):
            lat = request.form["lat"]
            lon = request.form["lon"]
            results = yelp.searchbound(term, float(lat), float(lon))
        else:
            loc = request.form["loc"]
            if (loc == ""):
                flash("Please enter a location or check automatic")
                return render_template("results.html",
                                       orderid=orderid,
                                       loggedin=loggedin,
                                       username2=username2,
                                       results=results)
            results = yelp.search(term, loc)
    if (results == None):
        flash("No results came up")
    return render_template("results.html",
                           orderid=orderid,
                           loggedin=loggedin,
                           username2=username2,
                           results=results)
Beispiel #11
0
    def get(self):
        currentUser = None
        user = users.get_current_user()
        profileInfo = True
        if user:
            logout_url = users.create_logout_url('/')
            login_url = None
            username = user.email()
        else:  # user is not logged in
            login_url = None
            logout_url = None
            username = None
        location = self.request.get('location')
        gmaps_address = location.replace(' ', '+')
        geocode = 'https://maps.googleapis.com/maps/api/geocode/json?address=' + str(gmaps_address) + '&key=AIzaSyDIH9iVlHtpMY0BsBd3F3sn43Bmf4YV4mI'
        json_content = urlfetch.fetch(geocode).content
        results = json.loads(json_content)['results']
        # Logic/process info - do a search with Yelp API
        miles = ''
        result = yelp.search('restaurants', location, 0)
        numResults = self.request.get('number')
        r = random.randint(0, len(result["businesses"]) - 1)
        if 'distance' not in result["businesses"][0]:
            self.redirect('/?error=true')
        else:
            distance = int((result["businesses"][r]["distance"] * (.000621371192)) * 100)
            miles = (1.0 *distance)/100

        alert = result["businesses"][r]['image_url']
        name = result["businesses"][r]["name"]
        address= result["businesses"][r]["location"]["display_address"]
        typeRest =result["businesses"][r]["categories"][0][0]
        lat =results[0]['geometry']['location']['lat']
        lng= results[0]['geometry']['location']['lng']
        restImages =result["businesses"][r]['image_url']
        yelp_url = result['businesses'][r]['url']
        rest_lat = result['businesses'][r]['location']['coordinate']['latitude']
        rest_lng =  result['businesses'][r]['location']['coordinate']['longitude']
        food_preference =[]
        if user:
            if profileInfo == True:
                currentUser = User.query(User.userEmail == user.email()).get()
                # foodTypePreference1 = self.request.get('')
                # foodTypePreference2 = self.request.get('foodTypePreference2')
                # foodTypePreference3 = self.request.get('foodTypePreference3')
                # foodTypePreference4 = self.request.get('foodTypePreference4')
                # foodTypePreference5 = self.request.get('foodTypePreference5')
                # food_preference = [foodTypePreference1, foodTypePreference2, foodTypePreference3, foodTypePreference4, foodTypePreference5]
                food_preference = currentUser.food_preference
                for foodType in food_preference:
                    for i in range(0, len(result["businesses"])-1):
                        if result["businesses"][i]["categories"][0][0] == foodType:
                            name = result["businesses"][i]["name"]
                            address= result["businesses"][i]["location"]["display_address"]
                            typeRest =result["businesses"][i]["categories"][0][0]
                            restImages =result["businesses"][i]['image_url']
                            yelp_url = result['businesses'][i]['url']
                            rest_lat = result['businesses'][i]['location']['coordinate']['latitude']
                            rest_lng= result['businesses'][i]['location']['coordinate']['longitude']

        # First random restaurant shown in second screen
        variables = {
        'login_url': login_url,
        'logout_url': logout_url,
        'username': username,
        'location': location,
        'distance': miles,
        'name': name,
        'address': address,
        'type': typeRest,
        'lat': lat,
        'lng': lng,
        'restImages': restImages,
        'yelp_url': yelp_url,
        'rest_lat': rest_lat,
        'rest_lng': rest_lng,
        'alert': alert,
        'food_preference': food_preference
        }
        template = env.get_template('results.html')
        # Print result in proper JSON - debugging purposes
        # self.response.headers['Content-Type'] = 'application/json'
        # obj = {'result': result}
        # self.response.out.write(json.dumps(result))
        # Send a response.
        self.response.write(template.render(variables))
Beispiel #12
0
def yelp_search(searchQuery, searchCount,location, locationCoord):
    return search(searchQuery,searchCount, location, locationCoord)
Beispiel #13
0
def home():
    message = random.choice(messages)
    searches = yelp.search('lunch', os.environ['HOME_ADDRESS'])
    biz = 'Try %s' % random.choice(searches)
    out = message % biz
    text.me(out)
Beispiel #14
0
def bub():
    message = random.choice(messages)
    searches = yelp.search('lunch', os.environ['BUB_WORK_ADDRESS'])
    biz = 'Try %s' % random.choice(searches)
    out = message % biz
    text.bub(out)
Beispiel #15
0
    print("1")
    start = request.form.get("1","")
    end = request.form.get("2","")
    print(start)
    print(end)
    #fields were left blank
    if start == None or end == None:
        return render_template("route.html")
    stationList = mta.getStopLocations(start, end)
    results = []
    stations= []
    for station in stationList:
        print station
        try: 
            yelplist = yelp.search("food",station)
            results.append(yelplist)
            stations.append(station)
        except KeyError:
            return render_template("route.html")

    print results
    session["stations"]= stations
    session["results"] = results
    return redirect("results")


=======
    if request.method=="POST":
        print("1")
        print request.form.get("pref","")
Beispiel #16
0
def yelp_search(searchQuery, searchCount, location, locationCoord):
    return search(searchQuery, searchCount, location, locationCoord)
Beispiel #17
0
#         user_location = user_location,
#         user_preferences = user_preferences,
#
#         date = datetime.utcnow()
#     ))

@app.route('/')
def hello_world():
    jenn = 'vegetarian'
    user_location = 'San Diego, CA'
    query = yelp.search(jenn, user_location)
    return str(query)
    # return 'Hello World!'
    # dict = {value: key for key, value in query.items()}
    # return dict
    # return jsonify(query)


jenn = 'vegetarian'
user_location = 'San Diego, CA'
query = yelp.search(jenn, user_location)

print query['businesses']

# for key in query.keys():
#     print (key)

if __name__ == '__main__':
    app.debug = True
    app.run(host='0.0.0.0', port=8080)
Beispiel #18
0
    def post(self):
        letter = ['A','B','C','D','E','F','G','H','I','J']
        location = self.request.get('location')
        gmaps_address = location.replace(' ', '+')
        geocode = 'https://maps.googleapis.com/maps/api/geocode/json?address=' + str(gmaps_address) + '&key=AIzaSyDIH9iVlHtpMY0BsBd3F3sn43Bmf4YV4mI'
        json_content = urlfetch.fetch(geocode).content
        results = json.loads(json_content)['results']
        result = yelp.search('restaurants', location, 0)
        distanceRest = []
        nameRest =[]
        addressRest = []
        typeRest =[]
        latRest = []
        lngRest = []
        urlRest = []
        businIndex = []
        numResults = int(self.request.get('number'))
        disResults = int(self.request.get('distance'))
        typeResults = self.request.get('restaurantType')
        i = 0
        j = 0
        resFound = ""
        if typeResults == "No Preference":
            while i != numResults:
                distance = int((result["businesses"][j]["distance"] * (.000621371192))*100)
                miles= (1.0 *distance)/100
                name = result["businesses"][j]["name"]
                address = result["businesses"][j]["location"]["display_address"]
                typeR = result["businesses"][j]["categories"][0][0]
                rest_lat = result['businesses'][j]['location']['coordinate']['latitude']
                rest_lng = result['businesses'][j]['location']['coordinate']['longitude']
                rest_yelp_url = result['businesses'][j]['url']
                if miles <= disResults:
                    distanceRest.append(miles)
                    nameRest.append(name)
                    addressRest.append(address)
                    typeRest.append(typeR)
                    latRest.append(rest_lat)
                    lngRest.append(rest_lng)
                    urlRest.append(rest_yelp_url)
                    businIndex.append(j)
                    i = i + 1
                j = j + 1
                if j >= (len(result["businesses"])-1):
                    break;
        else:
            # alert = "Hi"
            typeResults = typeResults
            while i != numResults:
                distance = int((result["businesses"][j]["distance"] * (.000621371192))*100)
                miles= (1.0 *distance)/100
                name = result["businesses"][j]["name"]
                address = result["businesses"][j]["location"]["display_address"]
                typeR = result["businesses"][j]["categories"][0][0]
                rest_lat = result['businesses'][j]['location']['coordinate']['latitude']
                rest_lng = result['businesses'][j]['location']['coordinate']['longitude']
                rest_yelp_url = result['businesses'][j]['url']
                if miles <= disResults:
                    if typeResults == result["businesses"][j]["categories"][0][0]:
                        distanceRest.append(miles)
                        nameRest.append(name)
                        addressRest.append(address)
                        typeRest.append(typeR)
                        latRest.append(rest_lat)
                        lngRest.append(rest_lng)
                        urlRest.append(rest_yelp_url)
                        businIndex.append(j)
                        i = i + 1
                j = j + 1
                if j >= (len(result["businesses"])-1):
                    break;
            j = 0
            resFound = str(i) + " results found for " + typeResults + " food"
            if i == 1:
                resFound = str(i) + " result found for " + typeResults + " food"
            while i != numResults:
                distance = int((result["businesses"][j]["distance"] * (.000621371192))*100)
                miles= (1.0 *distance)/100
                if miles <= disResults:
                    for check in businIndex:
                        alert = "uphomes"
                        if check == j:
                            j = j + 1
                    name = result["businesses"][j]["name"]
                    address = result["businesses"][j]["location"]["display_address"]
                    typeR = result["businesses"][j]["categories"][0][0]
                    rest_lat = result['businesses'][j]['location']['coordinate']['latitude']
                    rest_lng = result['businesses'][j]['location']['coordinate']['longitude']
                    rest_yelp_url = result['businesses'][j]['url']
                    distanceRest.append(miles)
                    nameRest.append(name)
                    addressRest.append(address)
                    typeRest.append(typeR)
                    latRest.append(rest_lat)
                    lngRest.append(rest_lng)
                    urlRest.append(rest_yelp_url)
                    i = i + 1
                j = j + 1

                #Change Background according to type of food
        backgroundImg = ""
        backImg ={
            'American':"carls-jr-most-american-burger.jpg",
            'Arabian':"grilled-kangaroo.jpg",
            'Australian':"grilled-kangaroo.jpg",
            'Brazilian':"Traditional-Brazilian-Food.jpg",
            'Caribbean':"ropa-vieja.jpg",
            'Chinese':"295198-chinese-food.jpg",
            'Filipino':"photo-4.jpg",
            'French': "4e7fe1ec14f092326f000153-1317003759.jpeg",
            'German': "pastacabbage-germanfood-germanrecipes.jpg",
            'Greek':"Greek-Lentil-Salad-recipe-with-Feta-cheese-.jpg",
            'Indian':"ethnic.jpg",
            'Indonesian':"indo-salad.jpg",
            'Japanese':"5.jpg",
            'Latin American':"Paella.jpg",
            'Malaysian':"img_2800.jpg",
            'Mexican': "dsc_0491.jpg",
            'Middle Eastern':"sahara_falafel_plate.jpg",
            'Portuguese':"octopus.jpeg",
            'Thai':"Thai-food1.jpg",
            'Turkish':"photo-9.jpg",
            'Vegan': "vegan-dietyou.jpg",
            'Vegetarian':"muscle-building-food1.jpg",
            'Vietnamese': "img_5935.jpg"
        }
        backgroundImg = "../static/"+ backImg[typeResults]
        variables = {
            'lat': results[0]['geometry']['location']['lat'],
            'lng': results[0]['geometry']['location']['lng'],
            'latRest': latRest,
            'lngRest': lngRest,
            'distanceRest': distanceRest,
            'nameRest': nameRest,
            'addressRest': addressRest,
            'typeRest': typeRest,
            'latRest': latRest,
            'lngRest': lngRest,
            'urlRest': urlRest,
            'location': location,
            'letter': letter,
            'resFound': resFound,
            'backgroundImg': backgroundImg
            # 'backgroundImg': backgroundImg
            }
        template = env.get_template('resultsfilter.html')
        self.response.write(template.render(variables))
Beispiel #19
0
def hello_world():
    jenn = 'vegetarian'
    user_location = 'San Diego, CA'
    query = yelp.search(jenn, user_location)
    return str(query)
Beispiel #20
0
def search():
    term = request.args.get("term", "", type=str)
    location = request.args.get("location", "", type=str)

    return jsonify(**yelp.search(term, location))