Example #1
0
def nearby(tid):
    """Nearby uses flask_wtform and wikipedia apis.

    Get the address, query for places around it
    (currently wikipedia, may become locations of tickets),
    return results.
    """
    tid = tid
    ticket = Ticket.query.get(tid)
    pickup_address = ticket.pickup_address
    pickup_ll = geocoder.google(pickup_address)
    p_lat, p_lng = pickup_ll.lat, pickup_ll.lng
    form = AddressForm()
    places = []
    my_coordinates = (p_lat, p_lng)
    lat_lng = (p_lat, p_lng)

    if request.method == 'POST':
        if form.validate() is False:
            return render_template('nearby.html', form=form, tid=tid,
                                   ticket=ticket)
        else:
            address = form.address.data
            p = Place()
            my_coordinates = p.address_to_latlng(address)
            places = p.main(address)

            return render_template('nearby.html', form=form, places=places,
                                   my_coordinates=my_coordinates, tid=tid,
                                   lat_lng=lat_lng, ticket=ticket)

    elif request.method == 'GET':
        return render_template("nearby.html", form=form, places=places,
                               my_coordinates=my_coordinates, tid=tid,
                               lat_lng=lat_lng, ticket=ticket)
Example #2
0
def home():
    if 'email' not in session:
        return redirect(url_for('login'))

    form = AddressForm()
    places = []
    my_coordinates = (37.4221, -122.0844)

    if request.method == 'POST':
        if form.validate() == False:
            return render_template('home.html', form=form)
        else:
            # get the address
            address = form.address.data
            #address = add

            # query for places around it
            p = Place()
            my_coordinates = p.address_to_latlng(address)
            places = p.query(address)

            # return those results
            return render_template('home.html',
                                   form=form,
                                   my_coordinates=my_coordinates,
                                   places=places)

    elif request.method == 'GET':
        return render_template("home.html",
                               form=form,
                               my_coordinates=my_coordinates,
                               places=places)
Example #3
0
def home():
	if 'email' not in session:
		return redirect(url_for('login'))
	
	form = AddressForm()
	places = []
	my_coordinates = (37.4221, -122.0844)
	
	if request.method == "POST":
		if form.validate() == False:
			return render_template("home.html", form=form)
		else:
			# get the address
			address = form.address.data

			# query for addresses nearby
			p = Place()

			my_coordinates = p.address_to_latlng(address)
			places = p.query(address)


			# return those results
			return render_template('home.html', form=form, my_coordinates=my_coordinates, places=places)
			

	elif request.method == "GET":
		return render_template("home.html", form=form, my_coordinates=my_coordinates, places=places)
Example #4
0
def home():
	if 'email' not in session:
		return redirect(url_for('login'))

	form = AddressForm()

	places = []
	my_coordinates = (50.45146, 30.52187) #37.4221     -122.0844

	if request.method == 'POST':
		if form.validate() == False:
			return render_template("home.html", form=form)
		else:
			address = form.address.data

			p = Place()
			my_coordinates =p.address_to_latlng(address)
			places = p.query(address)

			return render_template("home.html", 
									form=form,
									my_coordinates=my_coordinates,
									places=places)

	elif request.method == 'GET':
		return render_template("home.html", 
								form=form,
								my_coordinates=my_coordinates,
								places=places)

	return render_template("home.html")
Example #5
0
def home():
    if 'email' not in session:
        return redirect(url_for('login'))
    form = AddressForm()

    places = []
    my_coordinates = (37.4221, -122.0844)  #just dflts, mean nothing
    if request.method == "POST":
        if form.validate == False:
            return render_template('home.html', form=form)
        else:
            # get the addy
            address = form.address.data
            # make a model to wrap or consume the wiki api then query it at https://www.mediawiki.org/wiki/Extension:GeoData#Api
            p = Place()
            my_coordinates = p.address_to_latlng(address)
            places = p.query(address)
            # return results
            return render_template('home.html',
                                   form=form,
                                   my_coordinates=my_coordinates,
                                   places=places)
    elif request.method == "GET":
        return render_template('home.html',
                               form=form,
                               my_coordinates=my_coordinates,
                               places=places)
Example #6
0
def add_place():
    city = request.form.get('add_city')
    district = request.form.get('add_district')
    places = Place(city, district).get_objects()
    if len(places) == 0:
        Place(city, district).save()
    return redirect(url_for(views.admin_places_page.__name__))
Example #7
0
File: views.py Project: TandZ/Crowd
def createentrycontinue(request):
	title = request.POST['title'].replace(" ", "_")
	location = request.POST['location']
	comments = request.POST['details']
	p = Place(name = title, location=location, details=comments)
	p.save()
	return render_to_response('places/createpagecontinue.html', {"placename": p.name}, context_instance=RequestContext(request))
Example #8
0
def home():
    if 'email' not in session:
        return redirect(url_for('login'))

    form = AddressForm()

    places = []
    my_coordinates = (42.650435, -73.758516)

    if request.method == 'POST' and form.validate():
        # get the address
        address = form.address.data

        # query for places around it
        p = Place()
        my_coordinates = p.address_to_latlng(address)
        places = p.query(address)

        # return the results
        return render_template('home.html', form=form,
                                            my_coordinates=my_coordinates,
                                            places=places)
    return render_template('home.html', form=form,
                                        my_coordinates=my_coordinates,
                                        places=places)
