def newRestaurant(): ''' { "name" : "Drums", "category" : "Italian", "street" : "254 PLX St.", "city" : "Arlington", "state" : "TX", "zipcode" : 75043 } ''' restaurantName = request.get_json()["name"] categoryName = request.get_json()["category"] street = request.get_json()["street"] city = request.get_json()["city"] state = request.get_json()["state"] zipcode = request.get_json()["zipcode"] try: restaurant_exists = session.query(Restaurant).filter( Restaurant.restaurant_name == restaurantName).scalar() is not None address_exists = session.query(Address).filter( Address.address == street, Address.city == city, Address.state == state, Address.zipcode == zipcode).scalar() is not None except ValueError: return ("Unexpected error:", sys.exc_info()[0]) if restaurant_exists: if address_exists: return 'Restaurant Already Exists' else: newAddress = Address(address=street, city=city, state=state, zipcode=zipcode, restaurant_name=restaurantName) session.add(newAddress) session.commit() return "New Retaurant added" else: newRestaurant = Restaurant(restaurant_name=restaurantName, restaurant_category=categoryName) newAddress = Address(address=street, city=city, state=state, zipcode=zipcode, restaurant_name=newRestaurant.restaurant_name) session.add(newRestaurant) session.add(newAddress) session.commit() return "New Retaurant added"
def new_restaurant(): if request.method == 'POST': new_restaurant = Restaurant(name=request.form['restaurant-name']) session.add(new_restaurant) session.commit() flash("New restaurant created") return redirect(url_for('show_restaurants')) else: return render_template('newrestaurant.html')
def restore_object(self, attrs, instance=None): if instance: instance.id = attrs.get('id', instance.id) instance.name = attrs.get('name', instance.name) instance.address = attrs.get('address', instance.address) return instance return Restaurant(attrs.get('id'), attrs.get('name'), attrs.get('address'))
def add_restaurant(location, mealType): resto_info = findARestaurant(mealType, location) print( resto_info ) resto = Restaurant( restaurant_name=resto_info['name'], restaurant_address=resto_info['address'], restaurant_image=resto_info['image'] ) session.add(resto) session.commit() return jsonify(resto = resto.serialize)
def add_restaurant(): for item in comprehensive_name_list: restaurant = Restaurant(name=item['Name'], address=item['Address'], zip_code=item['Zip'], latitude=item['Latitude'], longitude=item['Longitude']) session.add(restaurant) session.commit()
def addResaurant(): restaurant = Restaurant(name=request.form.get('name'), restaurantType=request.form.get('type'), url=request.form.get('url')) db.session.add(restaurant) db.session.commit() sql = text('select "restaurantId", name from restaurant order by name') result = db.engine.execute(sql) return render_template('/edit-pages/edit-restaurants.html', result=result)
def setUp(self): """Define test variables and initialize app.""" self.app = create_app() self.client = self.app.test_client # Test database name self.database_name = "fsndcapstone_test" self.database_path = "postgresql://*****:*****@localhost:5432/" + self.database_name setup_db(self.app, self.database_path) # binds the app to the current context with self.app.app_context(): self.db = SQLAlchemy() self.db.init_app(self.app) # create all tables self.db.create_all() # Test variables # TOKENS self.manager = 'eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6ImtwNE8walZuX2pjT0pJbTRJSFBlRyJ9.eyJpc3MiOiJodHRwczovL2ZzbmQtaGFwcHlob3VyLmF1dGgwLmNvbS8iLCJzdWIiOiJnb29nbGUtb2F1dGgyfDEwNzk0MjE1NzM5OTc0NTk0NTM1MiIsImF1ZCI6WyJmc25kY2Fwc3RvbmUiLCJodHRwczovL2ZzbmQtaGFwcHlob3VyLmF1dGgwLmNvbS91c2VyaW5mbyJdLCJpYXQiOjE1ODkwNTQ0MTgsImV4cCI6MTU4OTE0MDgxOCwiYXpwIjoiclkzZWU2eGpvV29jWFA3UGtDVW91SFM0OHZYOVlBb28iLCJzY29wZSI6Im9wZW5pZCBwcm9maWxlIGVtYWlsIiwicGVybWlzc2lvbnMiOlsiZGVsZXRlOnJlc3RhdXJhbnQiLCJnZXQ6bG9naW5fcmVzdWx0cyIsImdldDptZW51X2l0ZW0iLCJnZXQ6cmVzdGF1cmFudCIsInBhdGNoOnJlc3RhdXJhbnQiLCJwb3N0OnJlc3RhdXJhbnQiLCJyZWFkOnlvdXJzZWxmIl19.eI9z-amB1pnAAgtM6UPdTEz8P-5hVkMMktx45Cc7NW8VhD-kB0mWn3b0aMjJ3e6iOhPMfY23fAHDgAyCXUZQcgaC1yBV07b8zSlObOFYVZr6NwYSJClXgXezVBjS-JFIlKRDbHyWLfFTmEsVDGd8H61dwovPJDTz-xQYNgsDnff-tx8gDhvugnK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2BirUA' self.badtoken = 'badtoken' # New Restaurant self.new_restaurant = {'name': 'Earls', 'address': '5555 Street rd'} #Patch Restaurant self.change_restaurant_address = {'address': '1111 Street rd'} # Post New Reservations self.reservation_info = { 'time_of_res': "2020-08-19 18:30:00", 'num_of_people': 5, 'name_for_res': "Reservations Name" } #Add new restaurant if database is empty with good token and set current_rest_id if Restaurant.query.filter( Restaurant.owner_id != 'badtoken').count() == 0: res = self.client().post( '/restaurants', headers={"Authorization": "Bearer {}".format(self.manager)}, json=self.new_restaurant) self.current_rest_id = Restaurant.query.order_by( Restaurant.id.desc()).filter( Restaurant.owner_id != 'badtoken').first().id # add new restaurant with bad token is it doesnt exist, and set bad_rest_id if Restaurant.query.filter( Restaurant.owner_id == 'badtoken').count() == 0: bad_token_rest = Restaurant(name="Bad name", address="bad address", owner_id="badtoken") bad_token_rest.insert() self.bad_rest_id = Restaurant.query.filter( Restaurant.owner_id == 'badtoken').first().id
def add_restaurant(session, data): new_restaurant = Restaurant(name=data['name']) mapper = inspect(Restaurant) for key in data: for column in mapper.attrs: if key == column.key: setattr(new_restaurant, key, data[key]) session.add(new_restaurant) session.commit() return new_restaurant
def newRestaurant(): if 'username' not in login_session: return redirect('/login') if request.method == 'POST': newRestaurant = Restaurant(name=request.form['newRestaurant']) db.session.add(newRestaurant) db.session.commit() return redirect(url_for('restaurants')) elif request.method == 'GET': return render_template('newRestaurant.html')
def create(self, validated_data): restaurant = Restaurant( username=validated_data['username'], email=validated_data['email'], password=validated_data['password'], restaurantName=validated_data['restaurantName'], first_name=validated_data['first_name'], last_name=validated_data['last_name']) restaurant.save() return restaurant
def makeANewRestaurant(location, mealType): print(location) print(mealType) foursquare = findARestaurant(mealType, location) restaurant = Restaurant(restaurant_name=foursquare['name'], restaurant_address=foursquare['address'], restaurant_image=foursquare['image']) session.add(restaurant) session.commit() return jsonify(Restaurant=restaurant.serialize)
def testOneEmployee(self): """ Test verifying one normal person that can scan. Expect matching output. """ r = Restaurant(rid=2, uid=17, name="", address="") e = Employee(uid=77, rid=2) db.session.add(r) db.session.add(e) db.session.commit() access = rhelper.verify_scan_list(2) self.assertEqual([17, 77], access)
def new_restaurant(): if request.method == 'POST': new_restaurant_obj = Restaurant(name=request.form['name'], user_id=login_session['user_id']) session.add(new_restaurant_obj) flash('New Restaurant %s Successfully Created' % new_restaurant_obj.name) session.commit() return redirect(url_for('show_restaurants')) else: return render_template('newRestaurant.html')
def post(self): parsed_args = parser.parse_args() restaurant = Restaurant(name=parsed_args['name'], description=parsed_args['description'], rating=parsed_args['rating'], address=parsed_args['address'], lat=parsed_args['lat'], lon=parsed_args['lon']) session.add(restaurant) session.commit() return restaurant, 201
def create_new_restaurant(): session = DBSession() if request.method == "POST": new_restaurant = Restaurant(name=request.form["name"]) session.add(new_restaurant) session.commit() flash(f"New restaurant {new_restaurant.name} created") return redirect(url_for("show_restaurants")) else: return render_template("1_new_restaurants.html")
def test_inheritance(self): Restaurant.objects.bulk_create([Restaurant(name="Nicholas's")]) self.assertQuerysetEqual(Restaurant.objects.all(), [ "Nicholas's", ], attrgetter("name")) with self.assertRaises(ValueError): Pizzeria.objects.bulk_create([Pizzeria(name="The Art of Pizza")]) self.assertQuerysetEqual(Pizzeria.objects.all(), []) self.assertQuerysetEqual(Restaurant.objects.all(), [ "Nicholas's", ], attrgetter("name"))
def test_res_name_not_found(self): """ Test getting a res name with given invalid rid. Expect return none. """ restaurant = Restaurant(rid=96, name="bla", address="1234 Main street", uid=758) db.session.add(restaurant) db.session.commit() name = rhelper.get_restaurant_name_by_rid(259) self.assertEqual(name, None)
def all_restaurants_handler(): if request.method == "GET": restaurants = session.query(Restaurant).all() print("Restaurants: ", restaurants) return jsonify([resto.serialize for resto in restaurants]) elif request.method == "POST": print("it's a post!") name = str(request.args.get('name')) restaurant = Restaurant(restaurant_name=str(request.args['name'])) session.add(restaurant) session.commit() return redirect('/restaurants')
def test_res_name_found(self): """ Test getting a res name with given normal rid. Expect output to match correct data. """ restaurant = Restaurant(rid=96, name="bla", address="1234 Main street", uid=758) db.session.add(restaurant) db.session.commit() name = rhelper.get_restaurant_name_by_rid(96) self.assertEqual(name, "bla")
def all_restaurants_handler(): # Return all restaraunts in database. # If request method is GET, run a query on the database's Restaraunt table # (Class) for all restaraunts. Return value is a list of Restaurant objects. if request.method == 'GET': restaraunts = session.query(Restaurant).all() print(restaurants) # Query results (variable restaraunts which is a list data type) are # serialized, or, made into a dictionary then added to a list via a list # comprehension. This list is then jsonfied for injestion by front end. return jsonify(restaurants=[i.serialize for i in restaraunts]) # Make a new restaraunt and store it in the database. elif request.method == 'POST': # Flask.Request.args creates a MultiDict (dictionary subclass customized # to deal with multiple values for the same key which, is used by the # parsing functions in the wrappers. This is necessary because some HTML # form elements pass multiple values for the same key.) with the parsed # contents of the query string (strings in the URL after the "?"). # Prototype: get(key, default=None, type=None) location = request.args.get('location', '') mealType = request.args.get('mealType', '') # Create restaraunt_info variable by calling the imported # findARestaurant function. restaurant_info = findARestaurant(mealType, location) # If there is restaraunt info, create a restaurant variable that is # equal to the instantiation of the Restaurant Class defined in our # model(models.py). if restaurant_info != "No Restaurants Found": restaurant = Restaurant( restaurant_name=unicode(restaurant_info['name']), restaurant_address=unicode(restaurant_info['address']), restaurant_image=restaurant_info['image']) # Add restaraunt variable just created to session. session.add(restaurant) # Commit Restaurant instance (restaurant variable created) to db. session.commit() # Return jsonified dictionary that results when object is serialized # via the Restaurant serialize attribute method. return jsonify(restaurant=restaurant.serialize) else: # If no restaurant data resulted from running findARestaurant on # the meal type and location passed in the address bar upon url # request, return error message. return jsonify({ "error": f"No Restaurants Found for {mealType} in {location}" })
def data_onboard(data): s = new_session() getOrElse = lambda o, k, d: o[k] if k in o else d violation_code = Collection(ViolationCode, lambda vc: vc.code) borough = Collection(Borough, lambda b: b.borough) restaurant = Collection(Restaurant, lambda r: r.camis) inspection = [] for row in data: if 'boro' in row: borough.insert(Borough(borough=row['boro'])) if 'violation_code' in row: violation_code.insert(ViolationCode(code=row['violation_code'])) if 'camis' in row: restaurant.insert(Restaurant( camis=getOrElse(row, 'camis', None), dba=getOrElse(row, 'dba', None), street=getOrElse(row, 'street', None), phone=getOrElse(row, 'phone', None), cuisine_description=getOrElse(row, 'cuisine_description', None), borough=getOrElse(row, 'boro', None), building=getOrElse(row, 'building', None), zipcode=getOrElse(row, 'zipcode', None))) inspection.append(Inspection( restaurant=getOrElse(row, 'camis', None), record_date=getOrElse(row, 'record_date', None), violation_code=getOrElse(row, 'violation_code', None), violation_description=getOrElse(row, 'violation_description', None), score=int(row['score']) if 'score' in row else None, inspection_date=getOrElse(row, 'inspection_date', None), inspection_type=getOrElse(row, 'inspection_type', None), critical_flag=getOrElse(row, 'critical_flag', None))) s.bulk_save_objects(borough.getall()) s.bulk_save_objects(violation_code.getall()) s.commit() boroughs = set([r.borough for r in restaurant.getall()]) boroughs = {b[1]: b[0] for b in s.query(Borough.__table__.c.id, Borough.__table__.c.borough)} for r in restaurant.getall(): if r.borough != None: r.borough = boroughs[r.borough] bulk_save(s, restaurant.getall(), 1500) codes = set([i.violation_code for i in inspection]) codes = {c[1]: c[0] for c in s.query(ViolationCode.__table__.c.id, ViolationCode.__table__.c.code)} camis = set([r.camis for r in restaurant.getall()]) camis = {c[1]: c[0] for c in s.query(Restaurant.__table__.c.id, Restaurant.__table__.c.camis)} for i in inspection: if i.restaurant != None: i.restaurant = camis[i.restaurant] if i.violation_code != None: i.violation_code = codes[i.violation_code] bulk_save(s, inspection, 1500) s.close()
def post(cls): restaurant_name = request.json['name'] location = request.json['location'] phone = request.json['phone'] email = request.json['email'] no_of_seats = request.json['max_seats'] restaurant = Restaurant(email=email, phone=phone, location=location, restaurant_name=restaurant_name, no_of_seats=no_of_seats) restaurant.save_to_db() return restaurant.to_json(), 201
def makeANewRestaurant(location, mealType): restaurantInfo = findARestaurant(mealType, location) if restaurantInfo == "No Restaurants Found": return "No Restaurants Found" newRestaurant = Restaurant(restaurant_name=restaurantInfo['name'], restaurant_address=restaurantInfo['address'], restaurant_image=restaurantInfo['image']) session.add(newRestaurant) session.commit() newRestaurant = session.query(Restaurant).filter_by( restaurant_name=restaurantInfo['name']).first() return jsonify(Restaurant=[newRestaurant.serialize])
def all_restaurants_handler(): if request.method == 'POST': meal = request.args.get('mealType', '') location = request.args.get('location', '') restaurant = findARestaurant(meal, location) newRestaurant = Restaurant(restaurant_name=restaurant['name'], restaurant_address=restaurant['address'], restaurant_image=restaurant['image']) session.add(newRestaurant) session.commit() return jsonify(newRestaurant=newRestaurant.serialize) if request.method == 'GET': restaurants = session.query(Restaurant).all() return jsonify(restaurants=[r.serialize for r in restaurants])
def create_restaurant(): request_restaurant = request.get_json() restaurant1 = Restaurant(name=request_restaurant["name"], address=request_restaurant["address"], phone=request_restaurant["phone"], email=request_restaurant["email"], web_page=request_restaurant["web_page"], is_active=request_restaurant["is_active"], latitude=request_restaurant["latitude"], longitude=request_restaurant["longitude"], city_id=request_restaurant["city_id"]) db.session.add(restaurant1) db.session.commit() return jsonify(restaurant1.serialize()), 200
def test_no_such_rid_name(self): """ Test that the coupon's related rid is not exist, the method should return "Not Found", the rid is autoincrement, which cannot be negative. """ res = Restaurant(name="resName", address="Address", uid=404) db.session.add(res) db.session.commit() coupon = Coupon(rid=100, name="coupon_testing", points=10, description="description", level=99, expiration=None, begin=None, deleted=0) db.session.add(coupon) db.session.commit() rname = chelper.find_res_name_of_coupon_by_cid(coupon.cid) self.assertEqual(rname, "Not Found")
def test_normal_resname_valid_cid(self): """ Test if we can find the correct res name by given the cid of the coupon as we expected. """ res = Restaurant(name="resName", address="Address", uid=404) db.session.add(res) db.session.commit() coupon = Coupon(rid=res.rid, name="coupon_testing", points=10, description="description", level=250, expiration=None, begin=None, deleted=0) db.session.add(coupon) db.session.commit() rname = chelper.find_res_name_of_coupon_by_cid(coupon.cid) self.assertEqual(rname, "resName")
def test_delete_restaurant(self): new_r = Restaurant(name='THE RESTO', cuisine='THE CUISINE') new_r.insert() r_id = Restaurant.query.filter_by(name='THE RESTO').first().id res = self.client().delete(f'/restaurants/{r_id}', headers=self.headers) data = json.loads(res.data) restaurant = Restaurant.query.filter_by(id=r_id).one_or_none() self.assertEqual(res.status_code, 200) self.assertEqual(restaurant, None) self.assertEqual(data['delete'], r_id) self.assertTrue(data['success'])
def testManyEmployee(self): """ Test verifying a list of person that can scan. Expect matching output. """ r = Restaurant(rid=2, uid=17, name="", address="") e1 = Employee(uid=77, rid=2) e2 = Employee(uid=189, rid=2) e3 = Employee(uid=98, rid=3) db.session.add(r) db.session.add(e1) db.session.add(e2) db.session.add(e3) db.session.commit() access = rhelper.verify_scan_list(2) self.assertEqual([17, 77, 189], access)
def dislike_restaurant(): if not g.user: return jsonify(UNAUTHORIZED_MSG),401 google_place_id = request.json['googlePlaceId'] name = request.json['name'] address = request.json['address'] area_id = session['curr_area'] restaurant = Restaurant(name=name,address=address,google_place_id=google_place_id,user_id=g.user.id,area_id=area_id) db.session.add(restaurant) db.session.commit() dislike = Dislikes(user_id=g.user.id, restaurant_id=restaurant.id) db.session.add(dislike) db.session.commit() return jsonify({"restaurant":"disliked"})