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_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 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 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 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 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 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 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 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 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 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')
import pandas as pd from restaurants import db from restaurants.models import Neighborhood, Category, Restaurant yelp_url = 'https://raw.githubusercontent.com/ledeprogram/courses/master/foundations/mapping/tilemill/yelp-lunch-nyc.csv' records = pd.read_csv(yelp_url) restaurants = records.to_dict('records') for restaurant in restaurants: category = Category.query.filter_by(name=restaurant["Category"]).first() category_id = category.id neighborhood = Neighborhood.query.filter_by( name=restaurant["City"]).first() neighborhood_id = neighborhood.id if Restaurant.query.filter_by( name=restaurant["Name"], neighborhood_id=neighborhood_id).count() == 0: restaurant = Restaurant(name=restaurant["Name"], url=restaurant["URL"], category=category, rating=restaurant["Rating"], neighborhood=neighborhood) db.session.add(restaurant) db.session.commit()
} ] }""") for user in data_json['all_users']: u = User(name=str(user["name"]), email=str(user["email"]), img=str(user["img"])) session.add(u) session.commit() for restaurant in data_json['all_restaurants']: res = Restaurant(user_id=restaurant["user_id"], name=str(restaurant["name"]), address=str(restaurant["address"]), phone=str(restaurant["phone"]), website=str(restaurant["website"]), cousine=str(restaurant["cousine"]), img=str(restaurant["img"])) session.add(res) session.commit() for menu_item in restaurant["menu_items"]: menuItem = MenuItem(user_id=menu_item["user_id"], restaurant_id=res.id, name=str(menu_item["name"]), description=str(menu_item["description"]), price=str(menu_item["price"]), course=str(menu_item["course"]), img=str(menu_item["img"])) session.add(menuItem) session.commit()
def perform_create(self, serializer): restaurant = Restaurant(restaurant=self.request.restaurant, **serializer.validated_data) restaurant.save()
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)
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 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 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): expected_result = 'test restaurant' menu = Menu(restaurant=Restaurant(name=expected_result)) self.assertEqual(str(menu), expected_result)
def test_string_representation(self): test_restaurant_name = 'Test restaurant name' self.assertEqual(str(Restaurant(name=test_restaurant_name)), test_restaurant_name)