Example #9
0
def home():
	if 'email' not in session:
		return redirect(url_for('login'))

	form = AddressForm()

	places = []
	my_coordinates = (37.4221, -122.0844)

	if request.method == 'POST':
		if not form.validate():
			return render_template('home.html', form=form)

		# Handle the Form here.
		# Get the adress.
		address = form.address.data

		# Query for places around it.
		p = Place()
		my_coordinates = p.address_to_latlng(address)
		places = p.query(address)

		# Return those results.
		return render_template('home.html', form=form, my_coordinates=my_coordinates, places=places)
	elif request.method == 'GET':
		return render_template('home.html', form=form, my_coordinates=my_coordinates, places=places)
Example #10
0
def home():
    if 'email' not in session:
        return redirect(url_for('login'))

    form = AddressForm()
    my_coordinates = (18.5745, 73.6847)
    places = []

    if request.method == 'GET':
        return render_template("home.html",
                               form=form,
                               my_coordinates=my_coordinates,
                               places=places)

    elif request.method == 'POST':
        if not form.validate:
            return render_template('home.html',
                                   form=form,
                                   my_coordinates=my_coordinates,
                                   places=places)
        else:
            location = form.address.data

            p = Place()
            my_coordinates = p.address_to_latlng(location)
            places = p.query(location)

            return render_template("home.html",
                                   form=form,
                                   my_coordinates=my_coordinates,
                                   places=places)
Example #11
0
def home():
    if 'email' not in session:
        return redirect(url_for("login"))

    form = AddressForm()
    places = []
    my_coordinates = (17.4435, 78.3772)

    if request.method == 'POST':
        if form.validate() == False:
            return render_template('home.html', form=form)
        else:
            address = form.address.data

            p = Place()
            places = p.query(address)

            return render_template('home.html',
                                   form=form,
                                   my_coordinates=my_coordinates,
                                   places=places)

    elif request.method == 'GET':
        return render_template("home.html",
                               form=form,
                               my_coordinates=my_coordinates,
                               places=places)
Example #12
0
def home():
    if "email" not in session:
        return redirect(url_for("login"))

    form = AddressForm()
    places = []
    my_coordinates = [37.4221, -122.0844]

    if request.method == "POST":
        if not form.validate():
            return render_template("home.html", form=form)
        else:
            # get address
            address = form.address.data
            # query for places
            p = Place()
            my_coordinates = p.address_to_latlng(address)
            places = p.query(address)
            # return results
            return render_template("home.html",
                                   form=form,
                                   my_coordinates=my_coordinates,
                                   places=places)
    elif request.method == "GET":
        return render_template("home.html",
                               form=form,
                               my_coordinates=my_coordinates,
                               places=places)
Example #13
0
def home():
	if 'email' not in session:
		return redirect(url_for("login"))

	form=AddressForm()

	places = []
	my_coordinates = (30.620949, -96.350764)

	if request.method=="POST":
		if form.validate() == False:
			return render_template("home.html", form=form)
		else:
			# get the address
			address=form.address.data
			print("Hello")

			# query for places around it
			p=Place()
			my_coordinates = p.address_to_latlng(address)
			print(my_coordinates)
			places=p.query(address)

			# return those results
			return render_template("home.html", form=form, my_coordinates=my_coordinates, places=places)

	elif request.method=="GET":
		return render_template("home.html", form=form, my_coordinates=my_coordinates, places=places)
Example #14
0
def create_place(city_id):
    """
    Creates new place. If request body not valid JSON, raises 400
    If dict does not contain 'name' key, raise 400
    Returns place object with status 201
    """
    if not request.get_json():
        abort(400, "Not a JSON")

    kwargs = request.get_json()

    a = storage.get("City", city_id)
    if a is None:
        abort(404)

    if not kwargs.get('user_id'):
        abort(400, "Missing user_id")
    if not kwargs.get('name'):
        abort(400, 'Missing name')

    a = storage.get("User", kwargs['user_id'])
    if a is None:
        abort(404)

    my_place = Place(city_id=city_id, **kwargs)

    storage.new(my_place)
    storage.save()

    return jsonify(my_place.to_dict()), 201
Example #15
0
def home():
    if 'email' not in session:
        return redirect(url_for('login'))

    form = AddressForm()

    places = []
    my_coordinates = (40.7127750, -74.0059730)

    if request.method == 'POST':
        if form.validate() == False:
            return render_template('home.html', form=form)
        else:
            #get address
            address = form.address.data

            #search places around it
            p = Place()
            my_coordinates = p.address_to_latlng(address)
            places = p.query(address)

            #return results

            return render_template('home.html',
                                   form=form,
                                   my_coordinates=my_coordinates,
                                   places=places)

    elif request.method == 'GET':
        return render_template('home.html',
                               form=form,
                               my_coordinates=my_coordinates,
                               places=places)
Example #16
0
def home():
    if 'email' not in session:
        return redirect(url_for('login'))

    form = AddressForm()
    places = []
    my_coordinates = (37.4221, -122.0844)

    if request.method == "POST":
        if form.validate() == False:
            return render_template("home.html", form=form)
        else:
            #handle good case
            # Get the address
            address = form.address.data

            # Search for places around it
            p = Place()
            my_coordinates = p.address_to_latlng(address)
            places = p.query(address)

            # Return the results
            return render_template("home.html",
                                   form=form,
                                   my_coordinates=my_coordinates,
                                   places=places)

    elif request.method == "GET":
        return render_template("home.html",
                               form=form,
                               my_coordinates=my_coordinates,
                               places=places)
