Beispiel #1
0
    def parse_restaurant(result_soup):
        restaurant = Restaurant()

        # name
        name_soup = result_soup.find('a', class_='name')
        if name_soup is not None:
            restaurant.name = name_soup.text.strip()

        # address
        address1_soup = result_soup.find('strong')
        if address1_soup is not None:
            address_match = re.search('(.*) (\d{5})', address1_soup.text.strip())
            if address_match:
                restaurant.address = address_match.group(1)
                restaurant.postcode = address_match.group(2)
        address2_soup = result_soup.find('span', class_='address')
        if address2_soup is not None:
            restaurant.address += ' ' + address2_soup.text.strip()

        # cuisines
        cuisine_soup = result_soup.find('span', class_='tipo-label')
        if cuisine_soup is not None:
            restaurant.cuisines = [cuisine_soup.text.strip()]

        return restaurant
Beispiel #2
0
def process_restaurant_registration():
    """Process restaurant registration."""

    name = request.form.get("name")
    email = request.form.get("email")
    password = request.form.get("password")
    street_address = request.form.get("street-address")
    city = request.form.get("city")
    state = request.form.get("state")
    zipcode = request.form.get("zipcode")

    if Restaurant.query.filter_by(email=email).first():
        flash("An account with this email already exists.")
        return redirect("/register")

    new_restaurant = Restaurant(name=name,
                                email=email,
                                street_address=street_address,
                                city=city,
                                state=state,
                                zipcode=zipcode)

    new_restaurant.set_password(password)

    db.session.add(new_restaurant)
    db.session.commit()

    restaurant_id = new_restaurant.id

    # Log in new restaurant.
    session["restaurant_id"] = restaurant_id

    flash(f"Successfully registered {name}.")
    return redirect(f"/restaurant-dashboard/{restaurant_id}")
Beispiel #3
0
def load_restaurants():
    """Load restaurants from restaurants.txt into database."""

    print("Restaurants")

    # Read restaurants.txt file and insert data
    for row in open("seed_data/restaurants.txt"):
        row = row.rstrip()
        id, name, street_address, city, state, zipcode, email, password = row.split(
            "|")

        restaurant = Restaurant(id=id,
                                name=name,
                                street_address=street_address,
                                city=city,
                                state=state,
                                zipcode=zipcode,
                                email=email)

        restaurant.set_password(password)

        # We need to add to the session or it won't ever be stored
        db.session.add(restaurant)

    # Once we're done, we should commit our work
    db.session.commit()
Beispiel #4
0
    def _parse_restaurant(self, restaurant_soup):
        restaurant = Restaurant()

        # ranking
        ranking_soup = restaurant_soup.find('span', class_='indexed-biz-name')
        if ranking_soup:
            ranking_match = re.search('(\d+)\.', ranking_soup.text)
            if ranking_match:
                restaurant.ranking = ranking_match.group(1)

        # name & link
        link_soup = restaurant_soup.find('a', class_='biz-name')
        if link_soup:
            restaurant.url = self.base_url + link_soup['href']
            restaurant_name_soup = link_soup.find('span')
            if restaurant_name_soup:
                restaurant.name = restaurant_name_soup.text

        # reviews
        reviews_soup = restaurant_soup.find('span', class_='review-count')
        if reviews_soup:
            reviews_match = re.search('(\d+)', reviews_soup.text)
            if reviews_match:
                restaurant.review_count = reviews_match.group(1)

        # rating
        rating_soup = restaurant_soup.find('i', class_='star-img')
        if rating_soup:
            rating_match = re.search('(\d(\.\d)?)', rating_soup['title'])
            if rating_match:
                restaurant.rating = rating_match.group(1)

        # cuisines
        cuisines_soup = restaurant_soup.find('span', 'category-str-list')
        if cuisines_soup:
            cuisine_soup_list = cuisines_soup.find_all('a')
            restaurant.cuisines = []
            for cuisine_soup in cuisine_soup_list:
                restaurant.cuisines.append(cuisine_soup.text)

        # address
        address_soup = restaurant_soup.find('address')
        if address_soup:
            address_match = re.search('(.*)(\d{5})([\s\S]*)', address_soup.text.strip())
            if address_match:
                restaurant.address = '%s, %s' % (address_match.group(1), address_match.group(3))
                restaurant.postcode = address_match.group(2)

        # price
        price_soup = restaurant_soup.find('span', class_='price-range')
        if price_soup:
            restaurant.price = price_soup.text

        return restaurant
