def add_favorites(username, park_code): """Add park to favorites""" if "username" not in session: return redirect("/login") user = User.query.filter_by(username=username).first() favorited_park = Park.query.filter_by(park_code=park_code).one_or_none() main_image_url = request.form['main_image_url'] full_name = request.form['full_name'] # if park already in the DB if favorited_park: user.parks.append(favorited_park) db.session.commit() flash("Park has been added to favorites") return redirect("/<username>/favorite-parks") # if the park is not already in the DB else: park = Park(park_code=park_code, main_image_url=main_image_url, full_name=full_name) user.parks.append(park) db.session.commit() flash("Favorite park has been added") return redirect("/<username>/favorite-parks")
def create_parking_object(parking_dataset_data): """ this method create new object of Park class base on mongodb :param parking_dataset_data: get parking_DATA dataset and write some attrs for new parking object :return: created object of Park class base on mongodb dataset information. """ # create sample object of Park class parking = Park(parking_dataset_data['parking_name'], parking_dataset_data['parking_address'], parking_dataset_data['parking_capacity'], parking_dataset_data['price_per_minute']) parking.park_place = parking_dataset_data['park_place'] return parking
def testPark_1(self): park = Park("pppp", "name!", "desc", "hello", "directionsInfo", "directionsUrl", "111,444", "https://www.facebook.com", "It's raining", "Campground 10", "TX, WA", "http://www.piazza.com") database.session.add(park) park = Park.query.first() self.assertTrue(park.fullName == "name!") self.assertTrue(park.weatherInfo == "It's raining")
def register_parking_information(): """ a method for giving parking info such as: parking name, parking address, parking capacity and parking price per minutes. :return: if register totally complete done return parking_data_as_bson_format, if not return to this menu again. """ # try to get parking information from user try: print('*' * 60) parking_name = input('* Please Enter Your Parking Name: ').strip() parking_address = input('* Please Enter Your Parking Address: ').strip() parking_capacity = int(input('* Please Enter Your Parking Capacity: ')) parking_price = int(input('* Please Enter Your Parking Price/Min: ')) print('*' * 60) # if some error occur except ValueError: print('!' * 60) print('! You should a integer number for parking capacity and parking price/min') print('!' * 60) # return user to register a gain. return register_parking_information() # user's data enter. register_parking_data = f'Parking Name: {parking_name} \n' \ f'Parking Address: {parking_address} \n' \ f'Parking Capacity: {parking_capacity} \n' \ f'Parking Price: {parking_price} \n' # assurance about parking information if are_you_confirm_these_data(register_parking_data, 'Parking info'): # user sure about do these works. # create this Parking object temp_parking = Park(parking_name, parking_address, parking_capacity, parking_price) # convert an object to the json. parking_data_as_json_format = json.dumps(temp_parking.__dict__) # convert above json to the bson for sending data to mongodb parking_data_as_bson_format = loads(parking_data_as_json_format) return parking_data_as_bson_format # if user doesn't sure do this. return register_parking_information()
def handle_park_heartbeat(srv, item, park_id, is_online=None, last_heartbeat_time=None): _srv = srv try: with _srv.database: if is_online is None: query = Park.update( last_heartbeat_time=last_heartbeat_time).where( Park.id == park_id) else: query = Park.update(is_online=is_online).where( Park.id == park_id) query.execute() except Exception, e: message = "[PARK_HEARTBEAT] park [%s] catch exception [%s]" % (park_id, str(e)) do_log(srv, item, "ERROR", LOG_T_DB, message) # loggine me return False
def test_user_model(self): """Does basic model work?""" u = User.signup("yetanothertest", "password") uid = 888 u.id = uid p = Park(park_code="yose", full_name="Yosemite National Park") db.session.add_all([u, p]) db.session.commit() u.parks.append(p) db.session.commit() # User should have one favorite park self.assertEqual(len(u.parks), 1)
def search_parks(location_name): park_list = [] query_result = google_places.nearby_search( location=location_name, radius=50000, types=[types.TYPE_AMUSEMENT_PARK]) for place in query_result.places: place.get_details() lon = place.geo_location['lng'] lat = place.geo_location['lat'] # only go further if the place has > 0 images if len(place.photos) < 1: continue photo = place.photos[0] photo.get(maxheight=500, maxwidth=500) # values we do not allow to be N/A if place.international_phone_number == None or place.website == None or place.formatted_address == None: continue park_name = place.name.encode("UTF8") park_phone_number = place.international_phone_number.encode("UTF8") website = place.website.encode("UTF8") address = place.formatted_address.encode("UTF8") park = Park(name=park_name, address=address, longitude=str(lon), latitude=str(lat), phone_number=park_phone_number, review_data=str(place.rating), image_uri=str(photo.url), website=website) park_list.append(park) # thread sleep to avoid rate limits time.sleep(1) return park_list
def handle_park(srv, item, park_id, spaces, total_remaining_spaces, vip_remaining_spaces=0, visitor_remaining_spaces=0): _srv = srv try: with _srv.database: query = Park.update( spaces=spaces, total_remaining_spaces=total_remaining_spaces, vip_remaining_spaces=vip_remaining_spaces, visitor_remaining_spaces=visitor_remaining_spaces).where( Park.id == park_id) query.execute() except Exception, e: message = "[PARK_SPACE] park [%s] catch exception [%s]" % (park_id, str(e)) do_log(srv, item, "ERROR", LOG_T_DB, message) return False
def national_scrape(): for string in national_parks: park_name = string string = string.replace(" ", "+") string = string.replace("-", "+") firsturl = base_url + string + end_url firstjson = requests.get(firsturl).json() if firstjson["status"] == "OK": print(len(firstjson["results"])) state_dict = firstjson["results"][0] #get place id and use place details api if len(state_dict) != 0: placeid = state_dict["place_id"] secondurl = base_url2 + placeid + end_url2 secondjson = requests.get(secondurl).json() if secondjson["status"] != "OK": print("well shit") assert(False) result = secondjson["result"] state = "" for add in result["address_components"]: if add["types"] == ["postal_code"]: zipcode = add["short_name"] if add["short_name"] in states: state = add["long_name"] #zipcodeset.add(zipcode) print(state) address = result["formatted_address"] try: phone = result["formatted_phone_number"] except KeyError: phone = "(555) 555-5555" if "rating" in result: rate = result["rating"] else: raters = 0 rate = 0.0 try: length = len(result["reviews"]) except KeyError: length = 0 if length != 0: for user in result["reviews"]: rate += int(user["rating"]) raters += 1 rate = rate/raters else: rate = 3.0 photo_link = photo_url zipregion = zipcode[0:3] try: website = result["website"] except KeyError: website = "http://www.sweetoutdoors.me/" try: photo_stuff = result["photos"][0] photo_link = photo_link + photo_stuff["photo_reference"] photo_link = photo_link + "&maxheight=" + str(photo_stuff["height"]) photo_link = photo_link + "&maxwidth=" + str(photo_stuff["width"]) + photo_end except KeyError: photo_link = default_photo_url latitude = str(result["geometry"]["location"]["lat"]) longitude = str(result["geometry"]["location"]["lng"]) #convert to STRING LATLONG park_obj = Park(park_name, latitude, longitude, address, phone, rate, website, zipcode, photo_link, zipregion, state) db.session.add(park_obj) if state_dict != {}: print("done for %s" %park_name) state_dict = {} else: #NO RESULTS print(firstjson["status"]) db.session.commit() db.session.close()
def state_scrape(begin, end): d = {} num = 0 for letter in az: d[letter] = num num += 1 state_dict = {} #2372 #4616 #NOT ALL STATE PARKS ARE IN GOOGLE MAPS for i in range(begin, end): state = states[i] url = "http://www.stateparks.com/" + state + ".html" response = requests.get(url) soup = BeautifulSoup(response.content, "html.parser") flag = True for parkdiv in soup.find_all(id="parklink"): string = parkdiv.get_text() if flag: currentletter = d[string[0].lower()] flag = False if currentletter <= d[string[0].lower()]: currentletter = d[string[0].lower()] park_name = string string = string.replace(" ", "+") string = string.replace("-", "+") firsturl = base_url + string + end_url firstjson = requests.get(firsturl).json() if firstjson["status"] == "OK": for dic in firstjson["results"]: if state in dic["formatted_address"]: #gets all the address w/ correct state state_dict = dic break #get place id and use place details api if len(state_dict) != 0: placeid = state_dict["place_id"] secondurl = base_url2 + placeid + end_url2 secondjson = requests.get(secondurl).json() if secondjson["status"] != "OK": print("well shit") assert(False) result = secondjson["result"] for add in result["address_components"]: if add["types"] == ["postal_code"]: zipcode = add["short_name"] zipregion = zipcode[0:3] address = result["formatted_address"] try: phone = result["formatted_phone_number"] except KeyError: phone = "(555) 555-5555" if "rating" in result: rate = result["rating"] else: raters = 0 rate = 0.0 try: length = len(result["reviews"]) except KeyError: length = 0 if length != 0: for user in result["reviews"]: rate += int(user["rating"]) raters += 1 rate = rate/raters else: rate = 3.0 photo_link = photo_url try: website = result["website"] except KeyError: website = "http://www.sweetoutdoors.me/" try: photo_stuff = result["photos"][0] photo_link = photo_link + photo_stuff["photo_reference"] photo_link = photo_link + "&maxheight=" + str(photo_stuff["height"]) photo_link = photo_link + "&maxwidth=" + str(photo_stuff["width"]) + photo_end except KeyError: photo_link = default_photo_url latitude = str(result["geometry"]["location"]["lat"]) longitude = str(result["geometry"]["location"]["lng"]) park_obj = Park(park_name, latitude, longitude, address, phone, rate, website, zipcode, photo_link, zipregion, statestran[state]) db.session.add(park_obj) if state_dict != {}: print("done for %s" % park_name) state_dict = {} else: #NO RESULTS print(firstjson["status"]) else: break db.session.commit() db.session.close()
# if park exists, create a new rel; if not we must add it to the db # this code is like in discussion section- need break here to continue if park_is_true: rel_exists = session.query(StateParkAssociation).filter( StateParkAssociation.Park_Id == park_is_true[0].Id, StateParkAssociation.State_Id == id).all() if rel_exists: break else: new_rel = StateParkAssociation(State_Id=id, Park_Id=park_is_true[0].Id) session.add(new_rel) session.commit() else: new_park = Park(Name=tag.h3.text, Type=tag.h2.text, Descr=tag.p.text.strip('\n'), Location=tag.h4.text) session.add(new_park) session.commit() new_rel = StateParkAssociation(State_Id=id, Park_Id=new_park.Id) session.add(new_rel) session.commit() # write the data to a csv file.... make db with open('nps_parks.csv', 'w') as parks_file: parkwriter = csv.writer(parks_file) parkwriter.writerow([ 'Park Name', 'Park Type', 'Park Location Description', 'Park Description', 'Park States' ]) parks = session.query(Park).all()
def handle_entry(srv, item, parking_info): _srv = srv notified = True try: with _srv.database: try: park = (Park.select(Park, Pmc).join(Pmc).where( Park.id == parking_info.park_id)).get() except Park.DoesNotExist: message = "[ENTRY] park [%s] does not exist" % parking_info.park_id do_log(srv, item, "WARN", LOG_T_LOCAL, message) return True defaults = dict(park=park, pmc=park.pmc, parking_id=parking_info.parking_id, entry_time=parking_info.entry_time, entry_code=parking_info.entry_code, card_type=parking_info.card_type) current_parking, created = CurrentParking.get_or_create( car_no=parking_info.car_no, defaults=defaults) parking = str(current_parking.id) if created: history_parking = HistoryParking.create( pmc=park.pmc, park=park, parking=parking, car_no=parking_info.car_no, entry_time=parking_info.entry_time, entry_code=parking_info.entry_code, card_type=parking_info.card_type) else: if parking_info.entry_time > current_parking.entry_time: current_parking.pmc = park.pmc current_parking.park = park current_parking.parking_id = parking_info.parking_id current_parking.entry_time = parking_info.entry_time current_parking.entry_code = parking_info.entry_code current_parking.card_type = parking_info.card_type current_parking.save() query = HistoryParking.update( pmc=park.pmc, park=park, card_type=parking_info.card_type, entry_code=parking_info.entry_code, entry_time=parking_info.entry_time).where( (HistoryParking.parking == parking) & (HistoryParking.car_no == parking_info.car_no)) query.execute() query = Booking.update( parking=parking, reality_start=parking_info.entry_time, parking_state='parking').where( (Booking.park == parking_info.park_id) & (Booking.car_no == parking_info.car_no) & (Booking.apply_state == 'pass') & ~(Booking.parking_state << ['leaved'])) query.execute() except Exception, e: message = "[ENTRY] park [%s] car [%s] catch excetion [%s]" % ( parking_info.park_id, parking_info.car_no, str(e)) do_log(srv, item, "ERROR", LOG_T_DB, message) notified = False