示例#1
0
文件: db.py 项目: ahinkka/paikkis
def build(input, database, verbose):
    conn = sqlite3.connect(database)
    c = conn.cursor()
    c.execute(CREATE_TABLE)
    c.execute(CREATE_INDEX)
    c.execute(CREATE_FTS_TABLE)
    conn.commit()

    size = os.path.getsize(input)
    total_read = 0
    with codecs.open(input, 'r', encoding='iso-8859-10') as f:
        for linenum, line in enumerate(f):
            total_read += len(line)
            parts = [
                item.strip() for item in line.replace("\n", "").split(";")
                if len(item) > 0
            ]

            p = Place(parts)
            c.execute(*p.insert_stmt())
            c.execute(*p.insert_fts_stmt())

            if linenum % 10000 == 0:
                conn.commit()
                print(u"# {0:.3}% {1}...".format(
                    100 * (float(total_read) / float(size)), str(p)))
        conn.commit()
示例#2
0
文件: db.py 项目: guaq/paikkis
def build(input, database, verbose):
    conn = sqlite3.connect(database)
    c = conn.cursor()
    c.execute(CREATE_TABLE)
    c.execute(CREATE_INDEX)
    c.execute(CREATE_FTS_TABLE)
    conn.commit()

    size = os.path.getsize(input)
    total_read = 0
    with codecs.open(input, 'r', encoding='iso-8859-10') as f:
        for linenum, line in enumerate(f):
            total_read += len(line)
            parts = [item.strip()
                     for item in line.replace("\n", "").split(";")
                     if len(item) > 0]

            p = Place(parts)
            c.execute(*p.insert_stmt())
            c.execute(*p.insert_fts_stmt())

            if linenum % 10000 == 0:
                conn.commit()
                print(u"# {0:.3}% {1}...".format(100 * (float(total_read) / float(size)),
                                                str(p)))
        conn.commit()
示例#3
0
def home():
    if 'email' not in session:
        return redirect(url_for('login'))

    form = AddressForm()

    places = []
    my_coordinates = (13.803513, 100.553042)

    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)
class CoverageController(BaseController):
    """Converts coverage area descriptions to GeoJSON documents
    so they can be visualized.
    """
    def geojson_response(self, document):
        if isinstance(document, dict):
            document = json.dumps(document)
        headers = {"Content-Type": "application/geo+json"}
        return Response(document, 200, headers=headers)

    def lookup(self):
        coverage = flask.request.args.get('coverage')
        try:
            coverage = json.loads(coverage)
        except ValueError, e:
            pass
        places, unknown, ambiguous = AuthenticationDocument.parse_coverage(
            self._db, coverage)
        document = Place.to_geojson(self._db, *places)

        # Extend the GeoJSON with extra information about parts of the
        # coverage document we found ambiguous or couldn't associate
        # with a Place.
        if unknown:
            document['unknown'] = unknown
        if ambiguous:
            document['ambiguous'] = ambiguous
        return self.geojson_response(document)
示例#5
0
 def _parse(self, location: str, json_resp: Dict[str, Any]) -> Place:
     return Place(location=location,
                  city=json_resp[0].get("address", {}).get("city", None),
                  postcode=json_resp[0].get("address",
                                            {}).get("postcode", None),
                  lat=float(json_resp[0]["lat"]),
                  lon=float(json_resp[0]["lon"]))