Example #17
0
    def test_issue_7276(self):
        # Regression test for #7276: calling delete() on a model with
        # multi-table inheritance should delete the associated rows from any
        # ancestor tables, as well as any descendent objects.
        place1 = Place(name="Guido's House of Pasta",
                       address='944 W. Fullerton')
        place1.save_base(raw=True)
        restaurant = Restaurant(place_ptr=place1,
                                serves_hot_dogs=True,
                                serves_pizza=False)
        restaurant.save_base(raw=True)
        italian_restaurant = ItalianRestaurant(restaurant_ptr=restaurant,
                                               serves_gnocchi=True)
        italian_restaurant.save_base(raw=True)

        ident = ItalianRestaurant.objects.all()[0].id
        self.assertEqual(Place.objects.get(pk=ident), place1)
        xx = Restaurant.objects.create(name='a',
                                       address='xx',
                                       serves_hot_dogs=True,
                                       serves_pizza=False)

        # This should delete both Restuarants, plus the related places, plus
        # the ItalianRestaurant.
        Restaurant.objects.all().delete()

        self.assertRaises(Place.DoesNotExist, Place.objects.get, pk=ident)
        self.assertRaises(ItalianRestaurant.DoesNotExist,
                          ItalianRestaurant.objects.get,
                          pk=ident)
Example #18
0
 def test_good_google_location_and_yelp(self):
   place = Place()
   place.name = "Whole Foods"
   place.location = '1240 Yale St, Santa Monica, CA 90404'
   place.save()
   self.assertEqual(place.yelp_id, 'hdQJrF3Fw_KrEaDywC3tyg')
   self.assertEqual(len(Place.objects.all()), 1)
Example #19
0
    def POST(self, place):
        data = json.loads(web.data())['data']

        for row in data:
            code = place.key + "/" + row['code']
            pb = Place.find(code)

            if row['ward'] and row['ward'].strip():
                # Extract te group code from its name
                key = place.key + "/" + row['ward'].split("-")[0].strip()
                ward = Place.find(key)
                if pb.ward_id != ward.id:
                    pb.set_ward(ward)
            else:
                pb.set_ward(None)

            if row['px'] and row['px'].strip():
                # Extract te group code from its name
                key = place.key + "/" + row['px'].split("-")[0].strip()
                px = Place.find(key)
                if pb.px_id != px.id:
                    pb.set_px(px)
            else:
                pb.set_px(None)

        web.header("content-type", "application/json")
        return '{"result": "ok"}'
Example #20
0
 def setUp(self):
     self.p1 = Place(name='Demon Dogs', address='944 W. Fullerton')
     self.p1.save()
     self.p2 = Place(name='Ace Hardware', address='1013 N. Ashland')
     self.p2.save()
     self.r = Restaurant(place=self.p1, serves_hot_dogs=True, serves_pizza=False)
     self.r.save()
Example #21
0
def home(id=None):
    if 'email' not in session:  # used to avoid login page if user already login
        return redirect(url_for('login'))
    # q = User.query.get(id)
    user = User.query.filter_by(email=session['email']).first()
    form = AddressForm()
    places = []
    my_coord = (37.4332, -122.0844)
    if request.method == 'POST':
        if form.validate() == False:
            return render_template("home.html", **dict(user=user, form=form))
        else:
            #get the add
            address = form.address.data
            #query for add
            p = Place()
            my_coord = p.address_to_latlang(address)
            places = p.query(address)

            # return those results
            return render_template(
                'home.html',
                **dict(user=user, form=form, my_coord=my_coord, places=places))
    elif request.method == 'GET':
        return render_template(
            "home.html",
            **dict(user=user, form=form, my_coord=my_coord, places=places))
    else:
        return "else"
Example #22
0
def home():
    if 'email' not in session:
        return redirect(url_for('login'))

    form = AddressForm()

    places = []
    my_coordinates = (33.7489, -84.3789)  # Based on the city of Atlanta

    if request.method == 'POST':
        if form.validate() == False:
            return render_template('home.html', form=form)
        else:
            # get the address
            address = form.address.data

            # query for places around it
            p = Place()
            my_coordinates = p.address_to_latlng(address)
            places = p.query(address)

            # return those results
            return render_template('home.html',
                                   form=form,
                                   my_coordinates=my_coordinates,
                                   places=places)

    elif request.method == 'GET':
        return render_template('home.html',
                               form=form,
                               my_coordinates=my_coordinates,
                               places=places)
Example #23
0
 def get(self):
     place = Place(
         name='Google',
         location=ndb.GeoPt(lat=1.279,lon=103.85)
     )
     place.put()
     self.redirect('/')
Example #24
0
def create_place(city_id):
    '''
       Creates a new Place object and saves it to storage
    '''
    city = storage.get("City", city_id)
    if not city:
        abort(404)

    if not request.json:
        abort(400)
        return jsonify({"error": "Not a JSON"})

    place_dict = request.get_json()
    if "user_id" not in place_dict:
        abort(400)
        return jsonify({"error": "Missing user_id"})
    elif "name" not in place_dict:
        abort(400)
        return jsonify({"error": "Missing name"})

    # Check that user_id is linked to actual User object
    user_check = storage.get("User", place_dict["user_id"])
    if not user_check:
        abort(404)

    place_name = place_dict["name"]
    user_id = place_dict["user_id"]
    place = Place(name=place_name, user_id=user_id, city_id=city_id)
    for k, v in place_dict.items():
        setattr(place, k, v)
    place.save()
    return jsonify(place.to_dict()), 201