Beispiel #5
0
def load_restaurants():
    """Load restaurants into database from restaurant.txt file"""

    print "Loading Restaurants"

    #Delete all rows in table to reseed data every time this function is called
    Restaurant.query.delete()

    #Read the source file and insert data, use 'rU' so \r is read as line break
    for line in open('seed/restaurants.csv', 'rU'):
        line = line.rstrip()
        name, opentable_id, eater, yelp, timeout, zagat, michelin, infatuation, lat, lng = line.split(
            ',')
        if opentable_id == 'None':
            opentable_id = None

        #create restaurant object based on inputs from the line
        restaurant = Restaurant(name=name,
                                opentable_id=opentable_id,
                                eater=eater,
                                yelp=yelp,
                                timeout=timeout,
                                zagat=zagat,
                                michelin=michelin,
                                infatuation=infatuation,
                                lat=lat,
                                lng=lng)

        #add restaurant to the database
        db.session.add(restaurant)

    #commit work
    db.session.commit()
Beispiel #6
0
def create_restaurant(latitude,
                      longitude,
                      name,
                      price=None,
                      location=None,
                      phone=None,
                      image=None,
                      yelp_id=None):
    """Create and return a new restaurant."""

    restaurant = Restaurant.query.filter(
        (Restaurant.yelp_id == yelp_id)).first()

    if restaurant is not None:
        return restaurant
    else:
        restaurant = Restaurant(latitude=latitude,
                                longitude=longitude,
                                name=name,
                                price=price,
                                location=location,
                                phone=phone,
                                image=image,
                                yelp_id=yelp_id)
        db.session.add(restaurant)
        db.session.commit()

    return restaurant
Beispiel #7
0
def saving_restaurant_results():
    """save a specific restaurant to the database"""

    r_name = request.form.get('name')
    r_location = request.form.get('address')
    r_rating = request.form.get('rating')
    r_price = request.form.get('price')
    nightout_id = request.form.get('nightoutId')

    new_restaurant = Restaurant.query.filter_by(r_name=r_name,
                                                r_location=r_location).first()

    if not new_restaurant:
        new_restaurant = Restaurant(r_name=r_name,
                                    r_rating=r_rating,
                                    r_location=r_location,
                                    r_price=r_price)

        db.session.add(new_restaurant)
        db.session.commit()

    nightout = NightOut.query.get(nightout_id)

    #could also put nightout.res_id = new_restaurant.res_id
    nightout.restaurant = new_restaurant

    db.session.commit()

    return jsonify({"sucess": True})
def load_restaurants(city):
    """Get all restaurants for a city from Yelp and load restaurants into database."""

    # Get city id, as city id is a required parameter when adding a restaurant to the database
    city_id = get_city_id(city)

    # Start offset at 0 to return the first 20 results from Yelp API request
    offset = 0

    # Get total number of restaurants for this city
    total_results = get_restaurants(city, offset).total

    # Get all restaurants for a city and load each restaurant into the database
    # Note: Yelp has a limitation of 1000 for accessible results, so get total results
    # if less than 1000 or get only 1000 results back even if there should be more
    while 1000 > offset < total_results:

        # API response returns a SearchResponse object with accessible attributes
        # response.businesses returns a list of business objects with further attributes
        for business in get_restaurants(city, offset).businesses:
            restaurant = Restaurant(
                city_id=city_id,
                name=business.name,
                address=" ".join(business.location.display_address),
                phone=business.display_phone,
                image_url=business.image_url,
                latitude=business.location.coordinate.latitude,
                longitude=business.location.coordinate.longitude)
            db.session.add(restaurant)

        # Yelp returns only 20 results each time, so need to offset by 20 while iterating
        offset += 20

    db.session.commit()
