Example #1
0
class TestAddTest(TestCase):
    def setUp(self):
        self.user = User.objects.create_user("TestAddTest_User")
        self.restaurant = Restaurant(name="Slippery Bannana", 
                             contactinfo="123 Fake Street",
                             qrfile="nonexistent qrfile",
                             client_gmt_offset=1);
        self.restaurant.save()
        wl = WaitList(restaurant=self.restaurant); 
        wl.save()
        self.user.restaurantAdminUser = RestaurantAdmin(nick="TestAddTest_nick",
                                                        restaurant=self.restaurant) 
        self.request = HttpRequest()
        self.request.user = self.user
    
    def test_add_single(self):
        response = views.test_add(self.request, 1, 1, "all")
        self.assertEqual(Customer.objects.count(), 1)
        self.assertEqual(response.status_code, 302)
        self.assertEqual(response['Location'], '/waitlist/current')
        
    def test_add_many(self):
        response = views.test_add(self.request, 3, 5, "checkedin_removed")
        self.assertEqual(Customer.objects.count(), 15)
        self.assertEqual(response.status_code, 302)
        self.assertEqual(response['Location'], '/archive_current/')
Example #2
0
	def get(self):
		context = { 
			'karma_ranking': Restaurant.gql('WHERE group=:1 ORDER BY karma DESC LIMIT 10', self.currentgroup),
			'lunchcount_ranking': Restaurant.gql('WHERE group=:1 ORDER BY lunchcount DESC LIMIT 10', self.currentgroup),
			'best_user': self.currentgroup.get_best_users(),
			'biggest_eater': self.currentgroup.get_biggest_users()			
			}
							
		self.render('stats', context)
Example #3
0
	def post(self):
		name = cgi.escape(self.request.get('name'))
		name = name.capitalize()
		if name == '':
			self.error(400)
			return
			
		restaurant = Restaurant.gql("WHERE name = :1 AND group = :2", name, self.currentgroup).get()
		if restaurant == None:
			restaurant = Restaurant(name=name, group=self.currentgroup)
			restaurant.put()
		else:
			logging.info("restaurant '%s' already exists, skipping" % name)

		self.get()
Example #4
0
 def setUp(self):
     self.user = User.objects.create_user('CustomerTest_User')
     self.restaurant = Restaurant(name="Slippery Bannana", 
                                  contactinfo="123 Fake Street",
                                  qrfile="nonexistent qrfile",
                                  client_gmt_offset=1);
     self.restaurant.save();
Example #5
0
def render_search():
    create_whoosh_dir()
    rest_ix = get_restaurant_index()
    loc_ix = get_location_index()
    cat_ix = get_category_index()

    restSearchableFields = ["name","phonenum"]
    locSearchableFields = ["address","neighborhood", "zipcode"]
    catSearchableFields = ["name"]

    restDataList = []
    locDataList = []
    catDataList = []

    if request.method == 'POST':
        search_query = request.form['search']
        restDataList = search_results(rest_ix, search_query, restSearchableFields)
        locDataList = search_results(loc_ix, search_query, locSearchableFields)
        catDataList = search_results(cat_ix, search_query, catSearchableFields)
        constructRelatedModels(restDataList, locDataList, catDataList)

    return render_template('search_results.html',
        restDataNames=Restaurant.getDataNames() + ["context"],
        restDataList=restDataList,
        locDataNames=Location.getDataNames() + ["context"],
        locDataList=locDataList,
        catDataNames=Category.getDataNames() + ["context"],
        catDataList=catDataList)
Example #6
0
 def setUp(self):
     self.p1 = Place(name='Demon Dogs', address='944 W. Fullerton')
     self.p1.save()
     self.p2 = Place(name='Ace Hardware', address='1013 N. Ashland')
     self.p2.save()
     self.r = Restaurant(place=self.p1, serves_hot_dogs=True, serves_pizza=False)
     self.r.save()
Example #7
0
def DocFromModels(rest_id, menu_id):
    # try:
    rest = Restaurant.get_by_id(rest_id)
    menu = Menu.get_by_id(menu_id)
    ui_profile = UIProfile.get_by_menu(menu)
    menuitems = MenuItem.get_by_menu(menu)

    grab_vars = lambda item: deepcopy(vars(item)["_entity"])

    obj = {}
    obj["menu_id"] = menu.menu_id
    obj["restaurant_id"] = rest.restaurant_id
    obj["restaurant_name"] = rest.name
    obj["menu_name"] = menu.name
    obj["ui_profile"] = grab_vars(ui_profile)
    obj["ui_profile"]["menu"] = "null"
    obj["menuitems"] = {}

    for menuitem in menuitems:
        category = menuitem.category
        menu_item_dict = grab_vars(menuitem)
        menu_item_dict["menu"] = "null"
        if obj["menuitems"].has_key(category):
            obj["menuitems"][category].append(menu_item_dict)
        else:
            obj["menuitems"][category] = [menu_item_dict]

    return json.dumps(obj)
Example #8
0
def verifyMessage(request):
    # message, secret_key, timestamp, request_hash
    message = request.get("message")
    timestamp = request.get("timestamp")
    request_hash = request.get("message_hash")
    secret_key = Restaurant.get_by_id(request.get("restaurant_id")).secret_key
    message_hash = hashlib.sha1(message + secret_key + timestamp).hexdigest()
    return message_hash == request_hash
Example #9
0
def create_restaurant():
  r = request.json
  if not r or 'title' not in r or type(r['title']) is not unicode or len(r['title'].strip()) < 2:
    abort(400)

  title = r['title'].strip().lower()

  if Restaurant.query.filter_by(title = title).count():
    abort(409)
  else:
    restaurant = Restaurant(**r)
    db.session.add(restaurant)
    db.session.commit()

    db.session.refresh(restaurant)
    sock.emit('append', {'uri': '/api/restaurants/%d' % restaurant.id}, namespace='/test')
    return json.dumps(restaurant.to_dict(), ensure_ascii = False)
Example #10
0
def render_restaurant():
    tableDataDict = getTableDataDict("Restaurants","restaurant", Restaurant)
    restDataDictList = getDataDictList(getModels(Restaurant, tableDataDict['offset'],
        tableDataDict['sortby'], tableDataDict['direction']))
    return render_template('template_db.html',
            dataNames=Restaurant.getDataNames(),
            dataList=restDataDictList,
            **tableDataDict
        )
Example #11
0
 def post(self):
     if AUTH_ENABLED and not verifyMessage(self.request):
         self.response.out.write("AUTH FAILED")
         return
     restaurant_id = self.request.get("restaurant_id")
     self.response.headers["Access-Control-Allow-Origin"] = "*"
     if Restaurant.delete_by_id(restaurant_id):
         self.response.out.write("Menu Successfully Deleted")
     else:
         self.response.out.write("ERROR: Could not delete")