def home():
    #protects the home page, turn off to turn on home
    if 'email' not in session:
        return redirect(url_for('login'))
    
    form = AddressForm()
    
    places = []
    my_coordinates = (0.0000,0.0000) #null island
    
    if request.method =="POST":
        if form.validate == False:
            return render_template("home.html", form = form)
        else:
            #handle form submission
            #pass
            address = form.address.data
            p = Place()
            my_coordinates = p.address_to_latlng(address)
            places = p.query(address)
            
            return render_template('home.html',form=form, my_coordinates, places=places)
    
    elif request.method == "GET":
        return render_template('home.html',form=form, my_coordinates, places=places)
Example #26
0
def places_of_a_city(city_id):
    '''
        GET: list all places in a specific city
        POST: add a place to a specific city
    '''
    my_city = storage.get('City', city_id)
    if my_city is None:
        abort(404)
    if request.method == 'POST':
        place_dict = request.get_json()
        if place_dict is None:
            return 'Not a JSON', 400
        if 'user_id' not in place_dict.keys():
            return 'Missing user_id', 400
        if 'name' not in place_dict.keys():
            return 'Missing name', 400
        place_dict['city_id'] = city_id
        try:
            my_place = Place(**place_dict)
            my_place.save()
        except:
            abort(404)
        return jsonify(my_place.to_dict()), 201
    my_places = [
        place.to_dict() for place in storage.all('Place').values()
        if place.city_id == city_id
    ]
    return jsonify(my_places)
Example #27
0
def home():
    if 'email' not in session:
        return redirect(url_for('login'))

    form = AddressForm()

    places = []
    my_coordinates = (66, -99)

    if request.method == 'POST':
        if form.validate() == False:
            return render_template('home.html',
                                   form=form,
                                   my_coordinates=my_coordinates,
                                   places=places)
        else:
            address = form.address.data
            print(address)

            p = Place()
            my_coordinates = p.address_to_latlng(address)
            places = p.get_places(*my_coordinates)

            return render_template('home.html',
                                   form=form,
                                   my_coordinates=my_coordinates,
                                   places=places)
    elif request.method == 'GET':
        return render_template('home.html',
                               form=form,
                               my_coordinates=my_coordinates,
                               places=places)
Example #28
0
def home():
    if "email" not in session:
        return redirect(url_for("login"))

    form = AddressForm()

    places = []
    my_coordinates = (40.7308619, -73.9871558)

    if request.method == "POST":
        if form.validate() == False:
            return render_template("home.html", form=form)
        else:
            # get the address
            address = form.address.data

            # query for places around it
            my_point = Place()
            my_coordinates = my_point.address_to_latlng(address)
            places = my_point.query(address)

            # return those results
            return render_template("home.html",
                                   form=form,
                                   my_coordinates=my_coordinates,
                                   places=places)

    elif request.method == "GET":
        return render_template("home.html",
                               form=form,
                               my_coordinates=my_coordinates,
                               places=places)
Example #29
0
 def setUp(self):
     self.p1 = Place(name='Demon Dogs', address='944 W. Fullerton')
     self.p1.save()
     self.p2 = Place(name='Ace Hardware', address='1013 N. Ashland')
     self.p2.save()
     self.r = Restaurant(place=self.p1, serves_hot_dogs=True, serves_pizza=False)
     self.r.save()
Example #30
0
def post_place(city_id):
    """Creates a Place
    Args:
        city_id: id of the city in uuid format
    Returns:
        jsonified version of created place
    """
    if storage.get("City", city_id) is None:
        abort(404)
    if not request.json:
        return jsonify({"error": "Not a JSON"}), 400
    place_dict = request.get_json()
    if "user_id" not in place_dict:
        return jsonify({"error": "Missing user_id"}), 400
    if storage.get("User", place_dict["user_id"]) is None:
        abort(404)
    if "name" not in place_dict:
        return jsonify({"error": "Missing name"}), 400
    else:
        p_user_id = place_dict["user_id"]
        p_name = place_dict["name"]
        place = Place(user_id=p_user_id, name=p_name, city_id=city_id)
        for key, value in place_dict.items():
            setattr(place, key, value)
        place.save()
        return jsonify(place.to_dict()), 201
Example #31
0
def query(request):
	if request.method == 'POST':
		latitude_pass = request.POST.get('lat', None)
		longitude_pass = request.POST.get('long', None)	
	else:
		latitude_pass = request.GET.get('lat', None)
		longitude_pass = request.GET.get('long', None)	
		
	if latitude_pass and longitude_pass:
		now = datetime.utcnow().replace(tzinfo=tz.tzutc())
		# guess[0] = place name, guess[1] = place lat, guess[2] = place longitude
		guess = searchPlaces(latitude_pass, longitude_pass)
		places = [obj.name for obj in Place.objects.all()]
		# use it from db if already exist, otherwise create a new one
		if guess[0] not in places:
			predict = Place(name=guess[0], latitude=guess[1], longitude=guess[2], time=now)
			predict.save()
		else:
			predict = Place.objects.get(name=guess[0])
		Track(
			latitude = latitude_pass,
			longitude = longitude_pass,
			prediction=predict,
			time=now
			).save()
		return HttpResponse('GET successful')
	else:
		return redirect('/')