Beispiel #9
0
def get_fake_restaurants():
    """Create 2 fake restaurants to check if those restaurants are not in Yelp"""

    fake_rest1 = Restaurant(yelp_restaurant_id='111111aaaaaa',
                            name='Rest fake 1',
                            address='nowhere',
                            zipcode='94118',
                            rating=4)
    fake_rest2 = Restaurant(yelp_restaurant_id='222222bbbbbb',
                            name='Rest fake 2',
                            address='far away',
                            zipcode='94118',
                            rating=5)

    db.session.add_all([fake_rest1, fake_rest2])

    db.session.commit()
Beispiel #10
0
def create_restaurant(yelp_id):
    """Create and return a new restaurant."""

    res = Restaurant(yelp_id=yelp_id)

    db.session.add(res)
    db.session.commit()

    return res
Beispiel #11
0
def sample_restaurant():
    """ Add sample restaurant to DB """

    print "Sample Restaurant"

    restaurant = Restaurant(yelp_biz_id='wGl_DyNxSv8KUtYgiuLhmA',
                            name='Bi-Rite Creamery')

    db.session.add(restaurant)
    db.session.commit()
def restaurant():
    restaurant = Restaurant(latitude=45,
                            longitude=-122,
                            name='New Restaurant',
                            price=4,
                            location='Test, Vancouver, WA',
                            phone='1234567890',
                            image='rest.jpg',
                            yelp_id='1234')

    return restaurant
Beispiel #13
0
def newRestaurant():
    if 'username' not in login_session:
        return redirect('/login')
    if request.method == 'POST':
        newRestaurant = Restaurant(name=request.form['name'],
                                   user_id=login_session['user_id'])
        session.add(newRestaurant)
        flash('New Restaurant %s Successfully Created' % newRestaurant.name)
        session.commit()
        return redirect(url_for('showRestaurants'))
    else:
        return render_template('newRestaurant.html')
    def __parse_single_restaurant(li):
        """
        下記の形式のHTMLをParseする。

        <li>
          <a href='****' title='****の待ち時間'>
            <ul>
              <li class='photo'><img data-src='****' width='64' height='64' class='lozad' alt='***'></li>
              <li class='desc'>
                <h4>レストラン名称</h4>
                <p>運営ステータス<br> <span class='runtime'>11:00-17:45</span></p>
              </li>
            </ul>
          </a>
        </li>
        """
        restaurant = Restaurant()
        if elem_desc := li.find(class_='desc'):
            # レストラン名称
            restaurant.name = elem_desc.find('h4').text
            for child in elem_desc.children:
                if not child:
                    continue
                if not child.text:
                    continue
                # 中止フラグ
                if "中止" in child.text:
                    restaurant.disable_flag = True
                # ステータス・営業時間
                if "-" in child.text and ":" in child.text:
                    splited_result = child.text.split(" ")
                    if len(splited_result) == 2:
                        restaurant.status, start_end_time = child.text.split(
                            " ")
                        restaurant.start_time, restaurant.end_time = start_end_time.split(
                            "-")
                else:
                    restaurant.status = child.text.strip()
            # リアルタイム待ち時間
            if elem_time := li.find(class_='time'):
                wait_time_str = elem_time.find('p').text.strip('待ち時間').strip(
                    "分")
                # 時間に幅がある場合は最も大きい値をとる
                if "-" in wait_time_str:
                    wait_time_min, wait_time_max = wait_time_str.split("-")
                    wait_time_str = wait_time_max if wait_time_max != "" else wait_time_min
                if wait_time_str.strip() != "":
                    restaurant.wait_time = int(wait_time_str)