Example #12
0
class WaitListTest(TestCase):
    def setUp(self):
        self.user = User.objects.create_user('WaitListTest_User')
        self.user.save()
        self.restaurant = Restaurant(name="Slippery Bannana", 
                                     contactinfo="123 Fake Street",
                                     qrfile="nonexistent qrfile",
                                     client_gmt_offset=1);
        self.restaurant.save();

    def test_add_customer(self):
        wl = WaitList(restaurant=self.restaurant); 
        wl.save()
        wl.add_customer(Customer(name="Fred", party_size=5, phone="0000000000", waitlist=wl))
        wl.add_customer(Customer(name="George", party_size=2, phone="0000000000", waitlist=wl))
        wl = save_load(wl);
        self.assertEqual(wl.customers.count(), 2)
        self.assertEqual(wl.customers.filter(name="Fred").count(), 1)
        self.assertEqual(wl.customers.filter(name="George").count(), 1)
Example #13
0
class TestArchiveCurrent(TestCase):
    def setUp(self):
        '''Add user data so we have something to archive'''
        self.user = User.objects.create_user("TestAddTest_User")
        self.restaurant = Restaurant(name="Slippery Bannana", 
                             contactinfo="123 Fake Street",
                             qrfile="nonexistent qrfile",
                             client_gmt_offset=1);
        self.restaurant.save()
        wl = WaitList(restaurant=self.restaurant); 
        wl.save()
        self.user.restaurantAdminUser = RestaurantAdmin(nick="TestAddTest_nick",
                                                        restaurant=self.restaurant) 
        self.request = HttpRequest()
        self.request.user = self.user
        views.test_add(self.request, 3, 7, "checkedin_removed")
    
    def test_archive_current(self):
        response = views.archive_current(self.request)
        self.assertEqual(response.status_code, 302)
        self.assertEqual(response['Location'], '/waitlist/current/')
Example #14
0
class CustomerTest(TestCase):
    def setUp(self):
        self.user = User.objects.create_user('CustomerTest_User')
        self.restaurant = Restaurant(name="Slippery Bannana", 
                                     contactinfo="123 Fake Street",
                                     qrfile="nonexistent qrfile",
                                     client_gmt_offset=1);
        self.restaurant.save();
        
    def test_customer_creation(self):
        # Save
        original_customer_count = Customer.objects.count()
        
        wl = WaitList(restaurant=self.restaurant); wl.save()
        c = Customer(name="Fred", party_size=5, phone="0000000000", waitlist=wl)
        c = save_load(c)
        self.assertEqual(Customer.objects.count(), original_customer_count+1)
        self.assertNotEqual(c, None)
        self.assertEqual(c.name, "Fred")
        self.assertEqual(c.party_size, 5)
        self.assertEqual(c.phone, "0000000000")
Example #15
0
def restaurant_feed():
    feed = AtomFeed('Recent Restaurants',
                    feed_url=request.url, url=request.url_root)
    restaurants = Restaurant.newest(10)
    for restaurant in restaurants:
        feed.add(restaurant.name, unicode(restaurant.menu_items_str),
                 content_type='html',
                 author=restaurant.user.name,
                 url=make_external(restaurant.url),
                 updated=restaurant.last_update,
                 published=restaurant.published)
    return feed.get_response()
Example #16
0
 def setUp(self):
     self.user = User.objects.create_user("TestAddTest_User")
     self.restaurant = Restaurant(name="Slippery Bannana", 
                          contactinfo="123 Fake Street",
                          qrfile="nonexistent qrfile",
                          client_gmt_offset=1);
     self.restaurant.save()
     wl = WaitList(restaurant=self.restaurant); 
     wl.save()
     self.user.restaurantAdminUser = RestaurantAdmin(nick="TestAddTest_nick",
                                                     restaurant=self.restaurant) 
     self.request = HttpRequest()
     self.request.user = self.user
Example #17
0
    def test_issue_7276(self):
        # Regression test for #7276: calling delete() on a model with
        # multi-table inheritance should delete the associated rows from any
        # ancestor tables, as well as any descendent objects.
        place1 = Place(
            name="Guido's House of Pasta",
            address='944 W. Fullerton')
        place1.save_base(raw=True)
        restaurant = Restaurant(
            place_ptr=place1,
            serves_hot_dogs=True,
            serves_pizza=False)
        restaurant.save_base(raw=True)
        italian_restaurant = ItalianRestaurant(
            restaurant_ptr=restaurant,
            serves_gnocchi=True)
        italian_restaurant.save_base(raw=True)

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

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

        self.assertRaises(
            Place.DoesNotExist,
            Place.objects.get,
            pk=ident)
        self.assertRaises(
            ItalianRestaurant.DoesNotExist,
            ItalianRestaurant.objects.get,
            pk=ident)
Example #18
0
    def get(self):
        if AUTH_ENABLED and not verifyMessage(self.request):
            self.response.out.write("AUTH FAILED")
            return

        rest_id = self.request.get("restaurant_id")
        rest = Restaurant.get_by_id(rest_id)
        if not rest:
            self.response.out.write("Restaurant does not exist")
            return

        doc = self.request.get("doc")
        doc_obj = json.loads(doc)
        self.response.headers["Access-Control-Allow-Origin"] = "*"
        self.response.out.write(template.render("templates/index.html", doc_obj))
Example #19
0
def render_category_id(category_id=None):
    catModel = Category.query.get_or_404(category_id)

    imgList = [restModel.imageurl for restModel in catModel.restlist][:5]

    while len(imgList) < 5:
        imgList = imgList + [url for url in imgList]
        imgList = imgList[:5]

    relatedRestModels = getDataDictList(catModel.restlist)
    return render_template('category.html',
        catModel = catModel,
        restAttrs = Restaurant.getDataNames(),
        imgList = imgList,
        restListModels = dumps(relatedRestModels))
Example #20
0
 def setUp(self):
     '''Add user data so we have something to archive'''
     self.user = User.objects.create_user("TestAddTest_User")
     self.restaurant = Restaurant(name="Slippery Bannana", 
                          contactinfo="123 Fake Street",
                          qrfile="nonexistent qrfile",
                          client_gmt_offset=1);
     self.restaurant.save()
     wl = WaitList(restaurant=self.restaurant); 
     wl.save()
     self.user.restaurantAdminUser = RestaurantAdmin(nick="TestAddTest_nick",
                                                     restaurant=self.restaurant) 
     self.request = HttpRequest()
     self.request.user = self.user
     views.test_add(self.request, 3, 7, "checkedin_removed")
Example #21
0
	def get(self):
		
		if self.currentuser.lastposted == None:
			self.redirect('/profile')
			return
		
		group = self.currentgroup
		
		context = { 'ask_to_rate' : can_vote(self.currentuser, self.currentgroup),
					'active_crew': get_active_crew(group),
					'dead_crew': get_dead_crew(group), 
					'suggestions': Suggestion.get_todays(group),
					'restaurants': Restaurant.get_for_group(group) }

		self.render('home', context)