Example #32
0
def home():
    form = AddressForm()

    places = []
    my_coordinates = (37.4221, -122.0844)

    if 'email' not in session:
        return redirect(url_for('login'))

    if request.method == 'POST':
        if form.validate() == False:
            return render_template('home.html', form=form)
        else:
            #get the address
            address = form.address.data

            #want to use geodata api - make a model (models.py)
            #query places around address
            p = Place()
            my_coordinates = p.address_to_latlng(address)
            places = p.query(address)

            return render_template('home.html',
                                   form=form,
                                   my_coordinates=my_coordinates,
                                   places=places)

    elif request.method == 'GET':
        return render_template("home.html",
                               form=form,
                               my_coordinates=my_coordinates,
                               places=places)
def home():

    form = AddressForm()

    places = []
    my_coordinates = (34.023076, -118.2870456)

    if request.method == 'POST':
        if form.validate() == False:
            return render_template('home.html', form=form)
        else:
            # get the address
            address = form.address.data

            # query for places around it
            p = Place()
            my_coordinates = p.address_to_latlng(address)
            places = p.query(address)

            # return those results
            return render_template('home.html',
                                   form=form,
                                   my_coordinates=my_coordinates,
                                   places=places)

    elif request.method == 'GET':
        return render_template("home.html",
                               form=form,
                               my_coordinates=my_coordinates,
                               places=places)
Example #34
0
def home():
    #enable this to have user login and permission
    # if 'email' not in session:
    #    return redirect(url_for('login'))

    form = AddressForm()

    places = []
    my_coordinates = (43.6629, -79.3957)

    if request.method == 'POST':
        if form.validate() == False:
            return render_template('home.html', form=form)
        else:
            # get the address
            address = form.address.data

            # query for places around it
            p = Place()
            my_coordinates = p.address_to_latlng(address)
            places = p.query(address)

            # return those results
            return render_template('home.html',
                                   form=form,
                                   my_coordinates=my_coordinates,
                                   places=places)

    elif request.method == 'GET':
        return render_template("home.html",
                               form=form,
                               my_coordinates=my_coordinates,
                               places=places)
Example #35
0
def home():
    if 'email' not in session:  #checks to see if logged in or not
        return redirect(url_for('login'))

    form = AddressForm()

    places = []
    my_coordinates = (41.7508, 88.1535)

    if request.method == 'POST':
        if form.validate() == False:
            my_coordinates = (41.7508, 88.1535)
            return render_template('home.html',
                                   form=form,
                                   my_coordinates=my_coordinates)
        else:
            # get the address
            address = form.address.data
            # query for places around it
            p = Place()
            my_coordinates = p.address_to_latlng(address)
            places = p.query(address)

            # return those results
            return render_template('home.html',
                                   form=form,
                                   my_coordinates=my_coordinates,
                                   places=places)

    elif request.method == 'GET':
        return render_template("home.html",
                               form=form,
                               my_coordinates=my_coordinates,
                               places=places)
Example #36
0
def home():
    if 'email' not in session:
        return redirect(url_for('LogIn'))
    #return render_template('home.html',email=session['email'])
    form = AddressForm()
    places = []
    my_coor = (37.4221, -122.0844)
    if request.method == 'POST':
        if (form.validate == False):
            return render_template('home.html', form=form)
        else:
            #get address
            address = form.address.data
            #use address with api
            p = Place()
            my_coor = p.address_to_lat_lon(address)
            places = p.query(address)
            #return result
            return render_template('home.html',
                                   form=form,
                                   my_coor=my_coor,
                                   places=places)
    elif request.method == 'GET':
        return render_template('home.html',
                               form=form,
                               my_coor=my_coor,
                               places=places)
Example #37
0
def home():
    if 'email' not in session:
        return redirect(url_for('login'))

    form = AddressForm()
    places = []
    my_coordinates = (37.4221, -122.0844)

    if request.method == 'POST':
        if form.validate() == False:
            return render_template("home.html",
                                   form=form,
                                   my_coordinates=my_coordinates,
                                   places=places)
        else:
            address = form.address.data
            p = Place()
            my_coordinates = p.address_to_latlng(address)
            places = p.query(address)
            return render_template("home.html",
                                   form=form,
                                   my_coordinates=my_coordinates,
                                   places=places)

    if request.method == 'GET':
        return render_template("home.html",
                               form=form,
                               my_coordinates=my_coordinates,
                               places=places)

    return render_template("home.html")
Example #38
0
def add_polling_centers(state, filename):
    d = {}
    with db.transaction():
        for ac_code, px_code, pb_code, name in read_csv(filename):
            print "adding polling center", state.id, ac_code, px_code
            if (ac_code, px_code) not in d:
                key = "{0}/{1}/{2}".format(state.key, ac_code, px_code)                    
                if not db.select("places", where="type='PX' AND key=$key", vars=locals()):
                    pb_key = "{0}/{1}/{2}".format(state.key, ac_code, pb_code)
                    pb = Place.find(pb_key)
                    lazy_insert("places", key=key, name=name, type="PX", 
                        code=key.split("/")[-1],
                        state_id=state.id,
                        region_id=pb.region_id,
                        pc_id=pb.pc_id,
                        ac_id=pb.ac_id,
                        ward_id=pb.ward_id)
                d[ac_code, px_code] = 1
        commit_lazy_inserts()

    with db.transaction():
        for ac_code, px_code, pb_code, name in read_csv(filename):
            key = "{0}/{1}/{2}".format(state.key, ac_code, px_code)                    
            px = Place.find(key)
            pb_key = "{0}/{1}/{2}".format(state.key, ac_code, pb_code)
            db.update("places", px_id=px.id, where="key=$pb_key", vars=locals())