示例#6
0
def load_places():
    """Load places from places.txt into database."""

    print("Places")

    for i, row in enumerate(open("seed_data/places.txt")):
        row = row.rstrip()
        place_id, lat, lng, viewport_ne_lat, viewport_ne_lng, viewport_sw_lat, viewport_sw_lng, formatted_address, maps_name, rating, phone_number, opening_hours, website = row.split(
            '|')

        place = Place(place_id=place_id,
                      lat=lat,
                      lng=lng,
                      viewport_ne_lat=viewport_ne_lat,
                      viewport_ne_lng=viewport_ne_lng,
                      viewport_sw_lat=viewport_sw_lat,
                      viewport_sw_lng=viewport_sw_lng,
                      formatted_address=formatted_address,
                      maps_name=maps_name,
                      rating=rating,
                      phone_number=phone_number,
                      opening_hours=opening_hours,
                      website=website)

        db.session.add(place)

        # provide some sense of progress
        if i % 100 == 0:
            print(i)

        db.session.commit()
    def testSecond(self):
        session.query(Event).delete()
        session.query(Person).delete()
        session.query(Place).delete()
        session.commit()

        place = Place('First place')
        place.address = 'Address'
        place.phone = 'Phone'
        place.site_url = 'http://localhost'
        persons_list = []
        persons_list.append(Person('First', Person.MUSICIAN))
        persons_list.append(Person('Second', Person.MUSICIAN))
        e = Event(self.et)
        e.place = place
        for p in persons_list:
            e.persons.append(p)
        session.add(e)
        session.commit()
        session.flush()

        first_query = self.first_query
        all_first = first_query.all()
        self.assertEquals(len(all_first), 1)
        e = all_first[0]
        place = e.place
        self.assertEquals(place.address, 'Address')
        self.assertEquals(place.phone, 'Phone')
        self.assertEquals(place.site_url, 'http://localhost')
        person_names = []
        for p in e.persons:
            person_names.append(p.name)
        self.assert_('First' in person_names)
        self.assert_('Second' in person_names)

        e = Event(EventType.findByName(session, 'live'), 'Live event')
        e.addEventStatus(EventStatus(EventStatus.LIVE_WANT))
        e.addEventStatus(EventStatus(EventStatus.LIVE_BE_HERE))
        session.add(e)
        session.commit()
        session.flush()

        events = self.live_query.all()
        self.assertEquals(len(events), 1)
        e = events[0]
        self.assertEquals(len(e.event_status_list), 2)
        self.assertEquals(e.last_status, EventStatus.LIVE_BE_HERE)
    def testSecond(self):
        session.query(Event).delete()
        session.query(Person).delete()
        session.query(Place).delete()
        session.commit()

        place = Place('First place')
        place.address = 'Address'
        place.phone = 'Phone'
        place.site_url = 'http://localhost';
        persons_list = [] 
        persons_list.append(Person('First', Person.MUSICIAN))
        persons_list.append(Person('Second', Person.MUSICIAN))
        e = Event(self.et)
        e.place = place
        for p in persons_list:
            e.persons.append(p)
        session.add(e)
        session.commit()
        session.flush()

        first_query = self.first_query
        all_first = first_query.all()
        self.assertEquals(len(all_first), 1)
        e = all_first[0]
        place = e.place
        self.assertEquals(place.address, 'Address')
        self.assertEquals(place.phone, 'Phone')
        self.assertEquals(place.site_url, 'http://localhost')
        person_names = []
        for p in e.persons:
            person_names.append(p.name)
        self.assert_('First' in person_names)
        self.assert_('Second' in person_names)
       
        e = Event(EventType.findByName(session, 'live'), 'Live event')
        e.addEventStatus(EventStatus(EventStatus.LIVE_WANT))
        e.addEventStatus(EventStatus(EventStatus.LIVE_BE_HERE))
        session.add(e)
        session.commit()
        session.flush()

        events = self.live_query.all()
        self.assertEquals(len(events), 1);
        e = events[0]
        self.assertEquals(len(e.event_status_list), 2)
        self.assertEquals(e.last_status, EventStatus.LIVE_BE_HERE)
示例#9
0
 def resolve(self, query_address: str, location: str) -> Place:
     resolve_url = self.BASE_API_URL_FMT.format(
         self.api_key, parse.quote(copy(query_address)))
     r = requests.get(url=resolve_url)
     if r.ok:
         json_resp = r.json()
         if len(json_resp):
             return self._parse(location, json_resp)
         else:
             self.log.warning(
                 f"No response for {query_address}: {r.status_code} {r.content}"
             )
             return Place(location, None, None, None, None)
     else:
         self.log.warning(
             f"MapQuest returned error for query {query_address}: {r.status_code} {r.content}"
         )
         return Place(location, None, None, None, None)
 def _geojson_for_service_area(self, service_type):
     """Serve a GeoJSON document describing some subset of the active
     library's service areas.
     """
     areas = [
         x.place for x in flask.request.library.service_areas
         if x.type == service_type
     ]
     return self.geojson_response(Place.to_geojson(self._db, *areas))