Example #22
0
    def post(self):
        auth_code = self.request.get("auth_code")
        if auth_code != PASSCODE and AUTH_ENABLED:
            self.response.out.write("AUTH FAILED")
            return

        rest = Restaurant.create(self.request.get("name"))
        return_obj = {"secret_key": rest.secret_key, "restaurant_id": rest.restaurant_id}

        menu = Menu.create("menu", rest)
        uiProfile = UIProfile.create(menu)
        menu_item_1 = MenuItem.create("Starter Item 1", menu, 10.00, "Appy", "This is a sample menu Item")
        menu_item_2 = MenuItem.create("Starter Item 2", menu, 11.00, "Drink", "This is a sample menu Item")

        self.response.headers["Access-Control-Allow-Origin"] = "*"
        self.response.out.write(json.dumps(return_obj))
Example #23
0
def ModelsFromDoc(jsonString, rest_id):
    try:
        obj = json.loads(jsonString)

        profile_id = obj["ui_profile"]["profile_id"]

        # Create or Update Rest
        rest = Restaurant.get_by_id(rest_id)
        rest.name = obj["restaurant_name"]

        # Create or Update Menu
        menu = Menu.get_menus_by_rest_id(rest_id)[0]

        menu.name = obj["menu_name"]
        menu.resturant = rest

        # Create or Update UI Profile
        UIProfile.delete_by_menu(menu)
        ui_profile = UIProfile.create(menu)
        ui_profile.template = obj["ui_profile"]["template"]
        ui_profile.color = obj["ui_profile"]["color"]
        ui_profile.font = obj["ui_profile"]["font"]
        ui_profile.logo_url = obj["ui_profile"]["logo_url"]
        # logging.info(str(obj))
        # Create or Update menuitems

        MenuItem.delete_by_menu(menu)
        menu_items_dict = obj["menuitems"]
        logging.info(type(menu_items_dict))
        for category in menu_items_dict.keys():
            category_list = menu_items_dict[category]
            for menu_item_dict in category_list:
                menuitem = MenuItem.create(
                    menu_item_dict["name"],
                    menu,
                    menu_item_dict["price"],
                    category,
                    menu_item_dict["image"],
                    menu_item_dict["description"],
                )
                menuitem.put()
        ui_profile.put()
        menu.put()
        rest.put()
        return True
    except:
        return False
def edit_menu_item(restaurant_id, menu_item_id):
    restaurant = Restaurant.get_by_id(restaurant_id)
    menu_item = MenuItem.get_by_id(menu_item_id)
    if request.method == 'POST':
        menu_item_name = request.form['menu_item_name']
        menu_item_description = request.form['menu_item_description']
        menu_item_price = request.form['menu_item_price']
        menu_item.update(name=menu_item_name,
                         description=menu_item_description,
                         price=menu_item_price)
        flash('Menu item edited')
        return redirect(
            url_for('single_restaurant', restaurant_id=restaurant_id))
    else:
        return render_template('edit-menu-item.html',
                               restaurant=restaurant,
                               menu_item=menu_item)
Example #25
0
 def test_issue_6755(self):
     """
     Regression test for #6755
     """
     r = Restaurant(serves_pizza=False)
     r.save()
     self.assertEqual(r.id, r.place_ptr_id)
     orig_id = r.id
     r = Restaurant(place_ptr_id=orig_id, serves_pizza=True)
     r.save()
     self.assertEqual(r.id, orig_id)
     self.assertEqual(r.id, r.place_ptr_id)
Example #26
0
def createRestaurant(location, mealType):
    print 'inside createRestaurant'
    try:
        restaurant_info = findARestaurant(location, mealType)
        if restaurant_info != 'No Restaurants Found':
            print 'restaurant info: %s' % unicode(restaurant_info)
            newRestaurant = Restaurant(
                restaurant_name = unicode(restaurant_info['name']),
                restaurant_address = unicode(restaurant_info['address']),
                restaurant_image = restaurant_info['image']
            )
            session.add(newRestaurant)
            session.commit()
            return jsonify(restaurant = newRestaurant.serialize)
        else:
            return jsonify({'error':'No Restaurants returned for %s in %s' % (mealType, location)})
    except:
        return jsonify({'error':'Cannot retrive Restaurants for %s in %s' % (mealType, location)})
    def test_restaurant_address_and_name_nonempty(self):
        ''' Tries to update restaurant information using a non-empty
        restaurant name and address.'''
        restaurant = Restaurant(name="test name",
                                address="test address",
                                uid=10)
        db.session.add(restaurant)
        db.session.commit()

        errmsg = rhelper.update_restaurant_information(restaurant, "new name",
                                                       "new address")
        self.assertEqual(errmsg, [])

        updatedRestaurant = Restaurant.query.filter(
            Restaurant.rid == 1).first()
        self.assertEqual(updatedRestaurant.name, "new name")
        self.assertEqual(updatedRestaurant.address, "new address")
        self.assertEqual(updatedRestaurant.uid, 10)
    def test_restaurant_name_empty(self):
        ''' Tries to update restaurant information using an empty
        restaurant name. '''
        restaurant = Restaurant(name="test name",
                                address="test address",
                                uid=10)
        db.session.add(restaurant)
        db.session.commit()

        errmsg = rhelper.update_restaurant_information(restaurant, "",
                                                       "new address")
        self.assertEqual(errmsg, ["The restaurant's name cannot be empty."])

        updatedRestaurant = Restaurant.query.filter(
            Restaurant.rid == 1).first()
        self.assertEqual(updatedRestaurant.name, "test name")
        self.assertEqual(updatedRestaurant.address, "test address")
        self.assertEqual(updatedRestaurant.uid, 10)
 def test_owner_found(self):
     """
     Test finding an rid by given a valid uid. Expect output to match correct data.
     """
     restaurant = Restaurant(rid=17465,
                             name="KFC",
                             address="1265 Military trail",
                             uid=34)
     user = User(uid=34,
                 name="joe",
                 email="*****@*****.**",
                 password="******",
                 type=1)
     db.session.add(restaurant)
     db.session.add(user)
     db.session.commit()
     rid = rhelper.get_rid(34)
     self.assertEqual(rid, 17465)
Example #30
0
def createARestaurant(location, mealtype):
    # Here I use my api findARestaurant to return the first restaurant
    # it will return name, address and image
    indication = find(mealtype, location)
    if type(indication) is not dict:
        return jsonify("no restaurant found")
    else:
        loc = ", ".join(indication["address"])

        # store the restaurant in the database
        restaurant = Restaurant(name=indication["name"],
                                address=loc,
                                image=indication["image"])
        session.add(restaurant)
        session.commit()

        # returns the restaurant for the user
        return jsonify(Restaurant=restaurant.serialize)