Example #39
0
def home():
  if 'email' not in session:
    return redirect(url_for('login'))

  form = AddressForm()

  places = []
  my_coordinates = (5.3109351,-1.9924259)

  if request.method == 'POST':
    if form.validate() == False:
      return render_template('home.html', form=form)
    else:
      # get the address
      address = form.address.data

      # query for places around it
      p = Place()
      my_coordinates = p.address_to_latlng(address)
      places = p.query(address)

      # return those results
      return render_template('home.html', form=form, my_coordinates=my_coordinates, places=places)

  elif request.method == 'GET':
    return render_template("home.html", form=form, my_coordinates=my_coordinates, places=places)
Example #40
0
def home():
    if 'email' not in session:
        return redirect(url_for('login'))

    form = AddressForm()

    places = []
    my_coordinates = (45.975589, 15.060825)

    if request.method == 'POST':
        if not form.validate():
            return render_template('home.html', form=form)
        else:
            # get the address
            address = form.address.data
            # query for places around it
            p = Place()
            my_coordinates = p.address_to_latlng(address)
            places = p.query(address)
            # return those results
            return render_template('home.html', form=form, my_coordinates=my_coordinates, places=places)

    elif request.method == 'GET':
        return render_template('home.html', form=form, my_coordinates=my_coordinates, places=places)

    return render_template('home.html')
Example #41
0
	def save_place( self, name, geojson ):
		owner = self.auth.user.auth_id
		place = Place( name=name, owner=owner, geojson=geojson )
		place.put()
		key = str( place.key() )
		self.session['current_place'] = key
		return {
			'key': str( place.key() )
		}
Example #42
0
def createNew(request):
    if request.method == 'POST':
        payload = json.loads(request.body)
        thisx, thisy = payload.get('location', None).split(',')
        pnt = GEOSGeometry('POINT(%s %s)' % (thisx, thisy))
        this_place = Place(name = payload.get('name', None), location = pnt)
        this_place.save()
        return HttpResponse('Success')
    else:
        return HttpResponseBadRequest('Missing POST data')
Example #43
0
def place_page(place_id=None):
    if request.method == 'POST':
        p = Place.get_by_id(place_id)

        # for add subscriber form
        if 'email' in request.form:
            email = request.form.get('email', '')
            if email not in [u.email for u in User.all()]:
                u = User(
                    email=email,
                    suscribed_at=datetime.datetime.now())
                u.put()
            else:
                u = User.gql("WHERE email = '{0}'".format(email)).get()

            up = UserPlace.all().filter('user ='******'place =', p).get()
            
            if up:
                return "This user already exists in subscribers!"
            else:
                if u.places_subscribed.count() >= 4:
                    return "This user has maximum subscribing"
                up = UserPlace(
                    user=u,
                    place=p
                )
                up.put()

        # for add update form
        elif 'update_link' in request.form and 'update_info' in request.form:
            update_link = request.form.get('update_link', '')
            update_info = request.form.get('update_info', '')
            u = Update(
                place=p,
                link=update_link,
                info=update_info
            )
            u.put()

        # for add link form
        elif 'link_link' in request.form and 'link_description' in request.form:
            link_link = request.form.get('link_link', '')
            link_description = request.form.get('link_description', '')
            l = PlaceLink(
                place=p,
                link=link_link,
                description=link_description
            )
            l.put()

    p = Place.get_by_id(place_id)
    updates = [update for update in p.place_updates.order('-added_at')]
    links = [link for link in p.placelink_set.order('-added_at')]

    return render_template('place.html', place=p, updates=updates, links=links)
Example #44
0
def place_delete(place_id, place_key_str):
    try:
        pkey = Place.make_key(place_id, place_key_str)
        cluster_ratings = ClusterRating.get_list({'place': pkey.urlsafe()})
        for cr in cluster_ratings:
            ClusterRating.delete(cr.key)
        user_ratings = Rating.get_list({'place': pkey.urlsafe()})
        for r in user_ratings:
            Rating.delete(r.key)
        res = Place.delete(pkey)
    except TypeError, e:
        return None, str(e), 400
Example #45
0
def fillConsumingPlaces(response):
    places = []
    for i in response["results"]:
        place = Place()
        ID = i["place_id"]
        place = getDetailsForID(ID, place)
        place.reward = ""
        pointsToSpend = random.randint(0, 100)
        place.offerPoints = str(pointsToSpend)
        place.offerText = "Get our special offer for " + place.offerPoints + " points"
        place.placeType = "consuming"
        places.append(place)
    return places
Example #46
0
    def test_simple_place_creation(self):
        """
        Creates test place
        """
        places = Place.objects.filter(name = "Test Place")
        [place.delete() for place in places]

        place = Place()
        place.name = "Test Place"
        place.capacity = 20
        place.save()

        place = Place.objects.filter(name = "Test Place")
        print place
        self.assertNotEqual(place, None)
Example #47
0
def savePlace(request):
    tokenId = request.GET["token"]
    voiceId = request.GET["voiceId"]
    placeId = request.GET["placeId"]
    lat = request.GET["lat"]
    lon = request.GET["lon"]

    user = User.objects.get(tokenHash=tokenId)
    voice = Voice.objects.get(sender=user, id=voiceId)
    place = Place(voice=voice, placeId=placeId, latitude=lat, longitude=lon);
    place.save()



    return JsonResponse({"success" : "1" })