示例#11
0
def add_places_to_db(city_id, data, place_type):
    """Add places gathered from Google Places to DB."""

    for result in data['results']:
        place = Place(google_place_id=result['place_id'],
                      city_id=city_id,
                      name=result['name'].encode('utf8'),
                      lat=result['geometry']['location']['lat'],
                      lon=result['geometry']['location']['lng'],
                      place_type=place_type)
        db.session.add(place)
    db.session.commit()
示例#12
0
def returnPage():##check the user login or not
    # if 'email' not in session:
    #    return redirect(url_for('login'))
     form = Address()
     places = []
     my_coordinates = (45.348306,-75.756240) ##default algonquin college latitude and longitude

     if request.method == 'POST':
         if form.validate() == False:
             return render_template('returnpage.html',form=form)
         else:
             ##retrieve the address from the form and save into varigable Address
             address=form.address.data
             ##query the places in flask
             p = Place()##new useable of place model
             ##convert the address input into latitude and longitude
             my_coordinates = p.address_to_latlng(address)
             places = p.query(address)##query these places around coordinates
             return render_template('returnpage.html', form=form,my_coordinates=my_coordinates,places=places)
     elif request.method == 'GET':
          return render_template("returnpage.html",form = form,my_coordinates=my_coordinates,places=places)
示例#13
0
def home():
	#if 'email' not in session: # make sure if user is not logged in, he cant access to the home page 
		#return redirect(url_for('login'))
	if not is_loggedin():
		return redirect(url_for('login'))
	places=[]
	my_coordinates=(37.4221, -122.0844)
	form =AddressForm()
	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)
示例#14
0
 def get(self, id):
     id = str(id)
     org_key = ndb.Key('Organization', id)
     client_id = users.get_current_user().user_id()
     if client_id != id:
         user_key = ndb.Key('User', client_id)
         user = user_key.get()
         if user is None or org_key not in user.works_for_organizations:
             abort(401)
     query = Place.query_by_org(org_key)
     response = {'places': ndb_util.query_to_dict_list(query)}
     return response
    def test_update_service_areas(self):

        # This Library has no ServiceAreas associated with it.
        library = self._library()

        country1 = self._place(abbreviated_name="C1", type=Place.NATION)
        country2 = self._place(abbreviated_name="C2", type=Place.NATION)

        everywhere = AuthenticationDocument.COVERAGE_EVERYWHERE
        doc_dict = dict(service_area=everywhere,
                        focus_area={
                            country1.abbreviated_name: everywhere,
                            country2.abbreviated_name: everywhere
                        })
        doc = AuthenticationDocument.from_dict(self._db, doc_dict)
        problem = doc.update_service_areas(library)
        self._db.commit()
        eq_(None, problem)

        # Now this Library has three associated ServiceAreas.
        [a1, a2, a3] = sorted([(x.type, x.place.abbreviated_name)
                               for x in library.service_areas])
        everywhere_place = Place.everywhere(self._db)

        # Anyone is eligible for access.
        eq_(('eligibility', everywhere_place.abbreviated_name), a1)

        # But people in two particular countries are the focus.
        eq_(('focus', country1.abbreviated_name), a2)
        eq_(('focus', country2.abbreviated_name), a3)

        # Remove one of the countries from the focus, add a new one,
        # and try again.
        country3 = self._place(abbreviated_name="C3", type=Place.NATION)
        doc_dict = dict(service_area=everywhere,
                        focus_area={
                            country1.abbreviated_name: everywhere,
                            country3.abbreviated_name: everywhere
                        })
        doc = AuthenticationDocument.from_dict(self._db, doc_dict)
        doc.update_service_areas(library)
        self._db.commit()

        # The ServiceArea for country #2 has been removed.
        assert a2 not in library.service_areas
        assert not any(a.place == country2 for a in library.service_areas)

        [a1, a2, a3] = sorted([(x.type, x.place.abbreviated_name)
                               for x in library.service_areas])
        eq_(('eligibility', everywhere_place.abbreviated_name), a1)
        eq_(('focus', country1.abbreviated_name), a2)
        eq_(('focus', country3.abbreviated_name), a3)