Example #31
0
def insert_new_restaurant(rname, address, uid):
    """
    Inserts restaurant into restaurant table.

    Args:
        rname: The name given to the resturant. A string with max 64 characters.
        address: The address given to the resturant. A string with max 64
          characters.
        uid: The user ID that corressponds to the a owner. A positive integer.

    Returns:
        the resturant ID that corressponds with the newly inserted restaurant.
        The resturant ID is always a positive interger.
    """
    restaurant = Restaurant(name=rname, address=address, uid=uid)
    db.session.add(restaurant)
    db.session.commit()
    return restaurant.rid
def all_restaurants_handler():
    if request.method == 'GET':
        restaurants = session.query(Restaurant).all()
        return jsonify(restaurants=[i.serialize for i in restaurants])

    elif request.method == 'POST':
        location = request.args.get('location', '')
        mealType = request.args.get('mealType', '')
        restaurant_info = findARestaurant(mealType, location)
        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'])
            session.add(restaurant)
            session.commit()
            return jsonify(restaurant=restaurant.serialize)
        else:
            return jsonify({"error": "No Restaurants Found for %s in %s" % (mealType, location)})
Example #33
0
def all_restaurants_handler():
  if request.method == 'GET':
  	# RETURN ALL RESTAURANTS IN DATABASE
  	restaurants = session.query(Restaurant).all()
  	return jsonify(restaurants = [i.serialize for i in restaurants])

  elif request.method == 'POST':
  	# MAKE A NEW RESTAURANT AND STORE IT IN DATABASE
    location = request.args.get('location', '')
    mealType = request.args.get('mealType', '')
    restaurant_info = findARestaurant(mealType, location)
    if restaurant_info != "No Restaurants Found":
      restaurant = Restaurant(restaurant_name = str(restaurant_info['name']), restaurant_address = str(restaurant_info['address']), restaurant_image = restaurant_info['image'])
      session.add(restaurant)
      session.commit() 
      return jsonify(restaurant = restaurant.serialize)
    else:
      return jsonify({"error":"No Restaurants Found for %s in %s" % (mealType, location)})
Example #34
0
def all_restaurants_handler():
    if request.method == 'GET':
        restaurants = session.query(Restaurant).all()
        return jsonify(restaurants=[i.serialize for i in restaurants])
    elif request.method == 'POST':
        location = request.args.get('location')
        mealType = request.args.get('mealType')
        restaurant = findARestaurant(mealType, location)

        if restaurant != 'No Restaurants Found':
            newItem = Restaurant(
                restaurant_name=restaurant['name'], restaurant_address=restaurant['address'], restaurant_image=restaurant['image'])
            session.add(newItem)
            session.commit()
            return jsonify(restaurant=newItem.serialize)
        else:
            return jsonify(
                {"error": "No Restaurants Found for {} in {}".format(mealType, location)})
Example #35
0
def all_restaurants_handler():
  #YOUR CODE HERE
  if request.method == 'GET':
    # Return all restaurants in database
    restaurants = session.query(Restaurant).all()
    return jsonify(restaurants = [restaurant.serialize for restaurant in restaurants])
  
  elif request.method == 'POST':
    # Make a new restaurant and store it in database
    location = request.args.get('location') # or ('location', '')
    mealType = request.args.get('mealType')
    restaurantInfo = findARestaurant(mealType, location)
    if restaurantInfo != "No Restaurants Found":
      restaurant = Restaurant(restaurant_name = unicode(restaurantInfo['name']), restaurant_address = unicode(restaurantInfo['address']), restaurant_image = unicode(restaurantInfo['image']))
      session.add(restaurant)
      session.commit()
      return jsonify(restaurant = restaurant.serialize)
    else:
      return jsonify({'Error':'No Restaurant Found for %s around %s'} % (mealType, location))
Example #36
0
def all_restaurants_handler():
    #YOUR CODE HERE
    if request.method == 'POST':
        #
        location = request.args.get('location')
        mealType = request.args.get('mealType')
        RestaurantJSON = findARestaurant(mealType, location)
        newRestaurant = Restaurant(
            restaurant_name=RestaurantJSON['name'],
            restaurant_address=RestaurantJSON['address'],
            restaurant_image=RestaurantJSON['image'])
        session.add(newRestaurant)
        session.commit()
        return jsonify(Restaurant=newRestaurant.serialize)

    if request.method == 'GET':
        #RETURN ALL RESTAURANTS
        allRestaurants = session.query(Restaurant).all()
        return jsonify(Restaurant=[i.serialize for i in allRestaurants])
Example #37
0
def newRestaurant():
    """
    Create a new restaurant.
    :return:
    on GET: Render new restaurant form template.
    on POST: Redirect to the restaurants page if the create request has been succeeded.
    """
    if request.method == 'POST':
        restaurant = Restaurant(name=request.form['name'],
                                description=request.form['description'],
                                telephone=request.form['telephone'],
                                user_id=login_session['user_id'])

        session.add(restaurant)
        session.commit()
        flash('New restaurant %s successfully created!' % restaurant.name)
        return redirect(url_for('showHome'))
    else:
        return render_template('newRestaurant.html')
Example #38
0
    def get(self):
        user = users.get_current_user()
        restaurant = Restaurant.query(Restaurant.user == user.email()).fetch()
        if restaurant:
            log_url = users.create_logout_url('/')
            restaurant = restaurant[0]
            tables = Table.query(Table.restaurant_id == restaurant.key).order(
                Table.time_filled).fetch()
            template_vars = {
                "tables": tables,
                "restaurant": restaurant,
                "log_url": log_url,
            }
            tables_template = jinja_current_directory.get_template(
                "templates/tables.html")
            self.response.write(tables_template.render(template_vars))

        else:
            self.response.write(users.create_logout_url('/'))
def read(opfile):
    reader = csv.reader(opfile)
    included_cols = [0, 1, 2, 3]
    for row in reader:
        content = list(row[i] for i in included_cols)
        url = main_api + 'search?q=' + content[1]
        data = returnresponse(url)
        for r in range(0, len(data["restaurants"])):
            var = data["restaurants"][r]["restaurant"]
            if var["location"]["locality"].find(content[2]) != -1:
                try:
                    Restaurant.nodes.get(rid=var["id"])
                except Restaurant.DoesNotExist:
                    Restaurant(rid=var["id"], name=var["name"], rating=var["user_rating"]["aggregate_rating"],
                               ratings_count=var["user_rating"]["votes"], avg_cost=var["average_cost_for_two"],
                               url=var["url"], has_online_delivery=var["has_online_delivery"],
                               has_table_booking=var["has_table_booking"]).save()
                    rest = Restaurant.nodes.get(rid=var["id"])
                    cuisines = var["cuisines"].split(',')
                    for j in range(0, len(cuisines)):
                        cuisine_node = Cuisine.nodes.get(name=cuisines[j].strip())
                        rest.SERVES.connect(cuisine_node)

                    var_loc = var["location"]
                    try:
                        Location.nodes.get(locality=var_loc["locality"])
                    except Location.DoesNotExist:
                        Location(locality=var_loc["locality"]).save()
                    loc = Location.nodes.get(locality=var_loc["locality"])
                    rest.IN.connect(loc, {'addr': var_loc['address'], 'lat': var_loc['latitude'],
                                          'long': var_loc['longitude'], \
                                          'zipcode': var_loc['zipcode']})
                rest = Restaurant.nodes.get(rid=var["id"])
                if content[0] != " ":
                    try:
                        User.nodes.get(name=content[0])
                        print("hello")
                    except User.DoesNotExist:
                        User(name=content[0]).save()
                u = User.nodes.get(name=content[0])
                u.RATED.connect(rest, {'rating': content[3]})
                break
