def create_users():
    request_dish = request.get_json()
    dish1 = Dish(name=request_dish["name"],
                 description=request_dish["description"],
                 is_typical=request_dish["is_typical"],
                 restaurant_id=request_dish["restaurant_id"])
    db.session.add(dish1)
    db.session.commit()
    return jsonify(dish1.serialize()), 200
Exemple #2
0
def delete_dish(dish: models.Dish):
    with models.database.transaction():
        delete_recipe = models.Recipe.delete().where(
            models.Recipe.dish == dish)
        delete_recipe.execute()

        clear_list = models.DishesList.delete().where(
            models.DishesList.dish == dish)
        clear_list.execute()

        dish.delete_instance()
def createDish(categorie, title, composition, price, weight, img):
    c = Categorie.objects.get(title=categorie)
    d = Dish(title=title,
             categorie=c,
             composition=composition,
             price=price,
             weight=weight,
             img=img)
    d.save()
    from datetime import datetime
    st = datetime.now().strftime("%y%m%d%H%M%S")
    c.update_code = st
    c.save()
def insert_test_data():
    all_objects = []
    with open('delivery_categories.csv', encoding='utf8') as categories_file:
        categories = csv.reader(categories_file, delimiter=',')
        categories_objs = []
        for i, row in enumerate(categories):
            if i == 0:
                continue
            categories_objs.append(Category(id=int(row[0]), title=row[1]))
    all_objects.extend(categories_objs)

    with open('delivery_items.csv', encoding='utf8') as dishes_file:
        dishes = csv.reader(dishes_file, delimiter=',')
        dishes_objs = []
        for i, row in enumerate(dishes):
            if i == 0:
                continue
            dishes_objs.append(
                Dish(
                    id=int(row[0]), title=row[1], price=int(row[2]), description=row[3],
                    picture=os.path.join('/static/images', row[4]),
                    categories=list(filter(lambda x: x.id == int(row[5]), categories_objs))
                )
            )
    all_objects.extend(dishes_objs)

    db.session.add_all(all_objects)
    db.session.commit()
Exemple #5
0
def addDish(request):
    data = {}
    data.update(csrf(request))
    if request.method == 'POST': #jak wyslano formularza
        form = AddDishForm(request.POST)
        if form.is_valid(): #jak wszystko okej
            newDish = Dish(name=request.POST['name'],
                           prize=request.POST['prize'],
                           information=request.POST['information'],
                           inscribeBy=request.user)
            newDish.save()
            #strona informacyjna
            data['information'] = 'Dodano danie!'
            data['back']='../'
            return render_to_response('info.html',data)
    else:
        form = AddDishForm()
        data['form']=form
        data['user']=request.user;
        return render_to_response('addDish.html',data)
Exemple #6
0
    def post(self):
        parsed_args = parser.parse_args()
        dish = Dish(dish_name=parsed_args['dish_name'],
                    dish_description=parsed_args['dish_description'],
                    dish_rating=parsed_args['dish_rating'],
                    dish_id=parsed_args['dish_id'],
                    restaurant_name=parsed_args['restaurant_name'])

        session.add(dish)
        session.commit()
        return dish, 201
    def putMenu(self, date, periodId):
        """ date format: XXXX-XX-XX, peroid: 481,482,483 for breakfast, lunch and dinner, 1778 and 1779 for other two """
        values = {}
        values['LocationId'] = "1965"  # fixed for ARA
        values['PeriodId'] = periodId  # 481,482,483 for breakfast, lunch and dinner, 1778 and 1779 for other two
        values['MenuDate'] = date
        values['UIBuildDateForm'] = date
        data = urllib.urlencode(values)
        url = "http://rose-hulman.campusdish.com/Commerce/Catalog/Menus.aspx"
        geturl = url + "?" + data
        print geturl
        request = urllib2.Request(geturl)
        response = urllib2.urlopen(request)
        soup = BeautifulSoup(response.read())
        blocks = soup.find_all('div', class_='menu-details-station')

        if periodId == 481:
            pName = "Breakfast"
        elif periodId == 482:
            pName = "Lunch"
        elif periodId == 483:
            pName = "Dinner"
        elif periodId == 1778:
            pName = "Con't Breakfast"
        elif periodId == 1779:
            pName = "Soup & Salad"

        period = Period(selectDate=date,
                        name=pName)
        period.put()
        for block in blocks:
            # print block.h2.string, "------"
            category = Category(parent=period.entityKey,
                                name=block.h2.string)
            category.put()
            for item in block.find_all('div', class_='menu-name'):
                # print "     ", item.a.string
                dish = Dish(parent=category.entityKey,
                            name=item.a.string)
                dish.put()