示例#16
0
def add_place_to_database(map_id, google_place_name, address, website, place_types, google_places_id, latitude, longitude, user_notes):
    """Add place to database"""
    new_place = Place(map_id=map_id, 
                    google_place_name=google_place_name,
                    address=address,
                    website=website,
                    place_types=place_types,
                    google_places_id=google_places_id,
                    latitude=latitude, 
                    longitude=longitude, 
                    user_notes=user_notes)
    db.session.add(new_place)
    db.session.commit()
示例#17
0
def create_place(wikipedia, xid, name, image, extract, location_id):
    """Create and return a new place."""

    new_place = Place(  wikipedia=wikipedia,
                        xid=xid,
                        name=name,
                        image=image,
                        extract=extract,
                        location_id=location_id)

    db.session.add(new_place)
    db.session.commit()

    return new_place
示例#18
0
def showdata():
	"""Method that takes into account user activity
	of bookmarks of events and shelters on the frontend
	and adjusts database accordingly."""

	# Get the currently logged in user id
	if session.get('user_id',0) != 0:
		user_id = session['user_id']

	# If the user has clicked on a shelter, get the general business 
	# information of the shelter and add or delete the entry from the db 
	# depending on the check_status flag variable
	if request.form.get("store_name"):
		place_name = request.form.get("store_name")
		place_address = request.form.get("store_address")
		place_photo = request.form.get("store_photo")
		place_website = request.form.get("business_website")
		place_hours = request.form.get("business_hours")
		check_status = request.form.get("check_status")

		place = Place.query.filter_by(user_id=user_id, place_name=place_name).first()
		
		if check_status:
			if not place:
				new_place = Place(user_id = user_id, place_name=place_name, place_address=place_address,
									 place_imURL = place_photo, place_website = place_website, place_hours = place_hours)
				db.session.add(new_place)

		if check_status=='false':
			Place.query.filter_by(user_id = user_id, place_name=place_name).delete()

		db.session.commit()

	# If the user has clicked on an event, get the event id and then add
	# or delete from the database depending on the db_action flag variable
	if request.form.get("event_id"):
		event_id = request.form.get("event_id")
		db_action = request.form.get("database_action")
		event_info = get_event_details(event_id)

		if db_action == 'add':
			new_event = Event(user_id = user_id, eventbrite_id = event_info['event_id'], event_name = event_info['event_name'], event_address = event_info['event_address'],
								event_date = event_info['event_date'], event_imURL = event_info['event_image'], event_website = event_info['eventbrite_url'])
			db.session.add(new_event)
		else:
			Event.query.filter_by(user_id = user_id, event_name=event_info['event_name']).delete()

	db.session.commit()

	return 'None'
示例#19
0
def create_place(place_name):
    ''' create a new place in the current users profile '''
    if place_name is None:
        raise ActionException('Name is required')
    my_profile = _get_my_profile()
    place = Place(name=place_name, parent=my_profile.key)
    place.name = place_name
    place.name_order = place_name.upper()
    place.updated = datetime.now()
    place.put()
    return place.key.urlsafe()
示例#20
0
def save_places():
    """Saves the places checked by the user."""
    user_id = session["user_id"]
    user = User.query.get(user_id)

    saved_businesses = request.form.getlist("saved_businesses")
    city_id = request.form["city_id"]
    arrival_date = request.form["arrival_date"]
    departure_date = request.form["departure_date"]

    trip = Trip(user_id=user_id,
                city_id=city_id,
                arrival_date=arrival_date,
                departure_date=departure_date)
    db.session.add(trip)

    for business in saved_businesses:
        # get the name from the form
        business_name = request.form[business + '__name']
        # get the label from the form
        business_label = request.form[business + '__label']
        # get the date from the form
        business_date = request.form[business + '__date']
        # get the url from the form
        business_url = request.form[business + '__url']
        # check this place already exists in db
        place = Place.query.get(business)
        if place is None:
            place = Place(yelp_id=business,
                          name=business_name,
                          place_url=business_url)
        saved_place = SavedPlace(trip=trip,
                                 place=place,
                                 meal_datetime=business_date,
                                 meal_label=business_label)

        # save the place to the database
        db.session.add(place)
        db.session.add(saved_place)

    db.session.commit()

    session["user_id"] = user.user_id

    return redirect("/users/{}".format(user.user_id))