Example #40
0
 def test_no_such_rid_addr(self):
     """
     Test that the coupon's related rid is not exist, the method should return 
     "Not Found". Expect an error message.
     """
     res = Restaurant(name="resName", address="Address", uid=404)
     db.session.add(res)
     db.session.commit()
     coupon = Coupon(rid=900,
                     name="coupon_testing",
                     points=10,
                     description="description",
                     level=88,
                     expiration=None,
                     begin=None,
                     deleted=0)
     db.session.add(coupon)
     db.session.commit()
     raddr = chelper.find_res_addr_of_coupon_by_cid(coupon.cid)
     self.assertEqual(raddr, "Not Found")
Example #41
0
def all_restaurants_handler():

    if request.method == 'GET':
        restaurants = session.query(Restaurant).all()
        return jsonify(restaurants=[i.serialize for i in restaurants])

    elif request.method == 'POST':
        mealType = request.args.get('mealType')
        location = request.args.get('location')

        found = findARestaurant(mealType, location)

        newRestaurant = Restaurant(restaurant_name=unicode(found['name']),
                                   restaurant_address=unicode(
                                       found['address']),
                                   restaurant_image=found['image'])
        session.add(newRestaurant)
        session.commit()

        return jsonify(newRestaurant=newRestaurant.serialize)
Example #42
0
 def test_normal_resaddr_valid_cid(self):
     """
     Test if we can find the correct res addr by given the cid of the coupon
     as we expected. Expect output to match correct data.
     """
     res = Restaurant(name="res", address="Address", uid=505)
     db.session.add(res)
     db.session.commit()
     coupon = Coupon(rid=res.rid,
                     name="coupon_testing",
                     points=10,
                     description="description",
                     level=56,
                     expiration=None,
                     begin=None,
                     deleted=0)
     db.session.add(coupon)
     db.session.commit()
     raddr = chelper.find_res_addr_of_coupon_by_cid(coupon.cid)
     self.assertEqual(raddr, "Address")
Example #43
0
    def post(self):
        user = users.get_current_user()
        Restaurant(
            name=self.request.get('name_r'),
            phone=self.request.get('phone_r'),
            street_address=self.request.get('street'),
            city=self.request.get('city'),
            state=self.request.get('state'),
            zip_code=self.request.get('zip'),
            user=user.email(),
        ).put()

        Table(
            description=self.request.get('table_description'),
            max=self.request.get('table_size_max'),
            min=self.request.get('table_size_min'),
            #restaurant_id = self.request.get(),
            full=False,
            time_filled=datetime.datetime.now(),
        ).put()
Example #44
0
    def get(self):
        user = users.get_current_user()
        restaurant = Restaurant.query(Restaurant.user == user.email()).fetch()
        if restaurant:
            log_url = users.create_logout_url('/')
            restaurant = restaurant[0]
            waits = Wait.query(
                Wait.restaurant_key == restaurant.key).order().fetch()
            template_vars = {
                "waits": waits,
                "restaurant": restaurant,
                "twilio_account_sid": SECRETS["twilio_account_sid"],
                "twilio_auth_token": SECRETS["twilio_auth_token"],
                "log_url": log_url,
            }

            activeq_template = jinja_current_directory.get_template(
                "templates/active_q.html")
            self.response.write(activeq_template.render(template_vars))
        else:
            self.response.write(users.create_logout_url('/'))
Example #45
0
    def get(self):
        if AUTH_ENABLED and not verifyMessage(self.request):
            self.response.out.write("AUTH FAILED")
            return

        rest_id = self.request.get("restaurant_id")
        rest = Restaurant.get_by_id(rest_id)
        if not rest:
            self.response.out.write("Restaurant does not exist")
            return

        menu_id = Menu.get_menus_by_rest_id(rest_id)[0].menu_id
        doc = DocFromModels(rest_id, menu_id)
        logging.info(doc)
        doc_obj = json.loads(doc)
        self.response.headers.add_header("Access-Control-Allow-Origin", "*")
        self.response.headers.add_header(
            "Access-Control-Allow-Headers",
            "X-Requested-With, Content-Type, Access-Control-Allow-Headers Origin, Access-Control-Allow-Origin, Access-Control-All",
        )
        self.response.out.write(template.render("templates/index.html", doc_obj))
Example #46
0
def login():
    errormsg = ''
    if request.method == 'POST':
        usrnm = request.form['username'].strip()
        pwd = request.form['password']
        from ecarte.admin.models import User
        u = User.find(usrnm)
        if not u:
            errormsg = 'Invalid user name.'
        else:
            if u.check_password(pwd):
                login_user(u, remember=True)
                # TODO: if not admin and has only one r, redirect to the edit page
                url = 'admin'
                if not u.is_admin:
                    rlist = list(Restaurant.list_names_and_addresses(u.id))
                    if len(rlist) == 1:
                        url = 'admin/%s' % rlist[0]['_id']
                return redirect(request.args.get('next') or url)
            else:
                errormsg = 'Invalid password.'
    return render_template('admin/login.html', errormsg=errormsg)
Example #47
0
def all_restaurants_handler():
    if request.method == 'GET':
        #Call the method to Get all of the restaurants
        restaurants = session.query(Restaurant).all()
        return jsonify(restaurants=[i.serialize for i in restaurants])

    elif request.method == 'POST':
        #Call the method to make a new restaurant
        print "Make a new restaurant from foursquare and store it into database"
        location = request.args.get('location', '')
        mealType = request.args.get('mealType', '')
        restaurant_info = findARestaurant(location, mealType)
        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'])
            session.add(restaurant)
            session.commit()
            return jsonify(restaurant = restaurant.serialize)
        else:
            return jsonify({"error":"No Restaurants Found for %s in %s" % (mealType, location)})
Example #48
0
    def get(self):
        user = users.get_current_user()
        #if statement that checks if user is logged in via google
        if user:
            log_url = users.create_logout_url('/')
            #check if user is in Restaurant Datastore already/is a returning user
            user_email = user.email()
            rest_query = Restaurant.query(
                Restaurant.user == user_email).fetch(1)

            #if user email is in Restaurant Datastore go to home page/ else send to new restaurant handler
            if rest_query != []:
                self.redirect('/tables')
            else:
                self.redirect('/new_rest')
        #if user not logged into google, generates login
        else:
            log_url = users.create_login_url('/')
        #renders login2 html page with link to login url for unlogged in users
        login_template = jinja_current_directory.get_template(
            "templates/login2.html")
        self.response.write(login_template.render({'log_url': log_url}))