Exemple #8
0
    def post_dish(jwt):
        """Adds a dish. Requires authentication and permission"""
        try:
            res = request.get_json()
            if not res:
                abort(404)

            if 'name' in res and 'ingredient' in res:
                ing = res.pop('ingredient')
                dish = Dish(**res)

                if ing:
                    for i in ing:
                        ingredient = Ingredient(**i, dish_id=dish.id)
                        dish.ingredient.append(ingredient)

                dish.insert()
                result = {"success": True, "result": dish.format()}
                return jsonify(result)
        except TypeError:
            print(sys.exc_info())
            abort(400)
Exemple #9
0
def add():
    data = request.get_json()
    name = data['name']
    description = data['description']
    price = data['price']
    category = data['category']

    entry = Dish(name=name,
                 description=description,
                 price=int(price),
                 category=category)
    db.session.add(entry)
    # commit all additions to db
    db.session.commit()
    return json.dumps("Solutions Added"), 200
Exemple #10
0
def create():
    if request.method == 'POST':
        name = request.form['name']
        recipe = request.form['recipe']
        ingredients = request.form['ingredients']
        cost = request.form['cost']
        error = None

        if not name:
            error = 'Name is required.'

        if not cost:
            error = 'Cost is required.'

        if error is not None:
            flash(error)
        else:
            db.session.add(Dish(name, recipe, ingredients, cost))
            db.session.commit()
            return redirect(url_for('show_dish'))
    return render_template('create.html')
Exemple #11
0
def change_dish(id, do):
    id = int(id)

    if do == "add":
        s = Dish()
    else:
        s = mydb.session.query(Dish).filter(Dish.id_dish == id).one_or_none()

    form = DishForm(request.form, obj=s)

    if do == "delete":
        mydb.session.delete(s)
        mydb.session.flush()
        return redirect(url_for('dish'))

    if form.button_save.data:
        form.populate_obj(s)
        mydb.session.add(s)
        if s.id_dish != id:
            return redirect(url_for('dish', id=s.id_dish))

    return render_template('change_dish.html', form=form)
Exemple #12
0
def updateSp(request):
    today = utils.getToday()
    todayD = dateutil.parser.parse(today).date()
    allDishes = json.loads(request.body)
    cnt = 0
    for x in allDishes:
        rs = Dish.objects.filter(pid=x["id"], date__range=(todayD, todayD))
        if rs:
            continue
        d0 = Dish()
        if rs:
            d0.date = rs[0].date
        d0.pid = x["id"]
        d0.name = x["name"]
        d0.booth = x["booth"]
        d0.ingredient = x["ingredient"]
        if "<Simple Wamen>" in x["name"]:
            d0.energy = 320
        else:
            d0.energy = x["energy"]
        d0.price = x["price"]
        d0.mealTime = x["mealTime"]
        d0.floor = x["floor"]
        d0.like = 0
        d0.dislike = 0
        d0.save()
        cnt += 1
    return HttpResponse("INFO(SP): updated %d pictures" % cnt)