示例#21
0
def add_place(trip_id):
    """Add place to a trip itinerary"""

    trip = Trip.query.filter_by(trip_id=trip_id).first()
    email = session.get('email')
    user = User.query.filter_by(email=email).first()
    place_name = request.args.get('place-location')
    place_exists = Place.query.filter_by(trip_id=trip_id,
                                         place_name=place_name).first()

    if place_name and place_exists == None:
        new_place = Place(trip_id=trip_id,
                          user_id=user.user_id,
                          place_name=place_name)

        db.session.add(new_place)
        db.session.commit()

    return redirect(
        url_for('trip_itinerary', trip_name=trip.trip_name, trip_id=trip_id))
示例#22
0
def convert_place_cache_from_json_to_csv(json_cache: str, csv_cache: str):
    setup_log()
    log = getLogger()
    with open(json_cache, "r") as pc:
        cache = json.load(pc)
    places: List[Place] = []
    for _, place in cache.items():
        p = Place.from_json(place)
        if p:
            places.append(p)
        else:
            log.warning(f"Could not parse into place: {place}")
    rows = []
    for p in places:
        csv_row = p.to_csv_row()
        rows.append(csv_row)
    with open(csv_cache, "w") as csv_f:
        place_writer = csv.writer(csv_f, delimiter=';', quotechar='"', quoting=csv.QUOTE_MINIMAL)
        for r in rows:
            place_writer.writerow(r)
    def test_success(self):
        us = self._place(type=Place.NATION, abbreviated_name='US')
        library = self._library()
        s = SetCoverageAreaScript(_db=self._db)

        # Setting a service area with no focus area assigns that
        # service area to the library.
        args = [
            "--library=%s" % library.name,
            '--service-area={"US": "everywhere"}'
        ]
        s.run(args)
        [area] = library.service_areas
        eq_(us, area.place)

        # Setting a focus area and not a service area treats 'everywhere'
        # as the service area.
        uk = self._place(type=Place.NATION, abbreviated_name='UK')
        args = [
            "--library=%s" % library.name, '--focus-area={"UK": "everywhere"}'
        ]
        s.run(args)
        places = [x.place for x in library.service_areas]
        eq_(2, len(places))
        assert uk in places
        assert Place.everywhere(self._db) in places

        # The library's former ServiceAreas have been removed.
        assert us not in places

        # If a default nation is set, you can name a single place as
        # your service area.
        ConfigurationSetting.sitewide(
            self._db, Configuration.DEFAULT_NATION_ABBREVIATION).value = "US"
        ut = self._place(type=Place.STATE, abbreviated_name='UT', parent=us)

        args = ["--library=%s" % library.name, '--service-area=UT']
        s.run(args)
        [area] = library.service_areas
        eq_(ut, area.place)