Example #49
0
def all_restaurants_handler():
    if request.method == 'GET':
        # RETURN ALL RESTAURANTS IN DATABASE
        restaurants = session.query(Restaurant).all()

        return jsonify(restaurants=[i.serialize for i in restaurants])

    elif request.method == 'POST':
        # MAKE A NEW RESTAURANT AND STORE IT IN DATABASE
        location = request.form.get('location')
        food = request.form.get('food')
        latitude, longitude = get_latitude_longitude_location(location)
        restaurant_info = get_restaurants(latitude, longitude, food)

        if restaurant_info != 'No Restaurants Found':
            restaurant = Restaurant(restaurant_id = restaurant_info['restaurant_id'], name = restaurant_info['name'], \
                                    location = restaurant_info['location'], food = restaurant_info['food'])
            session.add(restaurant)
            session.commit()
            return jsonify(restaurant=restaurant.serialize)
        else:
            return jsonify(
                {'error': f'No Restaurants Found for {food} in {location}'})
Example #50
0
def _save_helper(updatefn, **kwargs):
    rid = request.form.get('rid', '').strip()
    new = False
    r = None
    if rid:
        r = Restaurant.get(rid)
        if not r:
            abort(404)
    else:
        if kwargs.get('create_new', False):
            r, new = {}, True
        else:
            abort(404)
    ok, data = updatefn(r, request.form)
    if ok:
        data.update(status=STATUS_OK, rid=str(r['_id']))
        if new:
            data['redirect'] = True
        if 'success_msg' in kwargs:
            data['success_msg'] = kwargs['success_msg']
    else:
        data.update(status=STATUS_ERROR)
    return data
Example #51
0
    def test_to_json_1(self):

        a = Restaurant(
            restaurant_name="sample",
            rating=4.5,
            image_url="sample",
            price="sample",
            review_count=1,
            city_name="sample",
            state_name="sample",
            transactions="sample",
            categories="sample",
            address="sample",
            city_state_name="sample",
        )

        res = to_json(a, Restaurant)
        temp = json.loads(res)
        self.assertEqual(temp["restaurant_name"], "sample")
        self.assertEqual(temp["rating"], 4.5)
        self.assertEqual(temp["price"], "sample")
        self.assertEqual(temp["review_count"], 1)
        self.assertEqual(temp["address"], "sample")
Example #52
0
    def post(self):
        if AUTH_ENABLED and not verifyMessage(self.request):
            self.response.out.write("AUTH FAILED")
            return
        rest_id = self.request.get("restaurant_id")
        menu_name = self.request.get("menu_name")

        rest = Restaurant.get_by_id(rest_id)
        if not rest:
            self.response.out.write("Invalid restaurant_id")
            return

        if Menu.get_menus_by_rest_id(rest_id):
            self.resonse.out.write("Cant create another menu for this restaurant.  It already has one")
            return

        menu = Menu.create(menu_name, rest)
        uiProfile = UIProfile.create(menu)
        menu_item_1 = MenuItem.create("Starter Item 1", menu, 10.00, "Appy", "This is a sample menu Item")
        menu_item_2 = MenuItem.create("Starter Item 2", menu, 11.00, "Drink", "This is a sample menu Item")
        self.response.headers.add_header("Access-Control-Allow-Origin", "*")
        self.response.headers.add_header("Access-Control-Allow-Headers", "X-Requested-With")
        self.response.out.write(DocFromModels(rest_id, menu.menu_id))
Example #53
0
	def get(self):
		if is_morning():
			day = datetime.now() - timedelta(1)
			day_title = "yesterday"
		else:
			day = datetime.now()
			day_title = "today"
		
		suggestions = Suggestion.get_for_day(day, self.currentgroup)
		restaurants = [ s.restaurant for s in suggestions ]
		res_keys = [ r.key() for r in restaurants ]

		other_restaurants = []
		all_restaurants = Restaurant.gql("WHERE group=:1 ORDER BY name", self.currentgroup)
		for res in all_restaurants:
			if res.key() not in res_keys:
				other_restaurants.append(res)
				
		context = { 'day': day.toordinal(),
					'day_title': day_title, 
					'restaurants': restaurants,
					'other_restaurants': other_restaurants }			
		self.render('rate', context)		
Example #54
0
def all_restaurants_handler():
  if request.method == 'POST':
    # expects params
    # location, mealType
    location = request.form.get('location','55108')
    mealType = request.form.get('mealType','Pizza')

    print location,mealType

    # find a restaurant   
    located_restaurant = findARestaurant(mealType, location)
    name = located_restaurant['name']
    address = located_restaurant['address']
    image = located_restaurant['image']
    # insert into db
    new_restaurant = Restaurant(restaurant_name=name,restaurant_address=address,restaurant_image=image)
    try:
      session.add(new_restaurant)
      session.commit()
    except exc.DatabaseError as e:
      print("Problem commiting the update in {0}".format(new_restaurant.name))
      print("Error message:".format(e.message))


    return jsonify(new_restaurant.serialize)
  elif request.method == 'GET':
    # Return all Restaurants
    restaurants = session.query(Restaurant)
    restaurants_list = []
    # add serialized json to array
    for res in restaurants:
      restaurants_list.append(res.serialize)

    # send back a restaurants json object, with it's value the array of json restaurants
    return_obj={}
    return_obj['restaurants']=restaurants_list
    return jsonify(return_obj)
Example #55
0
def restaurants(request):
    #connect to our local mongodb
    db = Connection('localhost', 27017)
    #get a connection to our database
    dbconn = db.restaurants
    restaurantCollection = dbconn['restaurants']

    if request.method == 'GET':
        #get our collection
        restaurants = []
        for r in restaurantCollection.find():
            restaurant = Restaurant(r["_id"], r["name"], r["address"])
            restaurants.append(restaurant)
        serializedList = RestaurantSerializer(restaurants, many=True)
        return Response(serializedList.data)
    elif request.method == 'POST':
        #get data from the request and insert the record
        name = request.POST["name"]
        address = request.POST["address"]
        try:
            restaurantCollection.insert({"name": name, "address": address})
        except:
            return Response({"ok": "false"})
        return Response({"ok": "true"})
Example #56
0
 def update(r, form):
     if not request.files or 'file' not in request.files:
         return False, {'file': 'Missing image file.'}
     if request.files['file'].content_type != 'image/jpeg':
         return False, {'file': 'Only JPEG images are allowed.'}
     ret = Restaurant.update_entry_image(r, form)
     if ret[0]:
         sio = StringIO(request.files['file'].read())
         img = Image.open(sio)
         # crop to a sqare
         w1, w2 = min(img.size[0],
                      img.size[1]), max(img.size[0], img.size[1])
         d = (w2 - w1) / 2
         if img.size[0] > img.size[1]:
             img = img.crop((d, 0, w2 - d, w1))
         elif img.size[1] > img.size[0]:
             img = img.crop((0, d, w1, w2 - d))
         sz = app.config['ENTRY_PHOTO_SIZE']
         img = img.resize((sz, sz), Image.ANTIALIAS)
         path = os.path.join(app.config['UPLOAD_DIR'], ret[1])
         img.save(path, optimize=True, quality=65)
         if ret[0]:
             return True, {'image': '/uploaded/' + ret[1]}
     return ret
