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 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 test_edit_restaurant_valid(self): """ Test if restaurant document is properly updated """ id = Restaurant.objects.get(_id="111111111111111111111111")._id request = self.factory.post('/api/restaurant/edit/', { "restaurant_id": "111111111111111111111111", "name": "kfc2", "address": "211 Cambodia", "twitter": "", "instagram": "", "rating": "1.00" }, content_type='application/json') view_response.edit_restaurant_page(request) actual = Restaurant.objects.get(_id="111111111111111111111111") expected = Restaurant( _id=id, name='kfc2', address='211 Cambodia', phone=6475040680, city='markham', email='*****@*****.**', cuisine='american', pricepoint='High', twitter='', instagram='', bio='Finger licking good chicken', GEO_location="{'lat': 11.5395535, 'lng': 104.916782}", external_delivery_link=MOCK_VALID_LINK, cover_photo_url=MOCK_VALID_LINK, logo_url=MOCK_VALID_LINK, rating='3.00', owner_name='Colonel Sanders', owner_story='i made chicken', owner_picture_url=MOCK_VALID_LINK) self.assertDictEqual(model_to_dict(actual), model_to_dict(expected))
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 handle(self, *args, **options): path_fixtures = 'fixtures/' with open(path_fixtures + 'fixture.json') as load: data = json.loads(load.read()) if options['restaurant']: Restaurant.objects.all().delete() restaurants = [] for restaurant in data['restaurants']: image_file = open(path_fixtures + restaurant['imagePath'], 'rb') restaurant['imagePath'] = File(image_file) restaurants.append(Restaurant(**restaurant)) Restaurant.objects.bulk_create(restaurants) self.stdout.write( self.style.SUCCESS('It Works ! restaurants:'))
def test_reassign_BU_to_RO_Restaurant(self): """ Tests the reassign view (Upgrading from BU -> RO) by calling it then checking the database to see if the changes were made on the Restaurant Document """ request = self.factory.post('/api/user/role_reassign/', { "user_email": "*****@*****.**", "role": "RO", "name": "Rando Resto", "address": "211 detroit", "phone": 6475210680, "city": "toronto", "email": "*****@*****.**", "cuisine": "african", "pricepoint": "Medium", "twitter": "https://twitter.com/SupremeDreams_s1", "instagram": "https://www.instagram.com/rdcworld1/2?hl=en", "bio": "Finger licking good chicken", "external_delivery_link": "https://docs.djang22oproject.com/en/topics/testing/overview/", "cover_photo_url": "link", "logo_url": "link", "rating": "3.00" }, content_type='application/json') reassign_page(request) actual = Restaurant.objects.get(email="*****@*****.**") expected = Restaurant( _id=actual._id, name='Rando Resto', address='211 detroit', phone=6475210680, city='toronto', email='*****@*****.**', cuisine='african', pricepoint='Medium', twitter='https://twitter.com/SupremeDreams_s1', instagram='https://www.instagram.com/rdcworld1/2?hl=en', bio='Finger licking good chicken', GEO_location="{'lat': 42.3295629, 'lng': -83.0492457}", external_delivery_link= 'https://docs.djang22oproject.com/en/topics/testing/overview/', cover_photo_url='link', logo_url='link', rating='3.00') self.assertDictEqual(model_to_dict(actual), model_to_dict(expected))
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 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 approve_restr(model_admin, request, queryset): """ Approve of PendingRestaurant record and insert it into Restaurant collection, or updates the existing record in Restaurant collection that corresponds to this PendingRestaurant record. Sends a notification email to the restaurant email for each successful approval. """ count = 0 total = 0 restaurant_name = "" restaurant_id = None wrong_status = False for r in queryset: total += 1 restaurant = Restaurant(**model_to_json(r)) old_restaurant = Restaurant.objects.filter(_id=r._id).first() if r.status == Status.Pending.name: count += 1 # If there's already an approved restaurant record in Restaurant collection # check if the restaurant's media (image or video) is oudated, by comparing the url # to the url in the PendingRestaurant's media fields. If they don't match # delete the approved restaurant record's media file from google cloud bucket if old_restaurant: if old_restaurant.logo_url != r.logo_url: delete(old_restaurant.logo_url) if old_restaurant.cover_photo_url != r.cover_photo_url: delete(old_restaurant.cover_photo_url) if (old_restaurant.restaurant_video_url != r.restaurant_video_url and 'youtube' not in old_restaurant.restaurant_video_url): delete(old_restaurant.restaurant_video_url) edit_model(restaurant, { "status": Status.Approved.name, "approved_once": True }, ["status", "approved_once"]) save_and_clean(restaurant) owner_prefer_names = r.owner_preferred_name restaurant_name = r.name email = r.email restaurant_id = r._id send_approval_email(owner_prefer_names, email, restaurant_name, 'restaurant') else: wrong_status = True if count > 1: messages.success( request, "Successfully approved " + str(count) + " restaurant profiles.") queryset.update(status=Status.Approved.name, approved_once=True) elif count == 1: link = reverse("admin:restaurant_pendingrestaurant_change", args=[restaurant_id]) msg = format_html( "Successfully approved restaurant profile for <a href='{}' target='_blank' rel='noopener'>{}</a>", link, restaurant_name) messages.success(request, msg) queryset.update(status=Status.Approved.name, approved_once=True) elif wrong_status: messages.error(request, "You can only approve of 'Pending' restaurants") else: if total > 1: msg = "The selected restaurant profiles have been approved already." else: msg = "The selected restaurant profile has been approved already." messages.error(request, msg)
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()
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())