示例#24
0
def seed_test_data():
    "Seed the tests."
    f = "%Y-%m-%d %H:%M:%S"
    place1 = Place(
        yelp_id="Z0r83lDOA1mI8RpNccXtHw",
        name="The Fat Bear",
        place_url=
        "https://www.yelp.com/biz/the-fat-bear-london?adjust_creative=xRkF2ozLJzv0Tl0J-wOpZQ&utm_campaign=yelp_api_v3&utm_medium=api_v3_business_search&utm_source=xRkF2ozLJzv0Tl0J-wOpZQ"
    )
    place2 = Place(
        yelp_id="7Pc6VXiWEqc4JbgrH4U3tA",
        name="Rocca",
        place_url=
        "https://www.yelp.com/biz/rocca-london?adjust_creative=xRkF2ozLJzv0Tl0J-wOpZQ&utm_campaign=yelp_api_v3&utm_medium=api_v3_business_search&utm_source=xRkF2ozLJzv0Tl0J-wOpZQ"
    )
    place3 = Place(
        yelp_id="K_dDxWgagylIvuB2oQy1KQ",
        name="The Black Penny",
        place_url=
        "https://www.yelp.com/biz/the-black-penny-london?adjust_creative=xRkF2ozLJzv0Tl0J-wOpZQ&utm_campaign=yelp_api_v3&utm_medium=api_v3_business_search&utm_source=xRkF2ozLJzv0Tl0J-wOpZQ"
    )
    place4 = Place(
        yelp_id="0B-ag3J18TatG9H9EQohGg",
        name="Hawksmoor Seven Dials",
        place_url=
        "https://www.yelp.com/biz/hawksmoor-seven-dials-london-4?adjust_creative=xRkF2ozLJzv0Tl0J-wOpZQ&utm_campaign=yelp_api_v3&utm_medium=api_v3_business_search&utm_source=xRkF2ozLJzv0Tl0J-wOpZQ"
    )
    place5 = Place(
        yelp_id="BjPq77aiaKZAVUHIu2S3gA",
        name="The English Rose Cafe and Tea Shop",
        place_url=
        "https://www.yelp.com/biz/the-english-rose-cafe-and-tea-shop-london?adjust_creative=xRkF2ozLJzv0Tl0J-wOpZQ&utm_campaign=yelp_api_v3&utm_medium=api_v3_business_search&utm_source=xRkF2ozLJzv0Tl0J-wOpZQ"
    )
    place6 = Place(
        yelp_id="5sEiM_Xw5jXbMhloNqSgYQ",
        name="Grumbles",
        place_url=
        "https://www.yelp.com/biz/grumbles-london?adjust_creative=xRkF2ozLJzv0Tl0J-wOpZQ&utm_campaign=yelp_api_v3&utm_medium=api_v3_business_search&utm_source=xRkF2ozLJzv0Tl0J-wOpZQ"
    )
    place7 = Place(
        yelp_id="cgkDnzaQvP9q-JHXd-ECcA",
        name="Cambridge Street Kitchen",
        place_url=
        "https://www.yelp.com/biz/cambridge-street-kitchen-london?adjust_creative=xRkF2ozLJzv0Tl0J-wOpZQ&utm_campaign=yelp_api_v3&utm_medium=api_v3_business_search&utm_source=xRkF2ozLJzv0Tl0J-wOpZQ"
    )
    place8 = Place(
        yelp_id="-ylzTrYtRJUJa2BuAInoyQ",
        name="Friends of Ours",
        place_url=
        "https://www.yelp.com/biz/friends-of-ours-london?adjust_creative=xRkF2ozLJzv0Tl0J-wOpZQ&utm_campaign=yelp_api_v3&utm_medium=api_v3_business_search&utm_source=xRkF2ozLJzv0Tl0J-wOpZQ"
    )
    trip1 = Trip(user_id=1,
                 city_id=2,
                 arrival_date=datetime.strptime('2018-03-07 12:00:00', f),
                 departure_date=datetime.strptime('2018-03-13 23:00:00', f))
    trip2 = Trip(user_id=2,
                 city_id=1,
                 arrival_date=datetime.strptime('2018-04-10 10:00:00', f),
                 departure_date=datetime.strptime('2018-04-15 15:00:00', f))
    trip3 = Trip(user_id=1,
                 city_id=3,
                 arrival_date=datetime.strptime('2018-04-19 14:00:00', f),
                 departure_date=datetime.strptime('2018-04-22 12:00:00', f))
    saved_place1 = SavedPlace(place=place1,
                              trip=trip1,
                              meal_datetime=datetime.strptime(
                                  '2018-03-07 00:00:00', f),
                              meal_label="lunch")
    saved_place2 = SavedPlace(place=place2,
                              trip=trip1,
                              meal_datetime=datetime.strptime(
                                  '2018-03-07 00:00:00', f),
                              meal_label="dinner")
    saved_place3 = SavedPlace(place=place3,
                              trip=trip1,
                              meal_datetime=datetime.strptime(
                                  '2018-03-08 00:00:00', f),
                              meal_label="lunch")
    saved_place4 = SavedPlace(place=place4,
                              trip=trip1,
                              meal_datetime=datetime.strptime(
                                  '2018-03-09 00:00:00', f),
                              meal_label="breakfast")
    saved_place5 = SavedPlace(place=place5,
                              trip=trip2,
                              meal_datetime=datetime.strptime(
                                  '2018-04-12 00:00:00', f),
                              meal_label="breakfast")
    saved_place6 = SavedPlace(place=place6,
                              trip=trip2,
                              meal_datetime=datetime.strptime(
                                  '2018-04-13 00:00:00', f),
                              meal_label="lunch")
    saved_place7 = SavedPlace(place=place7,
                              trip=trip3,
                              meal_datetime=datetime.strptime(
                                  '2018-04-20 00:00:00', f),
                              meal_label="dinner")
    saved_place8 = SavedPlace(place=place8,
                              trip=trip3,
                              meal_datetime=datetime.strptime(
                                  '2018-04-21 00:00:00', f),
                              meal_label="lunch")

    db.session.add_all([
        place1, place2, place3, place4, place5, place6, place7, place8, trip1,
        trip2, trip3, saved_place1, saved_place2, saved_place3, saved_place4,
        saved_place5, saved_place6, saved_place7, saved_place8
    ])
    db.session.commit()