Example #57
0
def all_restaurants_handler():
    #If GET, return all resturant in Database
    if request.method == 'GET':
        restaurants = session.query(Restaurant).all()
        return jsonify(restaurants=(i.serialize for i in restaurants))
    #If POST, make a new resturant and post it in database
    elif request.method == 'POST':
        location = request.args.get('location', '')
        mealType = request.args.get('mealType', '')
        restaurant_info = findARestaurant(mealType, location)

        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'])
            session.add(restaurant)
            session.commit()
            return jsonify(restaurant=restaurant.serialize)
        else:
            return ({
                "error":
                "No Restaurants Found for %s in %s" % (mealType, location)
            })
Example #58
0
    def parse_detail(self, response):
        hxs = HtmlXPathSelector(response)
        shopname = hxs.select('//div[@class="shop-name"]/h1/text()').extract()
        tags = hxs.select('//div[@class="desc-list"]/dl/dd/span/a[contains(@href, "/search/")]/text()').extract()
        address = hxs.select(
            '//dl[@class="shopDeal-Info-address"]/dd/span[@itemprop="street-address"]/text()'
        ).extract()
        # TODO need a func to decode
        flavor_env_service = hxs.select('//div[@class="desc-list"]/dl/dd/em[@class="progress-value"]/text()').extract()
        trans = hxs.select('//div[@class="block-inner desc-list"]/dl/dd/span[@class="J_brief-cont"]/text()').extract()
        # TODO need to remove 更多
        specials = hxs.select(
            '//div[@class="block-inner desc-list"]/dl[@class="J_tags-fold-wrap"]/dd/span/a/text()'
        ).extract()
        recommendations_people = hxs.select('//div[@class="rec-menu"]/span/text()').extract()
        recommendations = hxs.select('//div[@class="rec-menu"]/span/a/text()').extract()
        recommendation_photos = hxs.select('//div[@class="rec-slide-entry"]/ul/li/a/img/@src').extract()
        score = hxs.select('//div[@class="comment-rst"]/span/meta/@content').extract()
        avg_price = hxs.select('//div[@class="comment-rst"]/dl/dd/text()').extract()
        collect = hxs.select('//div[@class="shop-action"]/ul/li/span/text()').extract()[0][1:-2]
        code = hxs.select("//script/text()")[3].re(r"poi: \'(\w+)\'")
        if code:
            code = code[0]
        else:
            code = ""

        if avg_price:
            avg_price = avg_price[0]
        else:
            avg_price = ""

        recs = [recommendations[i] + recommendations_people[i] for i in range(len(recommendations))]
        if len(flavor_env_service) < 3:
            flavor = ""
            env = ""
            service = ""
        else:
            flavor = flavor_env_service[0]
            env = flavor_env_service[0]
            service = flavor_env_service[0]

        if specials:
            if specials[-1] == u"更多":
                specials = specials[:-1]

        num = response.request.meta["num"]

        try:
            print("url is %s, shopname is %s %s" % (response.request.url, shopname[0], datetime.datetime.now()))
            restaurant = Restaurant(
                num=num,
                url=response.request.url,
                shop_name=shopname,
                tags=tags,
                address=address,
                flavor=flavor,
                env=env,
                service=service,
                specials=specials,
                trans=trans,
                recommendations=recs,
                recommendation_photos=recommendation_photos,
                shop_score=score,
                avg_price=avg_price,
                collect=collect,
                code=code,
            )
            restaurant.save()
        except Exception as err:
            print(err)
            file = open("error.log", "w")
            fcntl.flock(file, fcntl.LOCK_EX)
            file.write(response.request.url + "\n")
            fcntl.flock(file, fcntl.LOCK_UN)
            file.close()
Example #59
0
    def test_model_inheritance(self):
        # Regression for #7350, #7202
        # Check that when you create a Parent object with a specific reference
        # to an existent child instance, saving the Parent doesn't duplicate
        # the child. This behaviour is only activated during a raw save - it
        # is mostly relevant to deserialization, but any sort of CORBA style
        # 'narrow()' API would require a similar approach.

        # Create a child-parent-grandparent chain
        place1 = Place(
            name="Guido's House of Pasta",
            address='944 W. Fullerton')
        place1.save_base(raw=True)
        restaurant = Restaurant(
            place_ptr=place1,
            serves_hot_dogs=True,
            serves_pizza=False)
        restaurant.save_base(raw=True)
        italian_restaurant = ItalianRestaurant(
            restaurant_ptr=restaurant,
            serves_gnocchi=True)
        italian_restaurant.save_base(raw=True)

        # Create a child-parent chain with an explicit parent link
        place2 = Place(name='Main St', address='111 Main St')
        place2.save_base(raw=True)
        park = ParkingLot(parent=place2, capacity=100)
        park.save_base(raw=True)

        # Check that no extra parent objects have been created.
        places = list(Place.objects.all())
        self.assertEqual(places, [place1, place2])

        dicts = list(Restaurant.objects.values('name','serves_hot_dogs'))
        self.assertEqual(dicts, [{
            'name': u"Guido's House of Pasta",
            'serves_hot_dogs': True
        }])

        dicts = list(ItalianRestaurant.objects.values(
            'name','serves_hot_dogs','serves_gnocchi'))
        self.assertEqual(dicts, [{
            'name': u"Guido's House of Pasta",
            'serves_gnocchi': True,
            'serves_hot_dogs': True,
        }])

        dicts = list(ParkingLot.objects.values('name','capacity'))
        self.assertEqual(dicts, [{
            'capacity': 100,
            'name': u'Main St',
        }])

        # You can also update objects when using a raw save.
        place1.name = "Guido's All New House of Pasta"
        place1.save_base(raw=True)

        restaurant.serves_hot_dogs = False
        restaurant.save_base(raw=True)

        italian_restaurant.serves_gnocchi = False
        italian_restaurant.save_base(raw=True)

        place2.name='Derelict lot'
        place2.save_base(raw=True)

        park.capacity = 50
        park.save_base(raw=True)

        # No extra parent objects after an update, either.
        places = list(Place.objects.all())
        self.assertEqual(places, [place2, place1])
        self.assertEqual(places[0].name, 'Derelict lot')
        self.assertEqual(places[1].name, "Guido's All New House of Pasta")

        dicts = list(Restaurant.objects.values('name','serves_hot_dogs'))
        self.assertEqual(dicts, [{
            'name': u"Guido's All New House of Pasta",
            'serves_hot_dogs': False,
        }])

        dicts = list(ItalianRestaurant.objects.values(
            'name', 'serves_hot_dogs', 'serves_gnocchi'))
        self.assertEqual(dicts, [{
            'name': u"Guido's All New House of Pasta",
            'serves_gnocchi': False,
            'serves_hot_dogs': False,
        }])

        dicts = list(ParkingLot.objects.values('name','capacity'))
        self.assertEqual(dicts, [{
            'capacity': 50,
            'name': u'Derelict lot',
        }])

        # If you try to raw_save a parent attribute onto a child object,
        # the attribute will be ignored.

        italian_restaurant.name = "Lorenzo's Pasta Hut"
        italian_restaurant.save_base(raw=True)

        # Note that the name has not changed
        # - name is an attribute of Place, not ItalianRestaurant
        dicts = list(ItalianRestaurant.objects.values(
            'name','serves_hot_dogs','serves_gnocchi'))
        self.assertEqual(dicts, [{
            'name': u"Guido's All New House of Pasta",
            'serves_gnocchi': False,
            'serves_hot_dogs': False,
        }])
