def save_restaurants(restaurant_df, inspection_df): for index, row in inspection_df.iterrows(): try: b_id = None if Restaurant.objects.filter( restaurant_name=row["restaurantname"], business_address=row["businessaddress"], postcode=row["postcode"], ).exists(): rt = Restaurant.objects.get( restaurant_name=row["restaurantname"], business_address=row["businessaddress"], postcode=row["postcode"], ) save_inspections(row, rt.business_id) logger.info( "Inspection record for restaurant saved successfully: {}". format(rt)) else: response = json.loads( match_on_yelp(row["restaurantname"], row["businessaddress"])) if next(iter( response)) == "error" or not response["businesses"]: b_id = None else: b_id = response["businesses"][0]["id"] r = Restaurant( restaurant_name=row["restaurantname"], business_address=row["businessaddress"], postcode=row["postcode"], business_id=b_id, compliant_status=row["isroadwaycompliant"], ) if b_id: if not Restaurant.objects.filter( business_id=b_id).exists(): r.save() logger.info( "Restaurant details successfully saved: {}".format( b_id)) save_inspections(row, b_id) save_yelp_restaurant_details(b_id) else: Restaurant.objects.filter(business_id=b_id).update( compliant_status=row["isroadwaycompliant"]) save_inspections(row, b_id) else: r.save() save_inspections(row, b_id) except Exception as e: logger.error( "Error while saving to table Restaurant: {} {}".format( b_id, e)) # raise return
def add_restaurant(request): error = [] if 'ok' in request.POST: name = request.POST['name'] phone_number = request.POST['phone'] address = request.POST['address'] opentime = request.POST['opentime'] if not name: error.append('請輸入餐廳名稱') if not phone_number: error.append('請輸入電話') if not address: error.append('請輸入地址') if not opentime: error.append('請輸入營業時間') if not error: r = Restaurant(name=name, phone_number=phone_number, address=address, opentime=opentime) r.save() name = '' phone_number = '' address = '' opentime = '' return HttpResponseRedirect('/restaurant') return render_to_response('restaurant/add_restaurant.html', locals())
def add_restaurant(request): user = request.user if not user.is_authenticated: return HttpResponseRedirect(reverse('Login')) userprofile = UserProfile.objects.get(user = user) if request.method == 'POST': name = request.POST['name'] if name: r = Restaurant(name = name) try: r.save() except: return HttpResponseRedirect(reverse('addRestaurant')) r.user.add(user) base = userprofile.base array = userprofile.array if not base or not array: return HttpResponseRedirect(reverse('init')) base = json.loads(base) array = json.loads(array) base = add_arr(base, name) array = add_arr(array, name) userprofile.base = base userprofile.array = array userprofile.save() return HttpResponseRedirect(reverse('viewAll')) return render_to_response('restaurant/add.html')
def post(self, request): form = AddRestaurantForm(request.POST, request.FILES) data = dict(form=form) if form.is_valid(): data = form.cleaned_data restaurant = Restaurant() manager = Manager() restaurant.name = data['name'] restaurant.description = data['description'] restaurant.profile_image = request.FILES['profile_image'] manager.email = data['manager_email'] chars = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789" password = "".join([chars[ord(c) % len(chars)] for c in urandom(8)]) manager.set_password(password) manager.is_confirmed = True manager.save() manager.send_email("Login details - Restaurant booking online", "Your login details :\n E-mail : " + manager.email + "\n Password : "******"\n You can login now " + get_current_site(request).domain + "\n Restaurant booking online") restaurant.manager = manager restaurant.category = data['category'] restaurant.save() return render(request, self.template_name, dict(form=form))
def createrest(request): if request.method == 'POST': form = RestaurantCreateForm(request.POST) if form.is_valid(): data = form.cleaned_data user = form.save() restaurant = Restaurant() restaurant.user = user restaurant.business_name = data['business_name'] restaurant.address = data['address'] restaurant.city = data['city'] restaurant.state = data['state'] restaurant.zip_code = data['zip_code'] restaurant.phone_number = data['phone_number'] restaurant.save() user = authenticate(username=request.POST['username'], password=request.POST['password1']) login(request, user) return HttpResponseRedirect(reverse('restaurant_profile', args=[user.restaurant.id])) else: form = RestaurantCreateForm() return render(request, 'registration/restaurant_registration.html', {'form': form})
def seed(self): restaurant_names = [ 'El Celler de Can Roca', 'Osteria Francescana', 'Noma', 'Central', 'Eleven Madison Park', 'Mugaritz', 'Dinner by Heston Blumenthal', 'Narisawa', 'D.O.M.', 'Gaggan', ] description = """Lorem ipsum dolor sit amet, et mea legere blandit abhorreant, nam exerci accusam elaboraret no. Mea te minimum sensibus. Cu qui commodo omnesque percipit. Per munere nullam temporibus ea. Nec mentitum antiopam no. Ad duis doming indoctum his. Eos ex fabulas singulis, natum labores periculis mea ex. Quo libris apeirian eu. Per solet aperiri ea. Eligendi hendrerit nam id, eos eu alienum antiopam intellegebat, eam viderer denique cu. Homero equidem eu pro. Mel nostro constituam ad, ius ut modus cetero verear. Ad nam eros omnis, mea ei offendit molestiae. Vix adhuc possit inciderint ad, forensibus posidonium sed in, in mei decore vivendo volumus. No per labore nemore. Eos ei molestie percipit maiestatis, oratio audire molestiae ne est, dolore assentior prodesset sed ei. Ea tibique fastidii quo, sit accusata reformidans ei. Elitr primis an quo, quem contentiones eu pro. Eius cotidieque reformidans ex est, rebum expetenda has at. Ius nulla inermis disputando an, idque meliore sit et. Agam reque pericula ne mea, pro postea graeco debitis ne, mei habemus gubergren cotidieque id. Timeam eleifend cu sed, vero labitur per in. Vim ei laoreet minimum officiis, pri alterum gloriatur eu. Id erat debitis comprehensam vix, vix ea dicit dissentiet, cu vix ipsum luptatum. Ad eros ridens malorum eam.""".strip() for i in range(len(restaurant_names)): restaurant_name = restaurant_names[i] restaurant = Restaurant() restaurant.name = restaurant_name restaurant.description = description restaurant.manager = Manager.objects.filter(email="*****@*****.**" % str(i)).first() restaurant.category = random.choice(RestaurantCategory.objects.all()) menu = Menu() menu.save() restaurant.menu = menu restaurant.save()
def test_has_no_menu(self): user = User(username='******', email='*****@*****.**', password='******') user.save() rest = Restaurant(business_name="I love donuts", email='*****@*****.**', address='1122 City Center', city='LV', state='NV', zip_code='89178', phone_number='555-1212', user=user) rest.save() self.assertFalse(rest.has_menu(), "No Menu")
def test_has_menu(self): user = User(username='******', email='*****@*****.**', password='******') user.save() rest = Restaurant(business_name="I love donuts", email='*****@*****.**', address='1122 City Center', city='LV', state='NV', zip_code='89178', phone_number='555-1212', user=user) rest.save() menu = FoodItem(restaurant=rest, name='Sprinkle Donut', price='2.99', description='your favorite sprinkle donut', category='D') menu.save() self.assertTrue(rest.has_menu(), "Yes, there's a Menu")
def api_insert_review_view(request, **kwargs): """ "author" : "author_name", "rating" : "1", "weight_score" : "1", "text" : "content", "restaurant_id" : "1", "review_count" : "30", "source" : "google", "category" : "Pizza", "country" : "United States", "state" :"GA", "created_date" : "2021-01-18" """ if request.method == 'POST': serializer = ReviewSerializer(data=request.data) if serializer.is_valid(): # TODO: check if request missing restaurant id try: res_obj = Restaurant.objects.get( res_id=request.data['restaurant_id']) except Restaurant.DoesNotExist: res_obj = Restaurant(res_id=request.data['restaurant_id'], name='', number_review=0) res_obj.save() review = res_obj.res_review.create( author=serializer.data['author'], rating=serializer.data['rating'], weight_score=serializer.data['weight_score'], text=serializer.data['text'], review_count=serializer.data['review_count'], source=serializer.data['source'], category=serializer.data['category'], country=serializer.data['country'], state=serializer.data['state'], created_date=serializer.data['created_date']) review.save() res_obj.number_review = int(res_obj.number_review) + 1 res_obj.save() data = {'message': 'Success'} return Response(data, status=status.HTTP_200_OK) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) else: return Response(status=status.HTTP_400_BAD_REQUEST)
def populateDB(restaurants): for name, properties in restaurants.iteritems(): # Extract dictionary address = ", ".join(properties['address']) description = properties['description'] phone = properties['phone'] website = properties['website'] email = properties['email'] loc = (float(properties['longitude']), float(properties['latitude'])) # get image name only img = properties['image'].split('/')[-1].strip() categories = properties['categories'] try: # Only add new restaurant Restaurant.objects.all().get(name=name) except: # Create object in database r = Restaurant(name=name, address=address, description=description, phone=phone, website=website, email=email, img=img, pt=Point(loc)) r.save() print r i = 0 while i < len(categories) and i < 2: catName = categories[i] catName = catName.upper() c = None try: # Get existing category if exists c = Category.objects.get(name=catName) except: # Create new category if i == 0: c = Category(name=catName) # First cat else: c = Category(name=catName, super_cat=categories[0].upper()) # Sub cat c.save() print c r.categories.add(c) r.save() i += 1
def handle(self, *args, **options): all_restaurants = Restaurant.get_all()['Restaurants'] for restaurant in all_restaurants: try: geo_location = eval(restaurant['GEO_location']) price = restaurant['pricepoint'] print("geo" + str(geo_location)) if type(geo_location) == dict: continue if not type(geo_location) == tuple: print(f"one of the entries is not a tuple: {geo_location}") geo_location = eval(self.faker.location_on_land()) if not price.lower() in {'low', 'medium', 'high'}: print(f"invalid pricepoint {price}") if not price in {'$', "$$", "$$$"}: raise Exception else: price = { '$': 'Low', "$$": 'Medium', "$$$": "High" }[price] except NameError: traceback.print_exc() geo_location = self.faker.location_on_land() except Exception: print("execution halted") break new_location = { "lat": str(geo_location[0]), "long": str(geo_location[1]), "city": str(geo_location[2]), "state": str(geo_location[3]), "country": str(geo_location[4]) } restaurant['GEO_location'] = new_location restaurant['pricepoint'] = price.title() new_rest = Restaurant(**restaurant) new_rest.clean_fields() new_rest.clean() new_rest.save()
def add_restaurant(request): context = {} if request.user.userprofile.is_customer: context['errors'] = 'you are not a business user and cannot create a restaurant' return render(request, 'account/add-restaurant.html', context) if request.method == 'GET': context['form'] = RestaurantForm() return render(request, 'account/add-restaurant.html', context) form = RestaurantForm(request.POST) context['form'] = form if not form.is_valid(): return render(request, 'account/add-restaurant.html', context) location = Point(form.cleaned_data['longitude'], form.cleaned_data['latitude']) new_restaurant = Restaurant(name=form.cleaned_data['name'], introduction=form.cleaned_data['introduction'], address=form.cleaned_data['address'], owner=request.user, location=location) new_restaurant.save() added_recipes = form.cleaned_data['added_recipes'] if added_recipes: relate_added_recipes_helper(new_restaurant, added_recipes) return redirect(reverse('restaurant_home', kwargs={'restaurant_id': new_restaurant.id}))
def get_restaurants_and_food_data(): r = requests.get('https://api.food.jumia.com.gh/api/v5/vendors', headers={"X-FP-API-KEY": "HTML5"}) restaurants = r.json()["data"]["items"] for restaurant in restaurants: if restaurant['name'] == 'Hellofood Test Restaurant 2' or restaurant['name'] == 'Hellofood Test Restaurant 2': print('test restaurants avoid') else: existing_restaurant = get_object_or_none(Restaurant, name=restaurant['name']) if not existing_restaurant: rest_obj = Restaurant() rest_obj.name = restaurant['name'] rest_obj.restaurant_crawl_link = restaurant['web_path'] rest_obj.description = restaurant['description'] rest_obj.city = restaurant['city']['name'] rest_obj.address = '{} \n {}'.format(restaurant['address'], restaurant['address_line2'] if restaurant['address_line2'] else '') rest_obj.latitude = restaurant['latitude'] rest_obj.longitude = restaurant['longitude'] logo_path = restaurant['logo'].split('%s/') if len(logo_path) == 3: img = download_image(logo_path[2]) try: filename = '{}.{}'.format(restaurant['name'].replace(' ', '_'), img.format) rest_obj.logo = filename tempfile = img tempfile_io = BytesIO() # Will make a file-like object in memory that you can then save tempfile.save(tempfile_io, format=img.format) rest_obj.logo.save(filename, ContentFile(tempfile_io.getvalue()), save=False) # Set save=False otherwise you will have a looping save method except: print("Error trying to save model: saving image failed: ") pass if restaurant['cms_content']['vendor_wide_logo']: try: img = download_image(restaurant['cms_content']['vendor_wide_logo']) filename = '{}_cover.{}'.format(restaurant['name'].replace(' ', '_'), img.format) rest_obj.cover_photo = filename tempfile = img tempfile_io = BytesIO() # Will make a file-like object in memory that you can then save tempfile.save(tempfile_io, format=img.format) rest_obj.cover_photo.save(filename, ContentFile(tempfile_io.getvalue()), save=False) # Set save=False otherwise you will have a looping save method except: print("Error trying to save model: saving image failed: ") pass rest_obj.save() food_path = requests.get(restaurant['web_path']) soup = BeautifulSoup(food_path.text, 'html.parser') food_items = soup.find_all('article', class_='product-variation') food_name_parent = None for food_item in food_items: the_food_name = None food_name = food_item.find('span', class_='mrs') right_text_food = food_item.find('div', class_='has-text-right') if food_name and right_text_food: right_text_food_select = right_text_food.find('span', class_='has-ellipsis') food_name_parent = food_name.get_text() the_food_name = '{} {}'.format(food_name.get_text(), right_text_food_select.get_text()) elif right_text_food and not food_name: right_text_food_select = right_text_food.find('span', class_='has-ellipsis') the_food_name = '{} {}'.format(food_name_parent, right_text_food_select.get_text()) elif food_name: food_name = food_name.get_text() food_name_parent = food_name the_food_name = food_name food_description = food_item.find('p', class_='dsc').get_text() if food_item.find('p', class_='dsc') else '' food_price = food_item.find('span', class_='mlxs').get_text() existing_food = get_object_or_none(Food, name=the_food_name) if not existing_food: food_obj = Food() food_obj.name = the_food_name.strip() food_obj.description = food_description.strip() food_obj.price = food_price food_obj.restaurant = rest_obj if not existing_restaurant else existing_restaurant food_obj.save()
class RestaurantTest(TestCase): def setUp(self): self.now = '2019-01-01 12:00:00.000000+00:00' self.restaurant = Restaurant( name='군내치킨', owner='박군내', title='군내치킨-서초점', tel='1234', min_order_price=10000, order_way='현장 결제', origin='닭:국내산', delivery_charge=2000, info='군내나지만 맛있습니다.', type='요기요 등록 음식점', img='media/restaurant/chicken.png', estimated_delivery_time=self.now, operation_start_hour=self.now, operation_end_hour=self.now, ) self.restaurant.save() self.category = self.restaurant.category.create(name='1인분 주문') self.category.save() def test_restaurant_should_be_created_on_valid_data(self): ''' 유효한 데이터에 대해 레스토랑을 생성한다. ''' # Given # When # Then self.assertEqual(self.restaurant.owner, '박군내') self.assertEqual(self.restaurant.title, '군내치킨-서초점') self.assertEqual(self.restaurant.tel, '1234') self.assertEqual(self.restaurant.min_order_price, 10000) self.assertEqual(self.restaurant.order_way, '현장 결제') self.assertEqual(self.restaurant.delivery_charge, 2000) self.assertEqual(self.restaurant.info, '군내나지만 맛있습니다.') self.assertEqual(self.restaurant.type, '요기요 등록 음식점') self.assertEqual(self.restaurant.estimated_delivery_time, self.now) self.assertEqual(self.restaurant.operation_start_hour, self.now) self.assertEqual(self.restaurant.operation_end_hour, self.now) self.assertIsNotNone(self.restaurant.img) self.assertIsInstance(self.restaurant, Restaurant) self.assertEqual(self.restaurant.__str__(), self.restaurant.name) self.assertEqual(self.restaurant.category.get(pk=self.category.pk), self.category) self.assertEqual(self.category.name, '1인분 주문') def test_restaurant_should_not_be_created_on_invalid_data(self): ''' 유효하지 않은 데이터에 대해 레스토랑을 생성하지 않는다. ''' # Given # When # Then self.assertIsNot(self.restaurant.min_order_price, 1000) self.assertIsNot(self.restaurant.estimated_delivery_time, 'now') self.assertIsNot(self.restaurant.img, '-') self.assertNotIsInstance(self.category, Restaurant) self.assertIsNot(self.restaurant.__str__(), '굽굽치킨') self.assertIsNot(self.restaurant.category.get(pk=self.category.pk), self.restaurant)
def createRestaurant(request,idEntite): global myfile, entite if request.user.is_authenticated(): if request.user.is_superuser : global ckeck try: entite = Entite.objects.filter(idEntit=idEntite)[0] check=1 except: check=0 if check ==1: if request.POST: is_error = 0 nom = request.POST["nom"] quartier = request.POST["quartier"] email = request.POST["email"] numero = request.POST["numero"] latitude = request.POST["latitude"] longitude = request.POST["longitude"] # couleur=request.POST["coleur"] save_plus = request.POST.getlist('save_and') if latitude == "": error_latitude = "veuiller remplir ce champs" is_error = 1 if longitude == "": error_longitude = "veuiller remplir ce champs" is_error = 1 if nom == "": errer_nom = "veuiller remplir ce champs" is_error = 1 if quartier == "": error_quartier = "veuiller remplir ce champs" is_error = 1 if email == "": error_email = "veuiller remplir ce champs" is_error = 1 else: if re.search(r"^[a-z0-9._-]+@[a-z0-9._-]+\.[a-z]+", email) is None: is_error = 1 error_email = "email incorrect" if numero == "": error_numero = "veuiller remplir ce champs" is_error = 1 else: if re.search(r"^[0-9]{9}$", numero) is None: is_error = 1 error_numero = "numero incorrect" try: myfile = request.FILES['logo'] except: error_logo = "veuillez selectionner une image" is_error = 1 # fs = FileSystemStorage() if is_error == 0: restaurant=Restaurant() restaurant.nomRestaurant=nom restaurant.numeroRestaurant=numero restaurant.emailRestaurant=email restaurant.createurRestaurant=request.user restaurant.entite=entite restaurant.quartierRestaurant=quartier restaurant.longiRestaurant=longitude restaurant.latiRestaurant=latitude entite_folder = "C:/Users/root/PycharmProjects/senfood/static/images/uploads/" save_path = "C:/Users/root/PycharmProjects/senfood/static/images/uploads/" +decodeString(entite.nomEntite) logo_name = "restau_" + nom + "_" + myfile.name destination = open(os.path.join(save_path, logo_name), 'wb+') restaurant.logoRestaurant = "images/uploads/" + decodeString(entite.nomEntite) + "/" + logo_name restaurant.save() for chunk in myfile.chunks(): destination.write(chunk) destination.close() log = Log() log.utilisateur = request.user.username log.action = "Creation restaurant " + nom+" pour l'entite "+decodeString(entite.nomEntite) messages.success(request, 'Restaurant ajouté avec succès') try: _next = int(save_plus[0]) except: _next = 0 if _next == 0: v=5 #return render(request, 'creationRestaurant.html', locals()) return redirect(profilEntite,idEntite) else: nom = "" quartier = "" email = "" numero = "" longitude="" latitude="" return render(request, 'creationRestaurant.html', locals()) else: # entite=Entite() # entite.nomEntite=nom # entite.sloganEntite=slogan # entite.emailEntite=email # entite.numeroEntite=numero return render(request, 'creationRestaurant.html', locals()) else: return render(request, 'creationRestaurant.html', locals()) else: message = "page introuvable" return render(request, '404.html', locals())