示例#25
0
def get_my_places():
    ''' get the id and name of the current users Places '''
    return [(place.key.urlsafe(), place.name) for place in Place.query(ancestor=_get_my_profile().key).order(Place.name_order).fetch()]
示例#26
0
def add_to_folder():

    username = session['logged_in_user']
    print username
    folderName = request.form.get("folder_name")
    business_id = request.form.get("business_id")
    existing_place = Place.query.filter_by(business_id=business_id).first()

    business = sample_query.yelp_api.business_query(id=business_id)
    if business['location']['address']:
        address = business['location']['address'][0]
    else:
        address = ""
    if business['categories'][0]:
        category_description, category = business['categories'][0]
    else:
        category = ""

    if business['name']:
        name = business['name']
    else:
        name = ""

    if business['location']['coordinate']['latitude']:
        latitude = business['location']['coordinate']['latitude']
    else:
        latitude = None

    if business['location']['coordinate']['longitude']:
        longitude = business['location']['coordinate']['longitude']
    else:
        longitude = None

    if business['location']['city']:
        city = business['location']['city']
    else:
        city = ""

    if business['location']['country_code']:
        country = business['location']['country_code']
    else:
        country = ""

    print session['user_id']
    print folderName
    if not existing_place:

        new_place = Place(business_id=business_id,
                          category=category,
                          name=name,
                          address=address,
                          latitude=latitude,
                          longitude=longitude,
                          city=city,
                          country=country)

        db.session.add(new_place)
        db.session.commit()
        place_id = new_place.place_id
    else:
        place_id = existing_place.place_id

    folder = Folder.query.filter_by(user_id=session['user_id'],
                                    folder_name=folderName).first()
    print folder
    folder_id = folder.folder_id
    print folder_id, place_id
    new_place_folder = Place_folder(place_id=place_id, folder_id=folder_id)
    db.session.add(new_place_folder)
    db.session.commit()

    return redirect("/results")
示例#27
0
文件: seed.py 项目: jtrieu2/PressPaws

if __name__ == "__main__":
    connect_to_db(app)
    db.create_all()

    excel_file = 'avatars.xlsx'
    load_avatars(excel_file)

    user = User(user_id=1,
                fname='Jenny',
                lname='Trieu',
                email='*****@*****.**',
                password="******",
                url=default_url)
    place = Place(user_id=1,
                  place_name='WinterWonderland',
                  place_address='100 Main St, San Francisco, CA 94110',
                  place_imURL=default_url)
    event = Event(user_id=1,
                  event_name='Doggy Dayzz',
                  eventbrite_id='1234asdf',
                  event_address='200 Main St, San Francisco, CA 94110',
                  event_date='January 1, 2019',
                  event_imURL=default_url)
    db.session.add(user)
    db.session.add(place)
    db.session.add(event)
    db.session.commit()
    set_val_user_id()
示例#28
0
 def load(self, csv_cache):
     with self._cache_lock:
         for line in read_csv(csv_cache):
             self.cache[line[0]] = Place.from_csv_row(line)
示例#29
0
def add_place(name, country, city, street):
    """Add a store to the DB."""
    place = Place(name=name, country=country, city=city, street=street)
    session.add(place)
    session.commit()