Exemple #13
0
def test_data(client):
    pizza = Dish(name='pizza', price=10)
    pizza.ingredient = [
        Ingredient(dish_id=pizza.id, name='tomato', allergen=''),
        Ingredient(dish_id=pizza.id, name='cheese', allergen='milk'),
        Ingredient(dish_id=pizza.id, name='flour', allergen='wheat'),
    ]
    pizza.insert()

    salad = Dish(name='salad', price=5)
    salad.ingredient = [
        Ingredient(dish_id=salad.id, name='potato', allergen=''),
        Ingredient(dish_id=salad.id, name='nuts', allergen='peanut'),
        Ingredient(dish_id=salad.id, name='kale', allergen=''),
    ]
    salad.insert()

    icecream = Dish(name='icecream', price=5)
    icecream.ingredient = [
        Ingredient(dish_id=icecream.id, name='cream', allergen='milk'),
    ]
    icecream.insert()
Exemple #14
0
def updateSp(request):
    today = utils.getToday()
    todayD = dateutil.parser.parse(today).date()
    allDishes = json.loads(request.body)
    cnt = 0
    for x in allDishes:
        rs = Dish.objects.filter(pid=x["id"], date__range=(todayD, todayD))
        if rs:
            continue
        d0 = Dish()
        if rs:
            d0.date = rs[0].date
        d0.pid = x["id"]
        d0.name = x["name"]
        d0.booth = x["booth"]
        d0.ingredient = x["ingredient"]
        if "<Simple Wamen>" in x["name"]:
            d0.energy = 320
        else:
            d0.energy = x["energy"]
        d0.price = x["price"]
        d0.mealTime = x["mealTime"]
        d0.floor = x["floor"]
        d0.like = 0
        d0.dislike = 0
        d0.save()
        cnt += 1
    return HttpResponse("INFO(SP): updated %d pictures" % cnt)
Exemple #15
0
import csv
from __init__ import app
from config import Config
from models import db, Dish


with open('data.csv', 'r') as data:
    dishes_csv = csv.reader(data)
    dishes = list(dishes_csv)
    for row in dishes[1:]:
        dish = Dish(d_id=int(row[0]),
                    title=row[1],
                    price=row[2],
                    description=row[3],
                    picture=Config.PICTURE_PATCH + row[4],
                    cat_id=int(row[5]))
        with app.app_context():
            db.session.add(dish)

# import works only with commit in cycle 'for'. Why?
with app.app_context():
    db.session.commit()
Exemple #16
0
 def add_new_dishes(jwt):
     data = request.get_json()
     dish = Dish(data['name'], data['image_link'],
                 json.dumps(data['ingredients']))
     dish.insert()
     return jsonify({'success': True})
Exemple #17
0
    dishBitMapDict = pickle.load(handle)

with open('dishHTMLDict.pickle', 'rb') as handle:
    dishHTMLDict = pickle.load(handle)

for dish_name in allDishes:
	bitMap = pickle.dumps(dishBitMapDict[dish_name])
	dishData = {
		'dish_name': dish_name,
		'dish_url': dishHTMLDict[dish_name],
		'dish_bitmap': bitMap
	}
	# g.log.info('Creating a Dish')
	# g.log = g.log.bind(dish_name=dishData['dish_name'])
	# g.log.info('Creating a new dish')
	dish = Dish(dishData)
	DB.session.add(dish)
	DB.session.commit()
	# g.log.info('Successfully created dish')


	

##for ingredient in allIngredients:
##    print(ingredient)

##for dish in allDishes:
##    print(dish)

##for dish in dishToIngredientsDict.keys():
##    print(dish + ":")
Exemple #18
0
from app import db
from models import Category, Dish

# заполняем БД
for cat in ['Суши', 'Стритфуд', 'Пицца', 'Паста', 'Новинки']:
    c = Category(title=cat)
    db.session.add(c)

db.session.commit()

f = open("data.csv", "r")
for line in f:
    if line is not '':
        dish = line.split(';')
        if dish[0] is not '':
            d = Dish(id=dish[0],
                     title=dish[1],
                     price=dish[2],
                     description=dish[3],
                     picture=dish[4],
                     category_id=dish[5])
            db.session.add(d)
f.close()

db.session.commit()
# заполняем БД - окончание