Example #48
0
    def POST_update_pcs(self, place, data):
        for row in data:
            key = place.key + "/" + row['code']
            pc = Place.find(key)

            if row['region'] and row['region'].strip():
                # Extract te group code from its name
                key = place.key + "/" + row['region'].split("-")[0].strip()
                region = Place.find(key)
                if pc.region_id != region.id:
                    pc.set_parent("REGION", region)
            else:
                pc.set_parent("REGION", None)
        web.header("content-type", "application/json")
        return '{"result": "ok"}'
Example #49
0
    def add_places(self, user):
    
        # Add 10 Places
        places = [
            'the CN Tower',
            'the Eiffel Tower',
            'Athens Greece',
            'the Great Pyramids',
            'the Great Wall of China',
            'the Louvre',
            'the Palace of Versailles',
            'Sydney Australia',
            'the Grand Canyon',
            'Bora Bora'
        ]
        
        self.response.out.write('<hr/>Adding places to go<hr/>')
        
        # Get all list items for the current user        
        query = UserListItems.gql('WHERE user = :user', user=user)
        user_list_items = query.get()
        
        if user_list_items is None:
            user_list_items = UserListItems(user=user)        
        
        for name in places:
            place = Place()
            place.title = name
            place.put()
            
            # Add Reference to the Place from User
            user_list_item = UserListItem()
            user_list_item.user = user
            user_list_item.list_item = place
            
            # Update the list of items the user has
            user_list_items.list_items.append(place.key())
            
            # Add the specifics of the user list item linkage
            user_list_item = UserListItem()
            user_list_item.user = user
            user_list_item.list_item = place
            one_year = datetime.timedelta(days=365)
            today = datetime.datetime.today()
            user_list_item.date_due = today + one_year
            user_list_item.put()            

            self.response.out.write('Added %s<br/>' % place)
Example #50
0
 def get(self):
     user_id = logic.get_current_userid(self.request.cookies.get('user'))
     if user_id is None:
         self.redirect('/')
         return
     user, status, errcode = logic.user_get(user_id, None)
     if status != "OK":
         self.render("error.html", {'error_code': errcode, 'error_string': status, 'lang': LANG})
         return
     get_values = self.request.GET
     if not get_values:
         if user.role != 'admin':
             self.redirect('/error')
         else:
             self.render('restaurant_list_edit.html',{'user': user, 'lang' : LANG});
     else:
         place_key =  get_values.get('id')
         place, status, errcode = logic.place_get(None, place_key)
         if status == 'OK':
             try:
                 place = Place.to_json(place, None, None)
                 self.render('restaurant_edit.html', {'place': place, 'hours_string': json.dumps(place['hours']), 'closed': json.dumps(place['days_closed']), 'user': user, 'lang' : LANG });
             except TypeError, e:
                 # TODO: handle error
                 self.render("error.html", {'error_code': 500, 'error_string': str(e), 'lang': LANG})
                 return
         else:
Example #51
0
 def get(self):
     user_id = logic.get_current_userid(self.request.cookies.get('user'))
     if user_id is None:
         self.redirect('/')
         return
     
     user, status, errcode = logic.user_get(user_id, None)
     if status != "OK":
         self.render("error.html", {'error_code': errcode, 'error_string': status, 'lang': LANG})
         return
      
     place, status, errcode = logic.place_get(None, self.request.GET.get('rest_id'))
     if status == 'OK':
         if place is None:
             self.render("error.html", {'error_code': 404, 'error_string': "Restaurant not found", 'lang': LANG})
             return 
         try:
             place = Place.to_json(place, None, None)
             if 'description_' + LANG_NAME in place:
                 place['description'] = place['description_' + LANG_NAME]
             self.render('discount_manage.html', {'place': place, 'user': PFuser.to_json(user, [], []), 'lang' : LANG, 'lang_name' : LANG_NAME });
             return
         except TypeError, e:
             self.render("error.html", {'error_code': 500, 'error_string': str(e), 'lang': LANG})
             return
Example #52
0
 def get(self):
     post_query = Post.query().order(-Post.time).fetch()
     place_query = Place.query().fetch()
     time = None
     for post in post_query:
         time = post.time.strftime("%a %d-%b-%Y %H:%M")
     self.render_template('index.html',{'posts':post_query, 'time':time, 'places': place_query})
Example #53
0
    def post(self):
        if 'owned' in self.request.url:
            self.response.set_status(405)
            return
        
        logging.info("Received new place to save: " + self.request.body)
        # TODO: only an admin can create new places
#         auth = self.request.headers.get("Authorization")
#         if auth is None or len(auth) < 1:
#             auth = self.request.cookies.get("user")
#         if auth is None:
#             user_id = None
#         else:
#             user_id = logic.get_current_userid(auth)
#         if user_id is None:
#             self.response.set_status(403)
#             self.response.write("You must login first!")
#             return
        
        
        body = json.loads(self.request.body)
        try:
            place = Place.from_json(body)
        except TypeError, e:
            self.response.set_status(400)
            self.response.write(str(e))
            return