Beispiel #15
0
def create_restaurant(id, name, cuisine, address, longitude, latitude,
                      image_url):
    """Create and return a new restaurant."""

    r = Restaurant(id=id,
                   name=name,
                   cuisine=cuisine,
                   address=address,
                   longitude=longitude,
                   latitude=latitude,
                   image_url=image_url)

    db.session.add(r)
    db.session.commit()

    return r
def load_test_data():
    t_user = User(username='******',
                  email='*****@*****.**',
                  password='******')
    db.session.add(t_user)

    t_trail = Trail(latitude=45,
                    longitude=-122,
                    name='New Trail',
                    length=30,
                    location='Vancouver, WA',
                    image='trail.jpg',
                    hiking_id='1234')
    db.session.add(t_trail)

    t_restaurant = Restaurant(latitude=45,
                              longitude=-122,
                              name='New Restaurant',
                              price=4,
                              location='Test, Vancouver, WA',
                              phone='1234567890',
                              image='rest.jpg',
                              yelp_id='1234')
    db.session.add(t_restaurant)

    t_walk = Walk(user=t_user, walk_date=datetime.datetime(2020, 5, 17))
    db.session.add(t_walk)

    t_rest_rating = RestRating(restaurant=t_restaurant,
                               user=t_user,
                               rest_comment='Wow, what a restaurant.',
                               rest_star=5,
                               masks_worn=True,
                               socially_distanced=True,
                               outdoor_seating=True)
    db.session.add(t_rest_rating)

    t_trail_rating = TrailRating(trail=t_trail,
                                 user=t_user,
                                 trail_comment='Wow, what a trail.',
                                 trail_star=5,
                                 difficulty_level=3,
                                 crowded=False)
    db.session.add(t_trail_rating)

    db.session.commit()
Beispiel #17
0
def get_restaurant_id(yelp_id, rest_name):
    """ Finds restaurant_id for restaurants, adds restaurant if not yet in table """

    existing_restaurant = Restaurant.query.filter(Restaurant.yelp_biz_id == yelp_id).all()

    if len(existing_restaurant) == 1:
        print "Existing"
        restaurant_id = existing_restaurant[0].restaurant_id
        return restaurant_id

    elif len(existing_restaurant) == 0:
        print "New"
        restaurant = Restaurant(yelp_biz_id=yelp_id, name=rest_name)
        db.session.add(restaurant)
        db.session.commit()

        return get_restaurant_id(yelp_id, rest_name)
Beispiel #18
0
def add_rest_to_db():
    """Add all restaurants and info to the database."""

    for restaurant in restaurants:
        info = restaurants[restaurant]
        address = ', '.join(info['address'])

        category = Restaurant(rest_id=info['rest_id'],
                              rest_title=info['rest_title'],
                              rest_alias=info['rest_alias'],
                              rating=info['rating'],
                              num_reviews=info['num_reviews'],
                              address=address,
                              phone=info['phone'])

        db.session.add(category)
    db.session.commit()
Beispiel #19
0
def load_restaurants():
    """Load restaurants from seed_restaurants into database."""

    print "Restaurants"

    Restaurant.query.delete()

    for row in open("seed/seed_restaurants.txt"):

        row = row.rstrip()
        restaurant_id, name, address, delivery_fee = row.split("|")

        restaurant = Restaurant(restaurant_id=restaurant_id,
                                name=name,
                                address=address,
                                delivery_fee=delivery_fee)

        db.session.add(restaurant)

    db.session.commit()
def create_restaurants_list_from_restaurant_json(restaurants):
    """Create restaurants list from YELP restaurants.

    restaurants(json)

    return list of restaurants
    """

    restaurants_list = []

    for restaurant in restaurants['businesses']:

        new_restaurant = Restaurant(yelp_restaurant_id=restaurant['id'],
                                    name=restaurant['name'].lower(),
                                    address=restaurant['location']['address1'],
                                    zipcode=restaurant['location']['zip_code'],
                                    rating=restaurant['rating'])

        restaurants_list.append(new_restaurant)

    return restaurants_list
