def get(self, style=None): if style is not None and len(style) > 0: # FIXME: Un-urlize the string style = re.sub(r'%20', ' ', style) style = re.sub(r'%28', '(', style) style = re.sub(r'%29', ')', style) # Find all the styles by creating a set from all beers b/c # app engine won't let us grab just this column from a table beers = __weekly_brews__(Beer.all().filter("style = ", style)).order("name") template_values = {'beers' : beers, 'search' : style} path = os.path.join(os.path.dirname(__file__), 'templates/beers.html') self.response.out.write(template.render(path, template_values)) return # Use a list to preserve ordering styles = [] tmp = __weekly_brews__(Beer.all()) for beer in tmp: styles.append(beer.style) styles = list(set(styles)) styles.sort() template_values = {'styles' : styles} path = os.path.join(os.path.dirname(__file__), 'templates/search.html') self.response.out.write(template.render(path, template_values))
def test_init_menus(self): api_dict = { "TestBar": self.MockAPIPlan( self.mockAPI, ["shit", "shit", "Stone", "Stone", "Founders"]).executor(), } good_menu1 = Menu("TestBar", [ MenuSection("1", "Title1", [Beer("name Stone", "style", 8, "brewery")]) ]) good_menu2 = Menu("TestBar", [ MenuSection("1", "Title1", [Beer("name Founders", "style", 8, "brewery")]) ]) mm = MenuManager(api_dict=api_dict) self.assertEqual({}, mm.find_good_bars()) mm.update_menus() self.assertEqual({}, mm.find_good_bars()) mm.update_menus() self.assertEqual({"TestBar": good_menu1}, mm.find_good_bars()) mm.update_menus() self.assertEqual({}, mm.find_good_bars()) mm.update_menus() self.assertEqual({"TestBar": good_menu2}, mm.find_good_bars())
def test_MenuSectionEquals(self): section_1 = MenuSection("123", "Beers") section_2 = MenuSection("123", "Beers") for i in range(3): section_1.beers.append(Beer(str(i), str(i), i, str(i))) section_2.beers.append(Beer(str(i), str(i), i, str(i))) self.assertEqual(section_1, section_2, "Should be equal")
def test_GoodBeers(self): section = MenuSection("123", "Beers") section.beers.append(Beer("One beer", "From", 18.0, "There")) section.beers.append(Beer("Breakfast Stout", "From", 9.0, "Founders")) good_beers = section.good_beers() self.assertEqual(len(good_beers), 1) self.assertEqual(good_beers[0], Beer("Breakfast Stout", "From", 9.0, "Founders"))
def test_FromDict(self): b = Beer("Breakfast stout", "Stout", 8.0, "Founders") b_dict = { "name": "Breakfast stout", "style": "Stout", "abv": 8.0, "brewery": "Founders" } self.assertEqual(b, Beer().from_dict(b_dict))
def test_ToDict(self): b = Beer("Breakfast stout", "Stout", 8.0, "Founders") b_dict = { "name": "Breakfast stout", "style": "Stout", "abv": 8.0, "brewery": "Founders" } self.assertEqual(b.to_dict(), b_dict)
def test_BeerUnEquals(self): b1 = Beer("Breakfast stout", "Stout", 8.0, "Founders") b2 = Beer("Breakfast Stout", "Stout", 8.0, "Founders") b3 = Beer("Breakfast stout", "IPA", 8.0, "Founders") b4 = Beer("Breakfast stout", "Stout", 7.0, "Founders") b5 = Beer("Breakfast stout", "Stout", 8.0, "Stone") self.assertNotEqual(b1, b2) self.assertNotEqual(b1, b3) self.assertNotEqual(b1, b4) self.assertNotEqual(b1, b5)
def test_IsNotWorthIt(self): b1 = Beer("Breakfast stout", "Stout", 5.0, "No Brand") b2 = Beer("Breakfast stout", "Stout", 8.0, "Some Brand") b3 = Beer("Breakfast stout", "Stout", 6.0, "Founders") self.assertEqual(b1.is_worth_it(), False) self.assertEqual(b2.is_worth_it(), False) self.assertEqual(b3.is_worth_it(), False)
def test_Constructor(self): section_1 = MenuSection("123", "Beers") section_2 = MenuSection("124", "More beers", [Beer("B", "EE", 1.0, "R")]) self.assertEqual(section_1.section_id, "123") self.assertEqual(section_1.title, "Beers") self.assertEqual(len(section_1.beers), 0) self.assertEqual(section_2.section_id, "124") self.assertEqual(section_2.title, "More beers") self.assertEqual(len(section_2.beers), 1) self.assertEqual(section_2.beers[0], Beer("B", "EE", 1.0, "R"))
def test_MenuSectionUnequals(self): section_1 = MenuSection("123", "Beers") section_2 = MenuSection("124", "Beers") section_3 = MenuSection("123", "beers") section_4 = MenuSection("124", "beers") for i in range(3): section_1.beers.append(Beer(str(i), str(i), i, str(i))) section_2.beers.append(Beer(str(i), str(i), i, str(i))) section_3.beers.append(Beer(str(i), str(i), i, str(i))) section_1.beers.append(Beer("different", "section", 5.0, "brew")) self.assertNotEqual(section_1, section_2, "Should not be equal") self.assertNotEqual(section_1, section_3, "Should not be equal") self.assertNotEqual(section_1, section_4, "Should not be equal")
def post(self): json_string = self.request.body dict_object = json.loads(json_string) beer_name = dict_object['beerName'] beer_style = dict_object['beerStyle'] beer_price = float(dict_object['beerPrice']) beer_abv = float(dict_object['beerAbv']) beer_ibus = int(dict_object['beerIbus']) beer_srm = int(dict_object['beerSrm']) beer_on_tap = bool(dict_object['beerOnTap']) beer_tap_list_image = dict_object['beerTapListImage'] beer_description = dict_object['beerDescription'] beer_description_image = dict_object['beerDescriptionImage'] same_name = Beer.query(Beer.name == beer_name).fetch() if not same_name: #NDB storing beer = Beer(name=beer_name, style=beer_style, tap_list_image=beer_tap_list_image, description=beer_description, description_image=beer_description_image, price=beer_price, abv=beer_abv, ibus=beer_ibus, srm=beer_srm, on_tap=beer_on_tap) beer_key = beer.put() beer_id = str(beer_key.id()) res = { "msg": "Beer successfully added", "success": True, "beer_id": beer_id } self.response.out.write(json.dumps(res)) else: res = { "msg": "That beer already exists in the inventory or something went wrong. Please try again.", "success": False } self.response.out.write(json.dumps(res))
def get(self): beer_id = int(self.request.get('beerId', 0)) beer = Beer.get_by_id(beer_id) if beer != None: date = beer.creation_date date_string = date.strftime('%m/%d/%Y') beer_data = { 'id': beer.key.id(), 'name': beer.name, 'style': beer.style, 'tap_list_image': beer.tap_list_image, 'description': beer.description, 'description_image': beer.description_image, 'price': beer.price, 'abv': beer.abv, 'ibus': beer.ibus, 'srm': beer.srm, 'on_tap': beer.on_tap, 'review': beer.review, 'review_count': beer.review_count, 'creation_date': date_string } else: beer_data = {} self.response.out.write(json.dumps(beer_data))
def get(self): self.response.headers['Content-Type'] = 'application/json' beer_query = Beer.query().order(Beer.name) beers = beer_query.fetch() beer_list = [] for beer in beers: date = beer.creation_date date_string = date.strftime('%m/%d/%Y') beer_list.append({ 'id': beer.key.id(), 'key' : str(beer.key), 'name': beer.name, 'style': beer.style, 'tap_list_image': beer.tap_list_image, 'description': beer.description, 'description_image' : beer.description_image, 'price' : beer.price, 'abv' : beer.abv, 'ibus' : beer.ibus, 'srm' : beer.srm, 'on_tap' : beer.on_tap, 'review' : beer.review, 'review_count' : beer.review_count, 'creation_date' : date_string }) self.response.out.write(json.dumps(beer_list))
def get(self): beers = __weekly_brews__(Beer.all().filter("type = ", self.type())).order("name") template_values = {'beers' : beers, 'type' : self.type()} # FIXME: This template sucks b/c it has 4 loops that are duplicates path = os.path.join(os.path.dirname(__file__), 'templates/type.html') self.response.out.write(template.render(path, template_values))
class TestTelegramBotUtil(unittest.TestCase): beer_1 = Beer("Breakfast Stout", "Stout", "8.6", "Founders") beer_2 = Beer("Stone IPA", "IPA", "5.6", "Stone") section_1 = MenuSection("111", "On Tap (2 bier)", [beer_1, beer_2]) empty_section = MenuSection("222", "Empty", []) menu_1 = Menu("TAP", [section_1, empty_section]) menu_2 = Menu("FooBar", [section_1, empty_section]) beer_1_text = "Breakfast Stout\n" \ "8.6% ABV\n" \ "Stout\n" \ "Founders\n" beer_2_text = "Stone IPA\n" \ "5.6% ABV\n" \ "IPA\n" \ "Stone\n" section_1_text = "_On Tap_ (2 Beers)\n" \ " ---Beer 1---\n" \ "{}" \ " ---Beer 2---\n" \ "{}".format(beer_1_text, beer_2_text) menu_1_text = "*TAP*\n" \ "{}".format(section_1_text) menu_2_text = "*FooBar*\n" \ "{}".format(section_1_text) def test_beer_in_markdown(self): actual_text = util.beer_to_markdown(self.beer_1) self.assertEqual(actual_text, self.beer_1_text) def test_menusection_in_markdown(self): actual_text = util.section_to_markdown(self.section_1) self.assertEqual(actual_text, self.section_1_text) def test_menu_in_markdown(self): actual_text = util.menu_to_markdown(self.menu_1) self.assertEqual(actual_text, self.menu_1_text) def test_multiple_menus_in_markdown(self): actual_text = util.multiple_menus_to_markdown({ "TAP": self.menu_1, "FooBar": self.menu_2 }) self.assertEqual(actual_text, self.menu_1_text + "\n" + self.menu_2_text)
def request_menu(): logging.info("Retrieving TAP Craft Beer Menu") try: # Get menu location headers = { 'Accept-Language': 'en-GB,en-US;q=0.9,en;q=0.8', 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.186 Safari/537.36', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8', } response1 = requests.get('http://menu.tapthat.com.sg/', headers=headers) # print(response1.content) response_string = response1.content.decode('utf-8') groups = re.search( 'PreloadEmbedMenu\("menu-container",([0-9]+),([0-9]+)\)', response_string) # print(groups[1], groups[2]) # Retrieve menu response2 = requests.get( 'https://business.untappd.com/locations/{}/themes/{}/js'.format( groups.group(1), groups.group(2)), headers=headers) # print(response.content) menu_html = str(response2.content) menu_html = ' '.join( menu_html.replace('\\n', '').replace('\\', '').split()) menu_html = html.unescape(menu_html) # print(menu_html) beer_regex = re.compile( '<!-- Beer Name \+ Style -->.+?<\/span>(.+?)\s<\/a>.+?item-title-color">(.+?)<\/span>.+?"abv">(.+?)%\sABV', re.DOTALL) beer_groups = beer_regex.finditer(menu_html) beers = [] for beer_group in beer_groups: beers.append( Beer(beer_group.group(1), beer_group.group(2), float(beer_group.group(3)))) logging.info("Retrieved {} beers from Tap Craft Beer.".format( len(beers))) return beers except: logging.error("Error getting Tap Craft Beer menu: {}".format( sys.exc_info()[0])) traceback.print_exc() return []
def parse_beer_data(beers_data): beer_dicts = [] variables = [x for x in dir(Beer) if not (x.startswith('_'))] for b in beers_data: # print json.dumps(b) bb = Beer(b) beer_dict = dict((name, getattr(bb, name)) for name in variables) beer_dicts.append(beer_dict) return beer_dicts
def get(self): # Have to filter name afterwards b/c datastore requires the inequality # operators to have a order FIRST if there is going to be any order # clauses at all (see datastore docs) drafts = __weekly_brews__(Beer.all().filter("type = ", "Draft")).order("name") bottles = __weekly_brews__(Beer.all().filter("type = ", "Bottle")).order("name") cans = __weekly_brews__(Beer.all().filter("type = ", "Can")).order("name") casks = __weekly_brews__(Beer.all().filter("type = ", "Cask")).order("name") beers = {} beers['drafts'] = drafts beers['bottles'] = bottles beers['cans'] = cans beers['casks'] = casks template_values = {'beers' : beers} # FIXME: This template sucks b/c it has 4 loops that are duplicates path = os.path.join(os.path.dirname(__file__), 'templates/index.html') self.response.out.write(template.render(path, template_values))
def post(self, name): name = self.request.get('name') if name is None or not len(name): self.redirect("/search") return beers = __weekly_brews__(Beer.all().filter("name = ", name)) template_values = {'beers' : beers} path = os.path.join(os.path.dirname(__file__), 'templates/beers.html') self.response.out.write(template.render(path, template_values))
def get(self): self.response.headers['Content-Type'] = 'application/json' order_query = Order.query().order(-Order.timestamp) orders = order_query.fetch() order_list = [] for order in orders: date = order.timestamp date_string = date.strftime('%m/%d/%Y %H:%M:%S') order_beer_query = OrderBeer.query(OrderBeer.order_id == order.key. id()).order(-OrderBeer.quantity) order_beers = order_beer_query.fetch() order_beer_list = [] for order_beer in order_beers: beer = Beer.get_by_id(order_beer.beer_id) beer_list = "" if beer != None: beer_name = beer.name else: beer_name = "Unknown beer id " + beer_id order_beer_list.append({ 'id': order_beer.beer_id, 'beer_name': beer_name, 'quantity': order_beer.quantity }) customers = User.query( User.fb_user_id == order.fb_user_id).fetch() customer_name = "" for customer in customers: customer_name = customer.name order_list.append({ 'id': order.key.id(), 'order_total': order.order_total, 'customer_name': customer_name, 'user_id': order.fb_user_id, 'status': order.status, 'reward_id': order.reward_id, 'discount': order.discount, 'invoice_number': order.invoice_number, 'timestamp': date_string, 'details': order_beer_list }) self.response.out.write(json.dumps(order_list))
def test_FromDict(self): section = MenuSection("123", "Beers") section.beers.append(Beer("One beer", "From", 18.0, "There")) section.beers.append(Beer("Two beer", "From", 9.0, "Here")) section_dict = { "section_id": "123", "title": "Beers", "beers": [{ "name": "One beer", "style": "From", "abv": 18.0, "brewery": "There" }, { "name": "Two beer", "style": "From", "abv": 9.0, "brewery": "Here" }] } self.assertEqual(section, MenuSection().from_dict(section_dict))
def get(self): self.response.headers['Content-Type'] = 'application/json' user_id = self.request.get('userId', 0) limit = int(self.request.get('limit', 3)) order_query = Order.query( Order.fb_user_id == user_id).order(-Order.timestamp) orders = order_query.fetch(limit) order_list = [] for order in orders: date = order.timestamp # Please we need to use only 1 format! date_string = date.strftime('%m/%d/%Y %H:%M:%S') order_beer_query = OrderBeer.query(OrderBeer.order_id == order.key. id()).order(-OrderBeer.quantity) order_beers = order_beer_query.fetch() order_beer_list = [] for order_beer in order_beers: beer = Beer.get_by_id(order_beer.beer_id) if beer != None: beer_name = beer.name else: beer_name = "Unknown beer id " + beer_id order_beer_list.append({ 'id': order_beer.beer_id, 'beer_name': beer_name, 'quantity': order_beer.quantity }) order_list.append({ 'id': order.key.id(), 'order_total': order.order_total, 'user_id': order.fb_user_id, 'status': order.status, 'reward_id': order.reward_id, 'discount': order.discount, 'invoice_number': order.invoice_number, 'timestamp': date_string, 'details': order_beer_list }) self.response.out.write(json.dumps(order_list))
def build_menu_from_html(self, page): tree = html.document_fromstring(page) m = Menu(self.bar_name) # Get all menu sections sections = tree.find_class("menu-section") for section in sections: # Get section details section_id_string = section.get("id") section_id = re.search("section_(.+?)$", section_id_string).group(1) title = self.sanitize_markdown_characters( section.find_class("menu-section-header")[0].text_content()) beer_list = section.find_class("menu-section-list") beers = beer_list[0].getchildren() # If not all beers are loaded if len(section.find_class("show-more-section")) > 0: logging.debug( "Loading more beers for {}.".format(section_id_string)) beers += self.load_section(section_id) # There are beers in this section if len(beers) > 0: ms = MenuSection(section_id, title) for beer in beers: details = beer.find_class("beer-details")[0] h5, h6 = details.getchildren() name, style = h5.getchildren() abv = h6.getchildren()[0] brewery = h6.getchildren()[0].getchildren()[0] ms.beers.append( Beer( self.sanitize_markdown_characters( name.text_content()), self.sanitize_markdown_characters( style.text_content()), self.sanitize_markdown_characters( self.get_abv_from_span(abv.text_content())), self.sanitize_markdown_characters( brewery.text_content()))) m.sections.append(ms) return m
def post(self): json_string = self.request.body dict_object = json.loads(json_string) review = int(dict_object['review']) beer_id = int(dict_object['beer_id']) beer = Beer.get_by_id(beer_id) if beer != None: beer.review_sum = beer.review_sum + review beer.review_count = beer.review_count + 1 beer.review = beer.review_sum / beer.review_count beer.put() self.response.set_status(200) else: self.response.set_status(500)
def post(self): json_string = self.request.body dict_object = json.loads(json_string) beer_id = int( dict_object['beerId'] ) beer_name = dict_object['beerName'] beer_style = dict_object['beerStyle'] beer_price = float( dict_object['beerPrice'] ) beer_abv = float( dict_object['beerAbv'] ) beer_ibus = int( dict_object['beerIbus'] ) beer_srm = int( dict_object['beerSrm'] ) beer_on_tap = bool( dict_object['beerOnTap'] ) beer_tap_list_image = dict_object['beerTapListImage'] beer_description = dict_object['beerDescription'] beer_description_image = dict_object['beerDescriptionImage'] beer = Beer.get_by_id(beer_id) if beer != None: beer.name = beer_name beer.style = beer_style beer.price = beer_price beer.abv = beer_abv beer.ibus = beer_ibus beer.srm = beer_srm beer.on_tap = beer_on_tap beer.tap_list_image = beer_tap_list_image beer.description = beer_description beer.description_image = beer_description_image beer.put() res = { "msg" : "Beer successfully updated", "success": True, "beer_id" : beer_id } self.response.out.write(json.dumps(res)) else: res = { "msg" : "Oops! Something went wrong. Please try again.", "success": False, "beer_id" : beer_id } self.response.out.write(json.dumps(res))
def text_order(self, order_beers, user_id): account_sid = "" auth_token = "" client = Client(account_sid, auth_token) customers = User.query(User.fb_user_id == user_id).fetch() for customer in customers: customer_name = customer.name beer_list = "" for beer in order_beers: beer_name = Beer.get_by_id(int(beer['id'])).name beer_quantity = beer['quantity'] beer = '\n{} x{}'.format(beer_name, beer_quantity) beer_list += beer; msg_body = 'Beer Order for {}! {}'.format(customer_name, beer_list) bartending_employees = Employee.query(Employee.bartending == True).fetch() for employee in bartending_employees: msg_to = "+1"+employee.phone rv = client.messages.create(to=msg_to, from_="+15126400776 ",body=msg_body)
def post(self): json_string = self.request.body dict_object = json.loads(json_string) beer_id = int(dict_object['beerId']) beer = Beer.get_by_id(beer_id) if beer != None: beer.key.delete() res = { "msg": "Beer successfully deleted", "success": True, "beer_id": beer_id } self.response.out.write(json.dumps(res)) else: res = { "msg": "Oops! Something went wrong. Please try again.", "success": False, "beer_id": beer_id } self.response.out.write(json.dumps(res))
def test_IsWorthIt(self): b1 = Beer("Breakfast stout", "Stout", 8.0, "Founders") b2 = Beer("Founders Breakfast stout", "Stout", 8.0, "None") self.assertEqual(b1.is_worth_it(), True) self.assertEqual(b2.is_worth_it(), True)
def get_model(self, param): return Beer(param)
def test_repr(self): b = Beer("Breakfast stout", "Stout", 8.0, "Founders") self.assertEqual(str(b), "Beer(name=Breakfast stout, style=Stout, abv=8.0, brewery=Founders)")
def test_BeerEquals(self): b1 = Beer("Breakfast stout", "Stout", 8.0, "Founders") b2 = Beer("Breakfast stout", "Stout", 8.0, "Founders") self.assertEqual(b1, b2)
def mockAPI(self, beername=""): return Menu("TestBar", [ MenuSection("1", "Title1", [Beer("name " + beername, "style", 8, "brewery")]) ])
def make_beer(self, data, **kwargs): beer_args = {'id': str(uuid1()), **data} return Beer(**beer_args)
def make_beer(self, data, **kwargs): return Beer(**data)