def delete_store(store_id): # Remove the store from the database Store.get_by_id(store_id).remove_from_mongo() # return the user to '/stores/' return redirect(url_for('.index'))
def get(self): try: """ Obtains a Product given the corresponding filters on the JSON json example: { "store_name":"Buy and sell books", } :returns example: { "success": true, "stores":[ { "store_id":1, "store_name":"Buy and sell books", "store_address": "1st Avenue", }, ... ] } """ store = Store() json = request.json ans = [] if json is not None: conditions = conditions_builder(json) ans = store.get_store(conditions) return {'success': True, 'stores': ans} except Exception as e: print(e) return {'success': False, 'Error': str(e)}
def test_print_items_in_cart(self): list = self.generate_data() store = Store(list) for each_item in list: store.add_cart(each_item, 1) print_items_in_cart(store) self.assertEqual(list, store.get_cart_items())
def post(self): tdc = TestDataCreationHandler() tdc.create_member(self['owner_email'], self['owner_name'], self['owner_phone'], 'owner') tdc.create_member(self['manager_email'], self['manager_name'], self['manager_phone'], 'manager') store_obj = Store() store_obj.name = self['store_name'] store_obj.owner = self['owner_email'] store_obj.manager = self['manager_email'] store_obj.location = db.GeoPt(self['store_lat'],self['store_long']) store_obj.address = " ".join(self['store_address'].split("\n")) store_obj.billing_address = " ".join(self['store_billing_address'].split("\n")) store_obj.put() appliances_csv = self['appliances_csv'] appliances = appliances_csv.splitlines() appliance_index = [index.strip("\"") for index in str(appliances[0]).split(',')] for appliance in appliances[1:]: appliance = [detail.strip("\"") for detail in str(appliance).split(',')] appliance_obj = Appliance() appliance_obj.name = appliance[appliance_index.index("Name of Appliance")] appliance_obj.serial_num = appliance[appliance_index.index("Serial #")] appliance_obj.model = appliance[appliance_index.index("Model #")] appliance_obj.manufacturer = appliance[appliance_index.index("Manufacturer Name")] appliance_obj.last_repair_date = self.get_appliance_form_date("Last Repair Date (if you know it)", appliance, appliance_index) appliance_obj.installed_on = self.get_appliance_form_date("Installed on (if known)", appliance, appliance_index) appliance_obj.warranty = self.get_appliance_form_date("Is it in warranty (if known)", appliance, appliance_index) appliance_obj.store = store_obj appliance_obj.put()
def get(self): store = get_store() if store is None: store = Store(key_name=STORE_KEY, name='My Store', description='This is my store', declaration='Write your declaration') store.put() memcache.delete(STORE_KEY) memcache.set(STORE_KEY, store) self.redirect('/store')
def test_insert_store(): store = Store() store_to_db = { 'store_name': 'book seller No. 1', 'store_street': '5th Avenue', 'store_mail': '*****@*****.**', 'store_phone_number': '5522887799', 'store_city': 'City 1', 'store_state': 'State 1', 'store_zip_code': '99999', } ans = store.insert_store(store_to_db) assert ans['success']
def getStore(self, idstore): """method class for retrieve a store according to id """ if idstore > 100: store = Store(101, "unknown") return store elif idstore == "100": store = Store(101, "unknown") return store else: cur = self.cur cur.execute("SELECT * FROM `store`" " WHERE id = '" + str(idstore) + "'") row = cur.fetchall() store = Store(row[0][0], row[0][1]) return store
def get_appliances_for_logged_in_user(self): email = self.session['email'] role = self.session['role'] appliances = [] stores = Store.all().filter(role + ' =', email) for store in stores: appliances.extend([appliance for appliance in Appliance.all().filter('store =', store).fetch(100)]) return appliances
def post(self): try: """ inserts a store on the DB given by the JSON, for more information of the model refer to this project on model/store :returns example: { "success": True, "product": store_of_product } """ store = Store() json = request.json store.insert_store(json) return {'success': True, 'store': json} except Exception as e: return {'success': False, 'Error': str(e)}
def getStoreId(self, storename): """method class for retrieve a store according to name """ try: cur = self.cur cur.execute("SELECT * FROM `store`" " WHERE nom = '" + str(storename) + "'") row = cur.fetchall() if len(row) == 0: store = Store(101, "unknown") return store else: store = Store(row[0][0], row[0][1]) return store except mysql.connector.errors.ProgrammingError as err: print(err.msg) store = Store(101, "unknown") return store
def does_user_own_appliance(self): email = self.session['email'] role = self.session['role'] stores = Store.all().filter(role + ' =', email) appliance = Appliance.get_by_id(long(self['appliance'])) for store in stores: if appliance.store.key().id() == store.key().id(): return True return False
def main(args=None): """The main routine.""" if args is None: args = sys.argv[1:] list = parse_items_from_file(args[0]) store = Store(list) store_menu(store)
def post(self): loc = self['location'].split(',') store = Store() store.name = self['name'] store.location = db.GeoPt(loc[0], loc[1]) store.manager = self['manager'] store.owner = self['owner'] store.put()
def get(self): stores = [] for store_bson in self.stores_collection.find(): #TODO refactor out into mapper store = Store(str(store_bson['_id']), store_bson['store_type'], store_bson['location_quick_name'], Location(store_bson['location']['type'], store_bson['location']['coordinates'])) stores.append(store) return stores
def put(self): try: """ updates a store on the DB with the given JSON values and filtered by store_id, for more information of the model refer to this project on model/store :returns example: { "success": True, "product": store_of_product } """ store = Store() json = request.json print(request.json) conditions = conditions_builder({'store_id':json['store_id']}) json.pop('store_id', None) store.update_store(json, conditions=conditions) return {'success': True, 'store': json} except Exception as e: return {'success': False, 'Error': str(e)}
def create_store(): # If POST then the user has visited the form already and submitted a new store # After saving the new store, the user is forwarded back to '/stores/' if request.method == 'POST': name = request.form['name'] url_prefix = request.form['url_prefix'] tag_name = request.form['tag_name'] query = json.loads(request.form['query'].replace("'", "\"")) Store(name, url_prefix, tag_name, query).save_to_mongo() return redirect(url_for('.index')) # If no POST then user is givne the new store form to complete and submit return render_template('/stores/new_store.html')
def convert_to_store(stores: List) -> List[Store]: """ Convert list of dictionnaries to list of objects. :param stores: list containing dictionnaries :return: List[Store] """ store_list: List[Store] = [] for store in stores: if (store.get('name') and store.get('url') and store.get('products') > 100): store_list.append(Store(store['name'], store['url'])) return store_list
def get_work_orders_for_logged_in_user(self): email = self.session['email'] workorders = [] if is_store_login(self): appliances = [] stores = Store.all().filter(self.session['role'] + ' =', email) for store in stores: appliances.extend([appliance.id for appliance in Appliance.all().filter('store =', store).fetch(100)]) for appliance in appliances: workorders.extend([wo for wo in WorkOrder.all().filter('appliance =', str(appliance))]) elif is_provider_login(self): providers = [p for p in Provider.all().fetch(100) if p.owner.key().name() == email] for provider in providers: workorders.extend([wo for wo in WorkOrder.all().filter('provider =', str(provider.key().id()))]) return workorders
def get(self): email = self.session["email"] role = self.session["role"] stores = Store.all().filter(role + " =", email).order("name") if stores.count() > 1: self.session["bottom_menu_1"] = "Stores" elif stores.count() == 1: self.session["bottom_menu_1"] = "Appliances" store_appliances = [] for store in stores: appliances = [appliance for appliance in Appliance.all().filter("store =", store).fetch(100)] store_appliances.append((store, appliances)) path = "appliances.html" template_values = {"store_appliances": store_appliances, "count": len(store_appliances)} self.write(self.get_rendered_html(path, template_values), 200)
def test_remove_item_from_cart(self): list = self.generate_data() expected_remove_list = [] for each_item in list: expected_remove_list.append(each_item) toBeRemoved = expected_remove_list[0] del expected_remove_list[0] store = Store(list) for each_item in list: store.add_cart(each_item, 1) store.remove_from_cart(toBeRemoved) self.assertEqual(expected_remove_list, store.get_cart_items())
def index(): # Get a list of all stores from database stores = Store.all() # Get admin email address from environment variables admin_email = os.getenv("ADMIN") # Prepare a list of stores for store in stores: print(store.name) # Present user with page containing list of stores with admin email in memory return render_template('stores/index.html', stores=stores, admin=admin_email)
def create_alert(): if request.method == 'POST': item_url = request.form['item_url'] store = Store.find_by_url(item_url) item = Item(item_url, store.tag_name, store.query) item.load_price() item.save_to_mongo() alert_name = request.form['name'] price_limit = request.form['price_limit'] Alert(alert_name, item._id, price_limit, session["email"]).save_to_mongo() # What happens if it's a GET request return render_template("alerts/new_alert.html")
def enrollment_store(store_name, description, score, average_price, picture_url): try: add_store = Store(name=store_name, description=description, average_price=average_price, picture=picture_url, average_score=score) session.add(add_store) session.commit() return {"message": "success for create store information"} except SQLAlchemyError: session.rollback() return abort(500, "database_error")
def new_alert(): # If POST method included in the request, a new alert needs to be saved # After saving the new alert from the POST, user redirected to their alerts list at '/' if request.method == 'POST': alert_name = request.form['name'] item_url = request.form['item_url'] price_limit = float(request.form['price_limit']) store = Store.find_by_url(item_url) item = Item(item_url, store.tag_name, store.query) item.load_price() item.save_to_mongo() Alert(alert_name, item._id, price_limit, session['email']).save_to_mongo() return redirect(url_for('.index')) # If POST was not included in the request, form is provided for user to enter new alert information return render_template('/alerts/new_alert.html')
def edit_store(store_id): # Getting store from database store = Store.get_by_id(store_id) # If POST then edit form has been completed already # After store edit form saved, user redirected to '/stores/' if request.method == 'POST': name = request.form['name'] url_prefix = request.form['url_prefix'] tag_name = request.form['tag_name'] query = json.loads(request.form['query'].replace("'", "\"")) store.name = name store.url_prefix = url_prefix store.tag_name = tag_name store.query = query store.save_to_mongo() return redirect(url_for('.index')) # If no POST, then user is presented with the edit store form to be completed. return render_template('stores/edit_store.html', store=store)
def post(self): data = request.get_json() store_bson = self.stores_collection.find_one({ 'store_type': data['store_type'], 'location.coordinates': data['location']['coordinates'] }) if store_bson: return {'message': 'item exists'}, 400 new_store = { '_id': bson.ObjectId(), 'store_type': data['store_type'], 'location': data['location'], 'location_quick_name': data['location_quick_name'] } self.stores_collection.insert_one(new_store) store = Store(str(new_store['_id']), new_store['store_type'], new_store['location_quick_name'], Location(new_store['location']['type'], new_store['location']['coordinates'])) return store
def store_mapper(member, role_name): fields = member['fields'] store_obj = Store.all().filter('airtable_id =', fields['Store ID']).get() if not store_obj: store_obj = Store() store_obj.name = fields['Store Name'] store_obj.location = db.GeoPt(fields['Latitude'],fields['Longitude']) store_obj.address = fields['Store Address'] store_obj.billing_address = fields['Billing Address'] store_obj.owner = obj_map[fields['Store Owner'][0]].key().name() store_obj.manager = obj_map[fields['Store Manager'][0]].key().name() store_obj.airtable_id = fields['Store ID'] store_obj.put() obj_map[member['id']] = store_obj
def search(user_id): result = {} q_arg = request.args.get("q") sort_arg = request.args.get("sort") p_arg = request.args.get("p") category_arg = request.args.get("category") location_arg = request.args.get("location") zone_arg = request.args.get("zone") area_arg = request.args.get("area") filter_arg = request.args.get("filter") category = Table("category") merchant = Table("merchant") store = Table("store") q = "" haveLocation = False if location_arg: locations = location_arg.split(",") try: locations[0] = Decimal(locations[0]) locations[1] = Decimal(locations[1]) q = ("SELECT *, (6371*acos(cos(radians(" + str(locations[0]) + "))*cos(radians(lat))*cos(radians(`long`)-radians(" + str(locations[1]) + "))+sin(radians(" + str(locations[0]) + "))*sin(radians(lat)))) AS distance") haveLocation = True except (ValueError, DecimalException): abort(400) else: q = "SELECT *" q += " FROM store" if sort_arg: if str(sort_arg) == "popular": c = "SELECT store_id, COUNT(*) as count FROM transaction GROUP BY store_id" q += " LEFT JOIN (" + c + ") AS count ON count.store_id = id" elif str(sort_arg) == "match": pass wheres = [] if category_arg: q2 = Query.from_(category).select("*").where( category.id == category_arg) cursor = get_db().cursor() cursor.execute(str(q2)) record = cursor.fetchone() cursor.close() if record == None: abort(400) else: result["category"] = Category(record) q2 = (Query.from_(merchant).select( merchant.id).where(merchant.category_id == category_arg)) cursor = get_db().cursor() cursor.execute(str(q2)) merchants = cursor.fetchall() cursor.close() wheres.append("store.merchant_id IN (" + ",".join(str(i[0]) for i in merchants) + ")") if q_arg: wheres.append("store.name LIKE '%" + q_arg + "%'") if zone_arg: wheres.append("store.zone = " + zone_arg) if area_arg: wheres.append("store.area_level_2 = '" + area_arg + "'") q += " WHERE " + wheres[0] for i in wheres[1:]: q += " AND " + i if filter_arg: filters = filter_arg.split(";") for i in filters: splits = i.split(",") if splits[0] == "distance": if haveLocation: q += (" HAVING distance BETWEEN " + str(splits[1]) + " AND " + str(splits[2])) if sort_arg: if str(sort_arg) == "popular": q += " ORDER BY count.count DESC" elif str(sort_arg) == "distance": if haveLocation: q += " ORDER BY distance ASC" if p_arg: try: p_arg = int(p_arg) q += " LIMIT " + str((p_arg - 1) * 10) + ", 10" except ValueError: return abort(400) cursor = get_db().cursor() cursor.execute(str(q)) records = cursor.fetchall() cursor.close() newStore = lambda a: Store(a, 0) if not category_arg: newStore = lambda a: Store(a, 0) q = "INSERT INTO keyword(content, category, area, user_id, time, records" if zone_arg: q += ", zone" q += (") VALUES('" + q_arg + "', '" + category_arg + "', '" + area_arg + "','" + str(user_id[0]) + "'," + str(int(time.time() * 1000)) + "," + str(len(records))) if zone_arg: q += "," + zone_arg q += ")" cursor = get_db().cursor() cursor.execute(q) cursor.close() get_db().commit() records = list(map(newStore, records)) result["stores"] = records return jsonify(**result)
def create_stores(self, manager2, manager, owner): stores = [] store = Store(name="McDonald's", location=db.GeoPt(40.7131116,-74.015359), manager=manager2.key().name(), owner=owner.key().name(), address="McDonald's, Logn Gate Shopping Center, 4396 Montgomery Rd, Ellicott City, MD 21043", billing_address="Brdancat Enterprises, Inc., 9107 Mendenhall Ct., Unit B, Columbia, MD 21045") store.put() stores.append(store) store = Store(name="Starbucks", location=db.GeoPt(40.7131116,-83.015359), manager=manager.key().name(), owner=owner.key().name(), address="Starbucks, Shrt Gate Shopping Center, 6392 Gregory Rd, Kingston City, NV 52552", billing_address="Fieldcat Enterprises, Inc., 1822 Radcliffe St., Unit B, Durby, DL 62611") store.put() stores.append(store) store = Store(name="Friendly's", location=db.GeoPt(37.7131116,-96.015359), manager=manager.key().name(), owner=owner.key().name(), address="Friendly's, North Wall Shopping Center, 4319 Desmond St, Riverside, CA 92503", billing_address="Redwood Services, Inc., 6777 Brook Av., Lansing, PA 48912") store.put() stores.append(store) store = Store(name="Hardrock Cafe", location=db.GeoPt(41.4291638,-76.215929), manager=manager.key().name(), owner=owner.key().name(), address="Hardrock Cafe, 100 Broadway, New York City, NY 10001", billing_address="Rose Inc., 4193 Manning Dr., Richmond, VA 23420") store.put() stores.append(store) store = Store(name="Tavern", location=db.GeoPt(40.6192436,-77.819237), manager=manager.key().name(), owner=owner.key().name(), address="Tavern, 297 Clark St., Chicago, IL 60604", billing_address="The Billers, 78 University Rd., Syracuse, NY 13205") store.put() stores.append(store) return stores
def get_store(): store = memcache.get(STORE_KEY) if store is None: store = Store.get_by_key_name(STORE_KEY) memcache.set(STORE_KEY, store) return store
def test_print_items_in_store(self): list = self.generate_data() store = Store(list) print_items_in_store(store) store_list = store.items self.assertEqual(list, store_list)
def test_checkout(self): list = self.generate_data() store = Store(list) checkout(store) self.assertTrue(True)
def test_get_store(): store = Store() store_info = store.get_store(conditions=['store_id = 1']) assert 'store_id' in store_info[0] and 'store_name' in store_info[0] and 'store_street' in store_info[0] and \ 'store_mail' in store_info[0] and 'store_phone_number' in store_info[0] and 'store_city' in store_info[0] and \ 'store_state' in store_info[0] and 'store_zip_code' in store_info[0]
def test_update_store(): store = Store() updated_values = {'store_name': 'I completely love books'} conditions = ['store_id = 1'] ans = store.update_store(updated_values, conditions=conditions) assert ans['success']