Example #60
0
class OneToOneTests(TestCase):

    def setUp(self):
        self.p1 = Place(name='Demon Dogs', address='944 W. Fullerton')
        self.p1.save()
        self.p2 = Place(name='Ace Hardware', address='1013 N. Ashland')
        self.p2.save()
        self.r = Restaurant(place=self.p1, serves_hot_dogs=True, serves_pizza=False)
        self.r.save()

    def test_getter(self):
        # A Restaurant can access its place.
        self.assertEqual(repr(self.r.place), '<Place: Demon Dogs the place>')
        # A Place can access its restaurant, if available.
        self.assertEqual(repr(self.p1.restaurant), '<Restaurant: Demon Dogs the restaurant>')
        # p2 doesn't have an associated restaurant.
        self.assertRaises(Restaurant.DoesNotExist, getattr, self.p2, 'restaurant')

    def test_setter(self):
        # Set the place using assignment notation. Because place is the primary
        # key on Restaurant, the save will create a new restaurant
        self.r.place = self.p2
        self.r.save()
        self.assertEqual(repr(self.p2.restaurant), '<Restaurant: Ace Hardware the restaurant>')
        self.assertEqual(repr(self.r.place), '<Place: Ace Hardware the place>')
        self.assertEqual(self.p2.pk, self.r.pk)
        # Set the place back again, using assignment in the reverse direction.
        self.p1.restaurant = self.r
        self.assertEqual(repr(self.p1.restaurant), '<Restaurant: Demon Dogs the restaurant>')
        r = Restaurant.objects.get(pk=self.p1.id)
        self.assertEqual(repr(r.place), '<Place: Demon Dogs the place>')

    def test_manager_all(self):
        # Restaurant.objects.all() just returns the Restaurants, not the Places.
        self.assertQuerysetEqual(Restaurant.objects.all(), [
            '<Restaurant: Demon Dogs the restaurant>',
        ])
        # Place.objects.all() returns all Places, regardless of whether they
        # have Restaurants.
        self.assertQuerysetEqual(Place.objects.order_by('name'), [
            '<Place: Ace Hardware the place>',
            '<Place: Demon Dogs the place>',
        ])

    def test_manager_get(self):
        def assert_get_restaurant(**params):
            self.assertEqual(repr(Restaurant.objects.get(**params)),
                             '<Restaurant: Demon Dogs the restaurant>')
        assert_get_restaurant(place__id__exact=self.p1.pk)
        assert_get_restaurant(place__id=self.p1.pk)
        assert_get_restaurant(place__exact=self.p1.pk)
        assert_get_restaurant(place__exact=self.p1)
        assert_get_restaurant(place=self.p1.pk)
        assert_get_restaurant(place=self.p1)
        assert_get_restaurant(pk=self.p1.pk)
        assert_get_restaurant(place__pk__exact=self.p1.pk)
        assert_get_restaurant(place__pk=self.p1.pk)
        assert_get_restaurant(place__name__startswith="Demon")

        def assert_get_place(**params):
            self.assertEqual(repr(Place.objects.get(**params)),
                             '<Place: Demon Dogs the place>')
        assert_get_place(restaurant__place__exact=self.p1.pk)
        assert_get_place(restaurant__place__exact=self.p1)
        assert_get_place(restaurant__place__pk=self.p1.pk)
        assert_get_place(restaurant__exact=self.p1.pk)
        assert_get_place(restaurant__exact=self.r)
        assert_get_place(restaurant__pk=self.p1.pk)
        assert_get_place(restaurant=self.p1.pk)
        assert_get_place(restaurant=self.r)
        assert_get_place(id__exact=self.p1.pk)
        assert_get_place(pk=self.p1.pk)

    def test_foreign_key(self):
        # Add a Waiter to the Restaurant.
        w = self.r.waiter_set.create(name='Joe')
        w.save()
        self.assertEqual(repr(w), '<Waiter: Joe the waiter at Demon Dogs the restaurant>')
        # Query the waiters
        def assert_filter_waiters(**params):
            self.assertQuerysetEqual(Waiter.objects.filter(**params), [
                '<Waiter: Joe the waiter at Demon Dogs the restaurant>'
            ])
        assert_filter_waiters(restaurant__place__exact=self.p1.pk)
        assert_filter_waiters(restaurant__place__exact=self.p1)
        assert_filter_waiters(restaurant__place__pk=self.p1.pk)
        assert_filter_waiters(restaurant__exact=self.p1.pk)
        assert_filter_waiters(restaurant__exact=self.p1)
        assert_filter_waiters(restaurant__pk=self.p1.pk)
        assert_filter_waiters(restaurant=self.p1.pk)
        assert_filter_waiters(restaurant=self.r)
        assert_filter_waiters(id__exact=self.p1.pk)
        assert_filter_waiters(pk=self.p1.pk)
        # Delete the restaurant; the waiter should also be removed
        r = Restaurant.objects.get(pk=self.p1.pk)
        r.delete()
        self.assertEqual(Waiter.objects.count(), 0)

    def test_multiple_o2o(self):
        # One-to-one fields still work if you create your own primary key
        o1 = ManualPrimaryKey(primary_key="abc123", name="primary")
        o1.save()
        o2 = RelatedModel(link=o1, name="secondary")
        o2.save()

        # You can have multiple one-to-one fields on a model, too.
        x1 = MultiModel(link1=self.p1, link2=o1, name="x1")
        x1.save()
        self.assertEqual(repr(o1.multimodel), '<MultiModel: Multimodel x1>')
        # This will fail because each one-to-one field must be unique (and
        # link2=o1 was used for x1, above).
        sid = transaction.savepoint()
        mm = MultiModel(link1=self.p2, link2=o1, name="x1")
        self.assertRaises(IntegrityError, mm.save)
        transaction.savepoint_rollback(sid)