Example #54
0
def place_list_get(filters, user_id):
    """
    It retrieves a list of places corresponding to the specified filters.

    Parameters:
    - filters: a dictionary containing the characteristics the returned places should have.
    - user_id: if it s set, the personal data about the user added to each place (like ratings)

    Available filters:
        - 'city': 'city!province!state!country'
            The 'city' filter contains the full description of the city, with values separated with a '!'. 
            This string is split and used to retrieve only the places that are in the specified city. 
            'null' is used if part of the full city description is not available [example: 'Trento!TN!null!Italy'
            or if a bigger reagion is considered [example: 'null!TN!null!Italy' retrieves all places in the province of Trento]
        - 'lat', 'lon' and 'max_dist': lat and lon indicates the user position, while max_dist is a measure expressed in meters 
            and represnt the radius of the circular region the user is interested in. 

    Returns a tuple:
    - list of Places that satisfy the filters
    - status message
    - the http code indicating the type of error, if any
    """
    try:
        res = Place.get_list(filters, user_id)
    except (TypeError, ValueError) as e:
        return None, str(e), 400

    return res, "OK", 200
Example #55
0
def do_enter():
    """Enter numbers into database"""
    numbers = set(parse_numbers(request.forms.get('numbers', '')))
    timestamp = datetime.datetime.now()

    usr_hash = get_fingerprint(request)

    result_num = []

    # TODO make place variable, depending on current request
    q = Place.select().where(Place.place == 'LAGESO')
    lageso = q.get() if q.count() == 1 else None

    if not numbers:
        result_num.append(_('novalidnumbers'))
    else:
        for num in numbers:
            if is_valid_number(num):
                try:
                    n = Number.create(number=num.upper(), time=timestamp, place=lageso, fingerprint=usr_hash)
                    result_num.append(n.number)
                except IntegrityError:
                    try:
                        n = Number.get(Number.number == num.upper())
                        # FIXME Why ain't there any value placeholder in translation string?
                        result_num.append(_(u'erruniquenumber') + ': {}'.format(n.number))
                    except DoesNotExist:
                        result_num.append(u'Something weired happend with {}'.format(num))

    # FIXME result_num is horrible, as it contains success and failures, indistinguishable
    return {'entered': result_num, 'timestamp': timestamp.strftime('%x %X')}
Example #56
0
    def POST(self):
        i = web.input()
        token = i.get('token')
        place_key = i.get('place')
        #client_key = i['client_key']
        #client_secret = i['client_secret']

        user = account.token2user(token)
        place = Place.find(key=place_key)

        if not user:
            return jsonify(
                    status='failed',
                    code='error_token_invalid',
                    message='Token is either invalid or expired.')

        if not place:
            return jsonify(
                    status='failed',
                    code='error_invalid_input',
                    message='Invalid Place')

        if not place.writable_by(user):
            return jsonify(
                    status='failed',
                    code='error_permission_denied',
                    message="User doesn't have permission to modify data at this place.")
        else:
            return jsonify(
                    status='ok',
                    code='authorized',
                    message='The user is authorized to modify data at this place.')
Example #57
0
    def GET(self, key):
        place = Place.find(key)
        if not place:
            raise web.notfound()

        booths = place.get_all_polling_booths()
        from collections import defaultdict
        d = defaultdict(list)
        pxd = {}
        for booth in booths:
            px = booth.get_parent("PX")
            px_code = px.key.split("/")[-1]
            d[px_code].append(booth)
            pxd[px_code] = px

        def get_row(px_code):
            booths = d[px_code]
            px = pxd[px_code]
            ward = px.get_parent("WARD")
            ward_name = ward and ward.name or "-"
            return [place.code, place.name, px_code, ",".join(b.code for b in booths), px.name, ward_name]

        data = [get_row(px_code) for px_code in sorted(d)]
        web.header("content-type", "text/plain")
        return "\n".join("\t".join(row) for row in data)
Example #58
0
 def POST(self, code):
     place = Place.find(key=code)
     if not place:
         raise web.notfound()
     i = web.input(info="")
     place.update_info(i.info)
     raise web.seeother(place.url + "/info")
Example #59
0
def main():
    import sys
    import webapp
    webapp.check_config()

    global db 
    db = get_db()

    if "--add-admin" in sys.argv:
        index = sys.argv.index("--add-admin")
        email = sys.argv[index+1]
        state = Place.find(key=webapp.get_state())

        # Hack to fix the error at account.get_current_user() when adding volunteer
        web.ctx.current_user = None

        state.add_volunteer("Fix Your Name", email, "0000000000", role="admin")
        return
    if "--polling-centers" in sys.argv:
        index = sys.argv.index("--polling-centers")
        state_code = sys.argv[index+1]
        filename = sys.argv[index+2]
        state = Place.find(state_code)
        print "add_polling_centers", state, filename
        add_polling_centers(state, filename)
        return
    if "--wards" in sys.argv:
        index = sys.argv.index("--wards")
        state_code = sys.argv[index+1]
        filename = sys.argv[index+2]
        state = Place.find(state_code)
        print "add_wards", state, filename
        add_wards(state, filename)
        return


    
    dir = sys.argv[1]
    code = sys.argv[2]
    name = sys.argv[3]

    state = add_state(code, name)

    add_pcs(state, dir)
    add_acs(state, dir)
    #add_wards(state, dir)
    add_polling_booths(state, dir)
Example #60
0
def autoadd_pb_agents(place_key):
    """Finds all volunteers in the place and adds a new role as polling booth agent.
    """
    place = Place.find(place_key)
    if not place:
        raise ValueError("Invalid place {0}".format(place_key))

    _add_pb_agents(place, place.get_all_volunteers())