Beispiel #21
0
def load_restaurant(file):
    """Load movies from u.item into database."""

    print("Restaurants")

    for row in open(file):
        row = row.rstrip()

        restaurant_name, location, zone, latitude, longitude = row.split(",")

        restaurant = Restaurant(
            restaurant_name = restaurant_name,
            location = location,
            zone = zone,
            latitude =latitude,
            longitude = longitude)

        
        db.session.add(restaurant)

        db.session.commit()
Beispiel #22
0
    def _parse_restaurant(self, restaurant_soup):
        restaurant = Restaurant()

        # name and url
        title_soup = restaurant_soup.find('a', class_='property_title')
        if title_soup is not None:
            restaurant.name = title_soup.text.strip()
            restaurant.url = self.base_url + title_soup['href'].strip()

        # price
        price_soup = restaurant_soup.find('span', class_='price_range')
        if price_soup is not None:
            restaurant.price = price_soup.text.strip()

        # reviews
        reviews_soup = restaurant_soup.find('span', class_='reviewCount')
        restaurant.review_count = 0
        if reviews_soup is not None:
            reviews_match = re.findall('^\d+\.?\d+', reviews_soup.a.text.strip())
            if reviews_match and len(reviews_match) > 0:
                restaurant.review_count = reviews_match[0].replace('.', '')

        # rating
        rating_soup = restaurant_soup.find('img', class_='sprite-ratings')
        if rating_soup is not None:
            rating = rating_soup['alt'].strip()
            restaurant.rating = self._parse_rating(rating)
            restaurant.max_rating = self._parse_max_rating(rating)

        # ranking
        ranking_soup = restaurant_soup.find('div', class_='popIndexDefault')
        if ranking_soup is not None:
            ranking = ranking_soup.text.strip().replace('.', '')
            restaurant.ranking = self._parse_ranking(ranking)
            restaurant.ranking_len = self._parse_ranking_len(ranking)

        # cuisines
        cuisine_soup_list = restaurant_soup.find_all('a', class_='cuisine')
        if cuisine_soup_list is not None:
            restaurant.cuisines = []
            for tag in cuisine_soup_list:
                restaurant.cuisines.append(tag.text.strip())
        return restaurant
Beispiel #23
0
def import_restaurants_from_hardcode_list():
    """Load restaurant info into database model.
    Additional details:
    Importing name, address, phone number from hard coded data/restaurants.txt
    Using phone number, importing restaurant information from Yelp API"""

    hc_yelp_object_list = []

    # Parse through restaurants.txt and clean/unpack data
    for i, row in enumerate(open("data/restaurants.txt")):
        row = row.strip()
        name, address, phone = row.split("|")

        # Reformat phone number from "(XXX) XXX-XXXX" to "+1XXXXXXXXXX"
        yelp_phone = "+1" + phone[1:4] + phone[6:9] + phone[10:]

        # Return response dictionary from Yelp API for given phone number
        # Print how long the API call took
        start_time = time() * 1000
        yelp_dict = yelp_client.phone_search(yelp_phone)
        elapsed_time = (time() * 1000) - start_time
        print "API request %d: %d ms" % (i, elapsed_time)

        # Return single business in response dictionary that matches the
        # name and address from restaurants.txt
        yelp_object = validate_single_business(yelp_dict, name, address)

        # Add yelp_object to hc_yelp_object_list to be used later
        hc_yelp_object_list.append(yelp_object)

        # Get restaurant information for each yelp_object
        yelp_id = yelp_object.id
        city = yelp_object.location.city
        state_code = yelp_object.location.state_code
        country_code = yelp_object.location.country_code
        yelp_url = yelp_object.url
        yelp_img_url = yelp_object.image_url
        yelp_rating = yelp_object.rating
        yelp_rating_img = yelp_object.rating_img_url_small
        yelp_review_count = yelp_object.review_count
        lat = yelp_object.location.coordinate.latitude
        lng = yelp_object.location.coordinate.longitude

        # Instantiate new Restaurant object with unpacked data
        restaurant = Restaurant(name=name,
                                address=address,
                                city=city,
                                state_code=state_code,
                                country_code=country_code,
                                phone=phone,
                                yelp_id=yelp_id,
                                yelp_url=yelp_url,
                                yelp_img_url=yelp_img_url,
                                yelp_rating=yelp_rating,
                                yelp_rating_img=yelp_rating_img,
                                yelp_review_count=yelp_review_count,
                                lat=lat,
                                lng=lng)

        # Add new restaurant to database session (to be stored)
        db.session.add(restaurant)

    # Commit the additions to the database
    db.session.commit()

    return hc_yelp_object_list
