def test_sqlrepo_query_internal(self): restaurant_object = Restaurant(**fixtures.SINGLE_QUERY_RESULT) restaurant_object.save() result = self.sqlrepo._query(params=fixtures.PARAMS, first=True, as_dict=True) self.assertEqual(result, fixtures.SINGLE_QUERY_RESULT)
def add_delivery(request): pprint("Are we getting here?") message = "" if (request.user.is_authenticated and request.method == "POST"): # Get POST Vars, hopefully we can get Postamtes to open their API # So I can get access to this shit. # That's not gonna happen though. _name = request.POST.get('name') _address = request.POST.get('address') _time = request.POST.get('time') _wait = request.POST.get('wait') _distance = request.POST.get('distance') _base = float(request.POST.get('base')) _tip = float(request.POST.get('tip')) # Update Our Restaurant Table try: r = Restaurant.objects.get(name=_name) message = "Delivery Already Added, updating" _total_tips = 0 if _tip <= 0 else 1 r.total_tips += _total_tips r.total_tip_amount += _tip r.total_earnings += _base r.total_deliveries += 1 r.save() except Restaurant.DoesNotExist: _total_tips = 0 if _tip <= 0 else 1 r = Restaurant(name=_name, total_earnings=_base, total_tips=_total_tips, total_tip_amount=_tip) r.save() pprint(r) message = "Delivery Added To Database" # Update Our Delivery Table d = Delivery( user_id=request.user.id, restaurant=r, service="POSTMATES", address=_address, time_accepted=_time, wait_time=_wait, distance=_distance, base_earning=_base, tip=_tip ) d.save() return render(request, "add.html", {"message": message})
def get_queryset(self): q = self.request.query_params.get('q', None) if q: return Restaurant.get_searched_list(q=q) # querystring에서 type, price, district를 찾아 딕셔너리 형태로 Key에 대입, 없을경우 None객체를 넣음 filter_fields = { 'restaurant_type': self.request.query_params.get('type', None), 'average_price': self.request.query_params.get('price', None), 'district': self.request.query_params.get('district', None), } return Restaurant.get_filtered_list(filter_fields=filter_fields)
def upload_profile(id): user = Restaurant.objects(id=id).first() if not len(user): return jsonify({'error': 'Food Truck could not be found!'}), 400 file = request.files['file'] link = s3_upload(file) user = Restaurant.objects(id=id).first() user.modify(**dict(profile_picture=link)) user['pwd'] = None return jsonify(results=user)
def new(request): user = request.user if request.user.is_authenticated() else None if not user.lunchprofile.can_create_restaurants: return HttpResponseForbidden data = json.loads(request.BODY) restaurant = Restaurant(name=data['name']) try: restaurant.save() except: return HttpResponseBadRequest return HttpResponse('OK')
def restaurant_list_view(request): if request.method == "GET": q = request.GET.get('q', None) if q: restaurant = Restaurant.get_searched_list(q=q) return render(request, 'restaurant/list.html', {'list': restaurant}) filter_fileds = { 'restaurant_type': request.GET.get('type', None), 'average_price': request.GET.get('price', None), 'district': request.GET.get('district', None), } restaurant = Restaurant.get_filtered_list(filter_fields=filter_fileds) return render(request, 'restaurant/list.html', {'list': restaurant}) else: raise Http404
def register(): content = request.get_json() register = Register(**content) #1. check email if not register.check_email(): return (jsonify({'error': 'Not valid email address.'}), 400) if len(Restaurant.objects(email=content['email'])): return (jsonify({'error': 'Email is alredy in used.'}), 400) #2. check password check_password = register.check_password() if check_password: return (jsonify({'error': check_password}), 400) #3. hash password res = Restaurant(**content) res.set_password(content['pwd']) register.send_email() #4. save try: res.save() except Exception as e: return (jsonify({ 'error': "There is an error at the database. Please try later..." }), 500) content.pop('pwd', None) return (jsonify(content), 200)
def test_string_representation_if_description_value_and_value_unit_provided( self): menu = Menu(restaurant=Restaurant(name='test restaurant')) size = Size(menu=menu, description='Test size', value='32', value_unit='cm') expected_result = 'Test size (32 cm)' self.assertEqual(str(size), expected_result)
def save(self, commit=True): restaurant = Restaurant() restaurant.nom = self.cleaned_data["nom"] restaurant.adresse = self.cleaned_data["adresse"] restaurant.telephone = self.cleaned_data["telephone"] restaurant.restaurateur = self.cleaned_data["restaurateur"] restaurant.save() return restaurant
def get_by_location(): content = request.get_json() res = Restaurant.objects(lat__lte=content['maxLatitude'], lat__gte=content['minLatitude'], lng__lte=content['maxLongitude'], lng__gte=content['minLongitude'], isOpen=True) return jsonify(results=res)
def test_string_representation(self): menu = Menu(restaurant=Restaurant(name='test restaurant')) size = Size(menu=menu, description='Test size', value='32', value_unit='cm') meal = Meal(menu=menu, name='test meal') price = Price(value='24.99', size=size, content_object=meal) expected_result = '24.99' self.assertEqual(str(price), expected_result)
def load_restaurants(self, restaurant_json): """ Clear and load restaurants """ Restaurant.objects.all().delete() data = set( Restaurant(**i) for i in ijson.items(restaurant_json, "item")) Restaurant.objects.bulk_create(data) self.stdout.write( self.style.SUCCESS(f"Loaded {len(data)} restaurants"))
def update(id): user = Restaurant.objects(id=id).first() if not len(user): return jsonify({'error': 'Food Truck could not be found!'}), 400 #get by id if request.method == 'GET': user['pwd'] = None return jsonify(results=user) #delete by id if request.method == 'DELETE': user.delete() return jsonify({'message': 'User has been deleted'}), 400 #update by id if request.method == 'PUT': content = request.get_json() user.modify(**content) user = Restaurant.objects(id=id).first() user['pwd'] = None return jsonify(results=user)
def post(self, request, *args, **kwargs): restaurant = Restaurant(owner=self.request.user, name=request.data['name'], country=request.data['country'], street=request.data['street'], city=request.data['city'], phone=request.data['phone']) restaurant.save() if request.data['category']: result = Category.objects.filter( name__icontains=request.data['category']) if result: for category in result: restaurant.m2m_restaurant_cat.add(category) else: category = Category(name=request.data['category']) category.save() restaurant.m2m_restaurant_cat.add(category) return Response(status=200)
def save(self, commit=True): restaurant = Restaurant() restaurant.nom = self.cleaned_data["nom"] restaurant.adresse = self.cleaned_data["adresse"] restaurant.telephone = self.cleaned_data["telephone"] restaurant.restaurateur = self.cleaned_data["restaurateur"] restaurant.save() return restaurant
def get_token(): content = request.get_json() user = Restaurant.objects(email=content['email']).first() if user: token = user.get_token() token = token.split('.', 2)[2] content['token'] = token content['name'] = user['name'] reset = Reset(**content) reset.send_email() return jsonify({"message": "Token has been sent."}) return jsonify({'error': 'Email not found.'}), 400
def handle(self, *args, **kwargs): try: client = services.get_mongo_client() db = client.python_developer_db collection = db.segment_collection self.stdout.write( self.style.MIGRATE_HEADING(f"Cleaning SQL tables...")) Segment.objects.all().delete() Restaurant.objects.all().delete() self.stdout.write( self.style.MIGRATE_HEADING(f"Deserializing MongoDB data...")) data = [s for s in collection.find({})] self.stdout.write( self.style.MIGRATE_HEADING( f"Migrating data and creating relationships...")) with tqdm(total=len(data)) as progress_bar: for segment in data: segment_data = { k: v for k, v in segment.items() if k not in ( "restaurants", "size", "_id", ) } # Create Segment objects segment_object = Segment(**segment_data) segment_object.save() # Create Restaurant objects restaurant_objects = set( Restaurant(**r) for r in segment["restaurants"]) # bulk_create skips duplicates when ignore_conflicts is True with warnings.catch_warnings(): warnings.simplefilter("ignore") Restaurant.objects.bulk_create(restaurant_objects, ignore_conflicts=True) # Create relationships segment_object.restaurants.add(*restaurant_objects) progress_bar.update(1) except IntegrityError as e: return False
def test_get_restaurant_list_with_params(self): user = self.create_user() num = randint(1, 100) for i in range(num): self.create_restaurant(user=user) url = reverse(self.URL_RESTAURANT_LIST_NAME) params = { 'type': CHOICES_RESTAURANT_TYPE[randint(0, len(CHOICES_RESTAURANT_TYPE) - 1)][0], 'price': CHOICES_PRICE[randint(0, len(CHOICES_PRICE) - 1)][0], } # 필터된 리스트와 비교를 하기 위해 filter된 Restaurant List를 받아옴 filtered_restaurant = Restaurant.objects.filter(restaurant_type=params['type'], average_price=params['price']) response = self.client.get(url, params) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(response.data['count'], filtered_restaurant.count()) # 대문자 검색 테스트 search_param_uppercase = { 'q': 'DUMMY' } searched_upper_restaurant = Restaurant.get_searched_list(q=search_param_uppercase['q']) upper_response = self.client.get(url, search_param_uppercase) self.assertEqual(upper_response.status_code, status.HTTP_200_OK) self.assertEqual(upper_response.data['count'], searched_upper_restaurant.count()) # 소문자 검색 테스트 search_param_lowercase = { 'q': 'dummy' } searched_lower_restaurant = Restaurant.get_searched_list(q=search_param_lowercase['q']) lower_response = self.client.get(url, search_param_lowercase) self.assertEqual(lower_response.status_code, status.HTTP_200_OK) self.assertEqual(lower_response.data['count'], searched_lower_restaurant.count()) # 대문자 검색과 소문자 검색 결과가 같은지 테스트 self.assertEqual(upper_response.data['count'], lower_response.data['count'])
def login(): content = request.get_json() email = content['email'] if 'email' in session: return jsonify({'error': 'User alredy login.'}) user = Restaurant.objects(email=email).first() if not user: return jsonify({"error": "Error logging in. Please try again."}), 401 print user.check_password(content['pwd']) if not user.check_password(content['pwd']): return jsonify({"error": "Error logging in. Please try again."}), 401 session['email'] = content['email'] return jsonify({'message': 'You are login!'})
def change_password(): content = request.get_json() user = Restaurant.objects(email=content['email']).first() if not user: return jsonify({"error": "Invalid email address."}), 404 if not user.check_password(content['old_pwd']): return jsonify({"error": "Old password is incorrect."}), 404 register = Register(pwd=content['new_pwd']) check_password = register.check_password() if check_password: return (jsonify({'error': check_password}), 404) user.set_password(content['new_pwd']) user.save() return jsonify({'message': 'Password updated.'})
def reset_password(): content = request.get_json() user = Restaurant.objects(email=content['email']).first() if not user: return jsonify({'error': 'Email not found.'}), 400 try: user.check_token_password(content['token']) except SignatureExpired: return jsonify({"error": "Your token has expired."}), 400 except BadData: return jsonify({'error': 'Wrong token.'}), 400 rg = Register(**dict(pwd=content['new_pwd'])) check_password = rg.check_password() if check_password: return (jsonify({'error': check_password}), 400) user.change_password(content['new_pwd']) user.save() return jsonify({"message": "Password changed."})
def create(request): id = request.POST[ 'restaurant-id'] if 'restaurant-id' in request.POST else None restaurant = Restaurant.objects.get(id=id) if id else Restaurant() name = request.POST['name'] address = request.POST['address'] description = request.POST['description'] lat = request.POST['latitude'] lng = request.POST['longitude'] image = request.FILES[ 'restaurant-image'] if 'restaurant-image' in request.FILES else None if restaurant.id: for field in EDITABLE_FIELDS: if getattr(restaurant, field) != request.POST[field]: setattr(restaurant, field, request.POST[field]) if image: restaurant.image = image else: restaurant = Restaurant.objects.create(name=name, address=address, description=description, lat=lat, lng=lng) if image: restaurant.image = image try: restaurant.save() return HttpResponseRedirect(reverse('admin-index')) except: return render(request, 'admin/new.html')
def test_string_representation(self): menu = Menu(restaurant=Restaurant(name='test restaurant')) meal = Meal(menu=menu, name='test meal') expected_result = 'test restaurant | test meal' self.assertEqual(str(meal), expected_result)
def profile(): user = Restaurant.objects(email=session['email']).first() id = str(user['id']) return jsonify(results=user)
def perform_create(self, serializer): restaurant = Restaurant(restaurant=self.request.restaurant, **serializer.validated_data) restaurant.save()
def test_string_representation(self): menu = Menu(restaurant=Restaurant(name='test restaurant')) ingredient = Ingredient(name='test ingredient') topping = Topping(menu=menu, ingredient=ingredient) expected_result = 'test restaurant | test ingredient' self.assertEqual(str(topping), expected_result)
def random(self, request) -> Response: return Response( self.get_serializer(Restaurant.get_random_faster()).data)
def test_string_representation(self): expected_result = 'test restaurant' menu = Menu(restaurant=Restaurant(name=expected_result)) self.assertEqual(str(menu), expected_result)
def restaurant_parsing(self, restaurant_results, restaurant_info_results, list_info, avgrating_results): # top - info name = restaurant_results['name'] min_order_price = restaurant_results['min_order_amount'] methods = [] for method in restaurant_results['payment_methods']: if method == "creditcard": methods.append("신용카드") methods.append("현금") elif method == "online": methods.append("요기서결제") payment_methods = methods try: discount = restaurant_results['discounts']['additional'][ 'delivery']['amount'] except KeyError: discount = 0 delivery_charge = restaurant_results.get('delivery_fee') res_lat = restaurant_results['lat'] res_lng = restaurant_results['lng'] restaurant_image = restaurant_results['logo_url'] restaurant_back_image = restaurant_results['background_url'] categories = restaurant_results['categories'] # bottom - info notification = restaurant_info_results['introduction_by_owner'].get('introduction_text') \ if restaurant_info_results.get('introduction_by_owner') else '' s = restaurant_info_results['opening_time_description'].split(' - ') opening_time = datetime.strptime(s[0], '%H:%M') closing_time = datetime.strptime(s[1], '%H:%M') tel_number = restaurant_info_results['phone'] address = restaurant_info_results['address'] business_name = restaurant_info_results['crmdata']['company_name'] company_registration_number = restaurant_info_results['crmdata'][ 'company_number'] origin_information = restaurant_info_results['country_origin'] representative_menus = list_info['representative_menus'] average = avgrating_results['average'] average_delivery = avgrating_results['average_delivery'] average_quantity = avgrating_results['average_quantity'] average_taste = avgrating_results['average_taste'] try: delivery_time = int( restaurant_results['estimated_delivery_time'].split('~')[0]) except: delivery_time = 30 restaurant = Restaurant( name=name, notification=notification, opening_time=opening_time, closing_time=closing_time, tel_number=tel_number, address=address, min_order_price=min_order_price, payment_methods=payment_methods, business_name=business_name, company_registration_number=company_registration_number, origin_information=origin_information, delivery_discount=discount, delivery_charge=delivery_charge, delivery_time=delivery_time, lat=res_lat, lng=res_lng, categories=categories, representative_menus=representative_menus, # 평균 평점 average_rating=average, average_taste=average_taste, average_delivery=average_delivery, average_amount=average_quantity, ) restaurant.save() tags = list_info.get('keywords') if tags: restaurant.tags.add(*tags.split()) if restaurant_image: restaurant.image.save(*self.save_img('https://www.yogiyo.co.kr' + restaurant_image)) if restaurant_back_image: restaurant.back_image.save(*self.save_img(restaurant_back_image)) return restaurant
def test_string_representation(self): basket = Basket(owner=User.objects.get(username='******')) meal = Meal(menu=Menu(restaurant=Restaurant(name='restaurant')), name='soup') order = Order(basket=basket, meal=meal) self.assertEqual(str(order), 'christopher soup')
def test_string_representation_returns_default_if_desc_and_value_is_empty( self): menu = Menu(restaurant=Restaurant(name='test restaurant')) size = Size(menu=menu) expected_result = 'Normal size' self.assertEqual(str(size), expected_result)