Beispiel #24
0
def import_restaurants_from_dataset():
    """Import dog-friendly restaurants from Yelp Challenge Dataset."""

    ds_yelp_object_list = []

    # Parse through Yelp businesses dataset
    for i, b in enumerate(open('data/yelp_academic_dataset_business.json')):
        b = json.loads(b.strip())

        try:
            # Get only restaurant objects with dogs allowed attribute,
            # and get desired values
            if b["attributes"]["Dogs Allowed"] and "Restaurants" in b[
                    "categories"]:
                ds_yelp_id = b["business_id"]
                name = b["name"]
                lat = b["latitude"]
                lng = b["longitude"]

                # Get Yelp response object of businesses with matching coordinates
                start_time = time() * 1000
                yelp_objects = yelp_client.search_by_coordinates(
                    lat, lng).businesses
                elapsed_time = (time() * 1000) - start_time
                print "Row %d: %d ms" % (i, elapsed_time)

                # Get only one restaurant object with matching name,
                # and get desired values
                for y in yelp_objects:
                    try:
                        if name == y.name:
                            address = y.location.address[0]
                            city = y.location.city
                            state_code = y.location.state_code
                            country_code = y.location.country_code
                            phone = "(" + y.phone[:3] + ") " + y.phone[
                                3:6] + "-" + y.phone[6:]
                            yelp_id = y.id
                            yelp_url = y.url
                            yelp_img_url = y.image_url
                            yelp_rating = y.rating
                            yelp_rating_img = y.rating_img_url_small
                            yelp_review_count = y.review_count

                            # Add yelp_object to hc_yelp_object_list to be used later
                            ds_yelp_object_list.append(y)

                            # Instantiate new restaurant object and add to db.
                            restaurant = Restaurant(
                                name=name,
                                address=address,
                                city=city,
                                state_code=state_code,
                                country_code=country_code,
                                phone=phone,
                                yelp_id=yelp_id,
                                ds_yelp_id=ds_yelp_id,
                                yelp_url=yelp_url,
                                yelp_img_url=yelp_img_url,
                                yelp_rating=yelp_rating,
                                yelp_rating_img=yelp_rating_img,
                                yelp_review_count=yelp_review_count,
                                lat=lat,
                                lng=lng)

                            db.session.add(restaurant)
                            db.session.commit()

                    except (
                            sqlalchemy.exc.IntegrityError,  # if not unique
                            sqlalchemy.exc.DataError,  # if null values
                            IndexError
                    ):  # if weird formatting with address/phone
                        db.session.rollback()

        except KeyError:  # if no "Dogs Allowed" attribute
            continue

    return ds_yelp_object_list
Beispiel #25
0
def profile():

    my_form = ProfileForm()

    my_data = Profile()
    my_data.remove_none_values()

    # print("my_form.validate_on_submit()", my_form.validate_on_submit())
    # print(my_form.errors)
    if my_form.validate_on_submit():

        # print("************ FORM SUBMITTED****")
        my_data.first_name = request.form.get('first_name')
        my_data.last_name = request.form.get('last_name')
        my_data.email = request.form.get('email')
        my_data.dob = request.form.get('dob')
        # print("first_name", my_data.first_name)
        # print("last_name", my_data.last_name)

        # process file
        file = request.files.get('file_photo')
        if file:
            orig_filename = secure_filename(file.filename)
            file_extension = os.path.splitext(orig_filename)
            file_extension = str(file_extension[1]).lower()

            new_filename = str(uuid.uuid1()) + file_extension

            # save to upload folder
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], new_filename))
            # print("file saved")

            my_data.file_photo_filename = orig_filename
            my_data.file_photo_code = new_filename

        # ---------------EXCEL/CSV - Load into table
        data_file = request.files.get('excel_file')
        print("data_file", data_file)
        if data_file:
            orig_filename = secure_filename(data_file.filename)
            file_extension = os.path.splitext(orig_filename)
            file_extension = str(file_extension[1]).lower()

            new_filename = str(uuid.uuid1()) + file_extension

            file_full_path = os.path.join(app.config['UPLOAD_FOLDER'],
                                          new_filename)

            # save to upload folder
            data_file.save(file_full_path)
            # print("file_full_path", file_full_path)
            my_data.file_data_filename = orig_filename
            my_data.file_data_code = new_filename

            # load the data in the table using pandas
            df = pd.read_csv(file_full_path)
            rest_list_raw = df.to_dict('records')
            rest_list = []
            for rest in rest_list_raw:
                my_rest = Restaurant()
                my_rest.bill = rest['bill']
                my_rest.tip = rest['tip']
                rest_list.append(my_rest)
            db.session.bulk_save_objects(rest_list)
            db.session.commit()

        # save to database
        db.session.add(my_data)
        db.session.commit()
        # print("my_data", my_data.id)

        # redirect to display page
        return redirect('/profile/' + str(my_data.id))  # profile/5

    return render_template('profile.html', my_form=my_form, my_data=my_data)
Beispiel #26
0
def restaurants_create():
    data = request.json
    print(data)
    DB['restaurant'].append(Restaurant("ABC", 5))
    return Response(status=200)
Beispiel #27
0
def load_restaurants():
    """ Load restaurant and bakery data into database. """

    neighborhood_list = Neighborhood.query.all()

    for neighborhood in neighborhood_list:
        # Make a GET request to the API
        payload = {
            'location': neighborhood.neighborhood_name + ' san francisco',
            'categories': 'gluten_free,bakeries'
        }

        # r1 returns <Response 200>
        r1 = requests.get('https://api.yelp.com/v3/businesses/search',
                          headers={'Authorization': 'Bearer %s' % api_key},
                          params=payload)

        # results1.keys() is [u'region', u'total', u'businesses']
        results1 = r1.json()

        bakeries = results1['businesses']

        for bakery in bakeries:
            name = bakery['name']
            addresses = bakery['location'][
                'display_address']  # location key has a dict value
            phone_number = bakery['display_phone']
            picture = bakery['image_url']
            website_url = bakery['url']
            avg_rating = bakery['rating']
            nh = neighborhood.neighborhood_id
            latitude = bakery['coordinates']['latitude']
            longitude = bakery['coordinates']['longitude']
            price = bakery['price']
            transactions = bakery['transactions']
            id_b = bakery['id']

            titles = bakery['categories']

            alias = []
            for title in titles:
                if title['title']:
                    alias.append(title['title'])
            # Convert alias (datatype is list) to a string for correct format to store in db
            types_of_food = ' '.join(alias)

            # Convert addresses (datatype is list) to a string for correct format to store in db
            address = ' '.join(addresses)

            # Second request to API to get hours of operation data
            url = 'https://api.yelp.com/v3/businesses/{}'.format(id_b)
            headers = {'Authorization': 'Bearer %s' % api_key}
            r2 = requests.get(url, headers=headers)
            results2 = r2.json()

            data = results2.get('hours')

            if data:
                dictionary = data[0]
                lst = dictionary.get('open')
                if lst:
                    hours_of_operation = lst
                else:
                    print dictionary.keys()

            bakery_info = Restaurant(name=name,
                                     address=address,
                                     phone_number=phone_number,
                                     picture=picture,
                                     website_url=website_url,
                                     avg_rating=avg_rating,
                                     neighborhood_id=nh,
                                     latitude=latitude,
                                     longitude=longitude,
                                     price=price,
                                     transactions=transactions,
                                     types_of_food=types_of_food,
                                     hours_of_operation=hours_of_operation)

            # Add bakery data to the database.
            db.session.add(bakery_info)

            db.session.flush()
            bakery_info_id = bakery_info.restaurant_id
            gf_type_bakery = Restaurant_type(gf_type_id=3,
                                             restaurant_id=bakery_info_id)

            db.session.add(gf_type_bakery)
    db.session.commit()

    for neighborhood in neighborhood_list:
        # Make a GET request to the API
        payload = {
            'location': neighborhood.neighborhood_name + 'san francisco',
            'categories': 'gluten_free,restaurants'
        }

        # r2 returns <Response 200>
        r3 = requests.get('https://api.yelp.com/v3/businesses/search',
                          headers={'Authorization': 'Bearer %s' % api_key},
                          params=payload)

        # results2.keys() is [u'region', u'total', u'businesses']
        results3 = r3.json()

        restaurants = results3['businesses']

        for restaurant in restaurants:
            name = restaurant['name']
            addresses = restaurant['location'][
                'display_address']  # location key has a dict value
            phone_number = restaurant['display_phone']
            picture = restaurant['image_url']
            website_url = restaurant['url']
            avg_rating = restaurant['rating']
            nh = neighborhood.neighborhood_id
            latitude = restaurant['coordinates']['latitude']
            longitude = restaurant['coordinates']['longitude']
            price = restaurant['price']
            transactions = restaurant['transactions']
            id_r = restaurant['id']

            titles = restaurant['categories']

            alias = []
            for title in titles:
                if title['title']:
                    alias.append(title['title'])
            # Convert alias (datatype is list) to a string for correct format to store in db
            types_of_food = ' '.join(alias)

            # Convert addresses (datatype is list) to a string for correct format to store in db
            address = ' '.join(addresses)

            # Second request to API to get hours of operation data
            url = 'https://api.yelp.com/v3/businesses/{}'.format(id_r)
            headers = {'Authorization': 'Bearer %s' % api_key}
            r2 = requests.get(url, headers=headers)
            results2 = r2.json()

            data = results2.get('hours')

            if data:
                dictionary = data[0]
                lst = dictionary.get('open')
                if lst:
                    hours_of_operation = lst
                else:
                    print dictionary.keys()

            restaurant_info = Restaurant(name=name,
                                         address=address,
                                         phone_number=phone_number,
                                         picture=picture,
                                         website_url=website_url,
                                         avg_rating=avg_rating,
                                         neighborhood_id=nh,
                                         latitude=latitude,
                                         longitude=longitude,
                                         transactions=transactions,
                                         price=price,
                                         types_of_food=types_of_food,
                                         hours_of_operation=hours_of_operation)

            # Add restaurant data to the database.
            db.session.add(restaurant_info)

            db.session.flush()
            restaurant_info_id = restaurant_info.restaurant_id
            gf_type_restaurant = Restaurant_type(
                gf_type_id=2, restaurant_id=restaurant_info_id)

            db.session.add(gf_type_restaurant)
    db.session.commit()
Beispiel #28
0
def Add_Restaurant(name, location, foods):
    restaurant_object = Restaurant(Name=name, Location=location, Foods=foods)
    session.add(restaurant_object)
    session.commit()