def makeANewMeal(user_id, description, duration, healthy, unhealthy,
                 starch_rich, sucrose_rich):
    now = datetime.datetime.now()
    created = datetime.date(now.year, now.month, now.day)
    hours, minutes = duration.split(':')
    duration = datetime.timedelta(hours=int(hours), minutes=int(minutes))

    newMeal = Meal(
        created=created,
        description=description,
        duration=duration,
        healthy=0,
        unhealthy=1,
        starch_rich=0,
        sucrose_rich=1,
        user_id=user_id
    )
    db_session.add(newMeal)
    try:
        db_session.commit()
    except:
        db_session.rollback()
        raise
    newMeal.created = str(newMeal.created)
    newMeal.duration = str(newMeal.duration)
    return jsonify(Meal=newMeal.serialize)
Beispiel #2
0
def create_meal():
    if not request.json:
        abort(404)
    meal = Meal()
    db.session.add(meal)
    meal.load(request.json)
    db.session.commit()
    return jsonify({'meal': meal.serialize}), 201
Beispiel #3
0
def deleting_saved_meal(user_id, meal_id):
    check_user = do_user_check(user_id)
    if check_user:
        meal = Meal.query.filter(Meal.meal_id == meal_id,
                                 Meal.user_id == user_id).first()
        Meal.delete(meal)
        flash(f"You successfully deleted the meal", "success")
        return redirect(f'/users/{user_id}/saved-meals')
    else:
        return redirect("/")
Beispiel #4
0
def adding_saved_meal(user_id, meal_id, meal_name):
    check_user = do_user_check(user_id)
    if check_user:
        saved_meal = Meal(user_id=user_id,
                          meal_id=meal_id,
                          meal_name=meal_name,
                          meal_image=request.json['meal_image'])
        Meal.save(saved_meal)
        flash("You saved the meal successfully", "success")
        return redirect(f'/users/{user_id}/meals/{meal_id}/view/{meal_name}')
    else:
        return redirect("/")
Beispiel #5
0
def meal_new(request, *args, **kwargs):
    if request.method == 'POST':
        meal_form = MealForm(request.POST)
        if meal_form.is_valid():
            restaurant = meal_form.cleaned_data['restaurant']
            value = meal_form.cleaned_data['value']
            date = meal_form.cleaned_data['date']

            meal = Meal(meal_value=value, meal_date=date, meal_restaurant=restaurant)
            meal.save()
    else:
        meal_form = MealForm()
    return render(request, 'meal_new.html', {'meal_form': meal_form})
Beispiel #6
0
    def form_valid(self, form):
        def grab(s):
            return form.cleaned_data[s]

        m = Meal(
            eater=Player.logged_in_player(self.request),
            eaten=Player.current_players().get(feed=grab("feedcode")),
            time=grab("time"),
            location=grab("location"),
            description=grab("description"),
        )
        m.full_clean()
        m.save()

        return super(EatView, self).form_valid(form)
Beispiel #7
0
def add_meal():
    user = current_user
    title = 'Add Meal'
    header = 'Add Meal'
    form = AddMealForm()

    if form.validate_on_submit():
        new_meal = Meal(user_id=user.id,
                        label=form.label.data,
                        minutes=form.minutes.data,
                        recipe=form.recipe.data)

        try:
            db.session.add(new_meal)
            db.session.commit()
            flash('Meal "' + form.label.data + '" added!')
            return redirect('/food_planner')
        except IntegrityError as e:
            flash(e.message)
            return redirect('/food_planner')

    return render_template('add_meal.html',
                           user=user,
                           title=title,
                           header=header,
                           form=form)
Beispiel #8
0
 def meals():
     user = current_user
     o = request.json
     required_fields = ['name', 'planned_date', 'plan_id']
     missing_fields = [f for f in required_fields if f not in o]
     if missing_fields:
         abort(400, 'missing fields: ' + repr(missing_fields))
     # todo: check plan is owned by user
     m = Meal(
         name=o['name'],
         plan_id=o['plan_id'],
         planned_date=o['planned_date'],
     )
     db.session.add(m)
     db.session.commit()
     return m.to_dict()
Beispiel #9
0
def cart():
    form = OrderForm()
    data = []
    sum = 0
    selected_meals = {}
    user = User.objects.filter(name='guest').first()
    if 'data' in session:
        data = session['data']
        selected_meals = {int(key): int(value) for key, value in data.items() if value != 0 and key != ''}
        meals = Meal.objects(__raw__={"meal_id": {"$in": list(selected_meals.keys())}})
        data = []
        for meal in meals:
            sum += int(meal.price) * int(selected_meals[meal.meal_id])
            data.append({'meal_id': meal.meal_id, 'title': meal.title,
                         'price': meal.price, 'qnt': selected_meals[meal.meal_id]})
    if request.method == "POST":
        if 'logged_in' in session and session['logged_in']:
            form.name.data = session['name']
            form.email.data = session["username"]
            user = User.objects.filter(name=session['name']).first()
        order = Order(date=datetime.now(), sum=sum, status='ordered', user=user,
                      phone=form.phone.data, address=form.address.data)
        order.save()
        user.orders.append(order)
        user.save()
        for key, value in selected_meals.items():
            meal = MealWithCount(meal=Meal.objects.filter(meal_id=key).first(), count=value)
            meal.save()
            order.meals.append(meal)
        order.save()
        return redirect('/order_done/')
    return render_template("cart.html", data=data, form=form)
Beispiel #10
0
def meal():
    user = get_current_user()
    user_id = user.id
    if request.method == 'POST':
        if request.is_json:
            data = request.get_json()
            name = data['name']
            new_meal = Meal(name=name,
                            energy=data['energy'],
                            protein=data['protein'],
                            carbohydrate=data['carbohydrate'],
                            fat=data['fat'],
                            fiber=data['fiber'],
                            time=datetime.now(),
                            food_id=data['id'],
                            user_id=user_id)
            db.session.add(new_meal)
            db.session.commit()
            recently_added = Meal.query.filter_by(name=new_meal.name)
            return jsonify([*map(meal_serializer, recently_added)])
        else:
            return {"error": "The request failed."}
    elif request.method == 'GET':
        logged_meals = Meal.query.filter_by(user_id=user_id).order_by(
            Meal.time.desc()).all()
        return jsonify([*map(meal_serializer, logged_meals)])
Beispiel #11
0
def update():
    with open("data/delivery_categories.csv", "r") as file:
        lines = file.readlines()
        for i in range(1, len(lines)):
            data = lines[i].split(",")
            category = Category(id=data[0], title=data[1])
            db.session.add(category)

    # id,title,price,description,picture,category_id
    with open("data/meals.csv", "r") as file:
        lines = file.readlines()
        for i in range(1, len(lines)):
            data = lines[i].split(";")
            item = Meal(id=int(data[0]),
                        title=data[1],
                        price=int(data[2]),
                        description=data[3],
                        picture=data[4],
                        category_id=int(data[5]))
            db.session.add(item)
    guest = User(name='guest',
                 mail='guest',
                 password=Config.PASSWORD,
                 role='guest')
    admin = User(name='admin',
                 mail='admin',
                 password=Config.PASSWORD,
                 role='admin')
    db.session.add(guest)
    db.session.add(admin)
    db.session.commit()
Beispiel #12
0
def print_my_orders(my_order):
    return template.myorder.format(
        Meal.get(my_order.mealId).name,
        my_order.studentName,
        my_order.studentId,
        my_order.birthday,
        Canteen.get(my_order.canteenId).name,
        my_order.token)
Beispiel #13
0
def add_to_database():
    with open("categories.tsv", "r") as tsv_file:
        read_tsv = csv.DictReader(tsv_file, delimiter='\t')
        for row in read_tsv:
            db.session.add(Category(**row))
    with open("meals.tsv", "r") as tsv_file:
        read_tsv = csv.DictReader(tsv_file, delimiter='\t')
        for row in read_tsv:
            db.session.add(Meal(**row))

    db.session.commit()
Beispiel #14
0
def seed_meals():
    with open('meals.csv') as f:
        reader = csv.DictReader(f)
        for row in reader:
            meal = Meal(id=int(row['id']),
                        title=row['title'],
                        price=int(row['price']),
                        description=row['description'],
                        picture=row['picture'],
                        category_id=int(row['category_id']))
            db.session.add(meal)
        db.session.commit()
Beispiel #15
0
def fill_items():
    csv_items = 'delivery_items.csv'

    meals = pd.read_csv(csv_items, index_col=0)

    for i in range(meals.shape[0]):
        series = meals.iloc[i]
        meal = Meal(title=series['title'],
                    price=int(series['price']),
                    picture=series['picture'],
                    description=series['description'],
                    category_id=int(series['category_id']))
        db.session.add(meal)
Beispiel #16
0
def seed():
    for category1 in categories:
        category = Category(title=category1['title'])
        db.session.add(category)

    for meal1 in meals:
        meal = Meal(title=meal1['title'],
                    price=int(meal1['price']),
                    description=meal1['description'],
                    picture=meal1['picture'],
                    category_id=int(meal1['category_id']))
        db.session.add(meal)
    db.session.commit()
def fill_data():
    categories = pd.read_csv("categories.csv", index_col=0)
    meals = pd.read_csv("meals.csv", index_col=0)
    for cat in categories.values:
        new_cat = Category(title=cat[0])
        db.session.add(new_cat)
    for meal in meals.values:
        new_meal = Meal(title=meal[0],
                        price=meal[1],
                        description=meal[2],
                        picture=meal[3])
        cat = db.session.query(Category).filter(Category.id == meal[4]).first()
        new_meal.categories.append(cat)
        db.session.add(new_meal)
    db.session.commit()
Beispiel #18
0
def create_base():
    path = __file__[:-10] + 'data/'
    with open(path + 'delivery_categories.csv', "r") as file:
        lines = file.readlines()
        for i in range(1, len(lines)):
            data = lines[i].split(",")
            category = Category(category_id=int(data[0]), title=data[1].rstrip())
            category.save()

    # id,title,price,description,picture,category_id
    with open(path + 'meals.csv', "r") as file:
        lines = file.readlines()
        for i in range(1, len(lines)):
            data = lines[i].split(";")
            item = Meal(meal_id=int(data[0]), title=data[1], price=int(data[2]),
                        description=data[3], picture=data[4], category_id=int(data[5].rstrip()),
                        category=Category.objects(category_id=int(data[5].rstrip())).first())
            item.save()

    admin = User(name='admin', mail='*****@*****.**', role='admin')
    admin.password = Config.PASSWORD
    guest = User(name='guest')
    guest.save()
    admin.save()
Beispiel #19
0
def add_db_data(categories=categories, meals=meals):
    for category in categories.json():
        category_db = Category(title=category['title'])
        db.session.add(category_db)
        for meal in meals.json():
            if meal['category_id'] == category['id']:
                meal_db = Meal(id=meal['id'],
                               title=meal['title'],
                               price=meal['price'],
                               description=meal['description'],
                               picture=meal['picture'],
                               category=category_db)
                db.session.add(meal_db)
    admin_user = User(name="Admin", mail="*****@*****.**", role="Admin")
    admin_user.password = "******"
    db.session.add(admin_user)
    db.session.commit()
Beispiel #20
0
def add_meals():
    """Export data from csv items file
        to SQL DB table 'meals'.
        """
    with open(os.path.join(current_path, 'delivery_items.csv'), newline='') as csv_file:
        meals = [meal for meal in csv.reader(csv_file)][1:]

        for meal in meals:
            uid, title, price, description, picture, category_id = meal
            category_query = Category.query.get(int(category_id))
            new_meal = Meal(
                title=title, price=price, description=description,
                picture=picture, category=category_query
            )
            db.session.add(new_meal)

    db.session.commit()
Beispiel #21
0
    def meal(self, meal_data):
        d = datetime.timedelta(hours=meal_data.time.data.hour,
                               minutes=meal_data.time.data.minute)
        healthy_val = 1
        unhealthy_val = 0
        if meal_data.health.data == 'unhealthy':
            healthy_val = 0
            unhealthy_val = 1

        newMeal = Meal(created=meal_data.date.data,
                       description=meal_data.description.data,
                       duration=d,
                       healthy=healthy_val,
                       unhealthy=unhealthy_val,
                       starch_rich=meal_data.starch_rich.data,
                       sucrose_rich=meal_data.sucrose_rich.data,
                       user_id=session['user_id'])
        db_session.add(newMeal)
        db_session.commit()
Beispiel #22
0
def init_db(Meal, Plan, User):
    db.create_all()
    user = User.query.filter_by(email='*****@*****.**').first()
    if not user:
        user = User(
            alt_id=generate_alt_id(size=64),
            alias='dummy',
            email='*****@*****.**',
            password=hash_password('password'),
        )
        plan = Plan(name='dummy plan', users=[user])
        meal = Meal(
            name='dummy meal',
            created_date=datetime.datetime.utcnow(),
            planned_date=to_date_int(datetime.date.today()),
            plan=plan,
        )
        db.session.add(user)
        db.session.add(meal)
        db.session.commit()
Beispiel #23
0
def add_meal():
    if not current_user.IsAdmin:
        flash(
            "Cannot access this page unless you hold administrative privileges."
        )
        return redirect(url_for("home"))

    form = CreateMealForm(request.form)

    if form.validate_on_submit():
        date = form.mealDate.data
        description = form.description.data
        dinnerBool = form.dinnerBool.data

        try:
            meal = Meal(Date=date,
                        Description=description,
                        DinnerBool=dinnerBool)

            if session.query(Meal).filter(Meal.Date == date, Meal.DinnerBool
                                          == dinnerBool).first() is None:
                session.add(meal)
                session.commit()

                print("Meal added. {}".format(meal))
                flash("Success! The Meal was added.")
                return redirect(url_for('meals'))
            else:
                flash(
                    "Already added a meal for this date and time. Please try another day or time."
                )
                return render_template('forms/addMeal.html', form=form)
        except Exception as e:
            session.rollback()
            print(
                "add_meal function returned error on adding meal with descr of {}. {}"
                .format(description, str(e)))
            return render_template('errors/500.html'), 500
    else:
        print(form.errors)
        return render_template('forms/addMeal.html', form=form)
Beispiel #24
0
def import_csv():

    with open('delivery_categories.csv', encoding='utf-8') as f:
        cat = list(csv.reader(f, delimiter=','))
        for row in cat:
            if row[1] != 'title':
                cat = Category(id=row[0], title=row[1])
                db.session.add(cat)
    db.session.commit()
    with open('delivery_items.csv', encoding='utf-8') as f:
        table = csv.reader(f, delimiter=',')
        for row in table:
            if row[0] != 'id':
                item = Meal(id=row[0],
                            title=row[1],
                            price=row[2],
                            description=row[3],
                            picture=row[4],
                            category_id=row[5])
                db.session.add(item)

    db.session.commit()
Beispiel #25
0
 def form_valid(self, form):
     def grab(s):
         return form.cleaned_data[s]
     zombie = Player.logged_in_player(self.request)
     victim = Player.current_players().select_for_update().get(feed=grab("feedcode"))
     m = Meal(
         eater=zombie,
         eaten=victim,
         time=grab('time'),
         location=grab("location"),
         description=grab("description"),
     )
     m.full_clean()
     m.save()
     
     
     return super(EatView, self).form_valid(form)
Beispiel #26
0
 def mutate(self, info, date, restaurant_id, meal_type):
     current_user = get_jwt_identity()
     user = User.query.filter_by(email=current_user).first()
     _meal = Meal.query.filter(
         and_(Meal.user_id == user.id, Meal.meal_type == meal_type,
              Meal.eat_date == date)).first()
     if _meal:
         _meal.date = date
         _meal.restaurant_id = restaurant_id
         _meal.meal_type = meal_type
     else:
         new_meal = Meal(restaurant_id=restaurant_id,
                         user_id=user.id,
                         meal_type=meal_type,
                         eat_date=date)
         db.session.add(new_meal)
     try:
         db.session.commit()
     except Exception as e:
         db.session.rollback()
         print(e)
         raise GraphQLError('Internal Server Error')
     return MealUpsert(response={'ok': True})
Beispiel #27
0
from models import User, Category, Meal

with open("../../untitled/data/delivery_categories.csv", "r") as file:
    lines = file.readlines()
    for i in range(1, len(lines)):
        data = lines[i].split(",")
        print(data)
        category = Category(category_id=int(data[0]), title=data[1].rstrip())
        category.save()

# id,title,price,description,picture,category_id
with open("../../untitled/data/meals.csv", "r") as file:
    lines = file.readlines()
    for i in range(1, len(lines)):
        data = lines[i].split(";")
        print(data)
        item = Meal(meal_id=int(data[0]),
                    title=data[1],
                    price=int(data[2]),
                    description=data[3],
                    picture=data[4],
                    category_id=int(data[5].rstrip()),
                    category=Category.objects(
                        category_id=int(data[5].rstrip())).first())
        item.save()

admin = User(name='admin', mail='*****@*****.**', role='admin')
admin.password = '******'
guest = User(name='guest')
guest.save()
admin.save()
Beispiel #28
0
    row = sheet_categories.row(row_num)
    category = Category(title=row[1].value)
    db.session.add(category)

db.session.commit()

# По скольку БД уже начала индексировать данные в таблице, id не откатить до 1-5.
# Что бы не пересоздавать таблицы и бд небольшой вспомогательный словарь

cat = {1: "Суши",
       2: "Стритфуд",
       3: "Пицца",
       4: "Паста",
       5: "Новинки",
       }

for row_num in range(1, sheet_meals.nrows):
    row = sheet_meals.row(row_num)
    meal = Meal(
                title=row[1].value,
                price=row[2].value,
                description=row[3].value,
                picture=row[4].value
                )
    db.session.add(meal)

    category = db.session.query(Category).filter(Category.title == cat[int(row[5].value)]).first()
    meal.categories.append(category)

db.session.commit()
Beispiel #29
0
def generator():
    # Clear up database first
    User.query.delete()
    Setting.query.delete()
    Category.query.delete()
    Tag.query.delete()
    Recipe.query.delete()
    Ingredient.query.delete()
    RecipeIngredient.query.delete()
    Meal.query.delete()

    jurian = User(name='jurian', email='*****@*****.**', password=generate_password_hash('password'))

    grocery_day             = Setting('grocery_day', 'sat')
    default_servings        = Setting('default_servings', '2')
    allow_user_registration = Setting('allow_user_registration', 'true')
    default_language        = Setting('default_language', 'nl')

    starter   = Category('Starter')
    main      = Category('Main')
    side_dish = Category('Side dish')
    desert    = Category('Desert')
    breakfast = Category('Breakfast')
    lunch     = Category('Lunch')

    vegetarian = Tag('Vegetarian')
    indian     = Tag('Indian')
    italian    = Tag('Italian')
    moroccan   = Tag('Moroccan')
    lactose    = Tag('Lactose free')

    recipe1 = Recipe(
        name='Fish curry', servings=4, prep_time=15, cook_time=30,
        category=main, intro='A delicious but simple curry',
        description="""Wash and cook the rice.\n\nStart with oil and fry the
            paste for 5 minutes. Add the fish and coconut milk. Poach fish until
            tender. Finalize with coriander.""")

    rice = Ingredient('Rice', 'g')
    paste = Ingredient('Curry paste', 'ts')
    fish = Ingredient('White fish', 'g')
    coconut = Ingredient('Coconut milk', 'ml')
    coriander = Ingredient('Coriander', 'g')

    recipe1.ingredients.append(RecipeIngredient(rice, 320))
    recipe1.ingredients.append(RecipeIngredient(paste, 3, 0.75))
    recipe1.ingredients.append(RecipeIngredient(fish, 400))
    recipe1.ingredients.append(RecipeIngredient(coconut, 150))
    recipe1.ingredients.append(RecipeIngredient(coriander, 20))

    recipe2 = Recipe(name='Pasta something', servings=4, prep_time=20, cook_time=15, category=main,
        intro='Quick pasta for a working day meal',
        description="Start with bla bla and then\nDo some more steps\n\nEnjoy!")

    recipe3 = Recipe(name='Weekend tajine', servings=4, prep_time=30, cook_time=60, category=main,
        intro='Something truly the waiting for during a weekend',
        description="Start with bla bla and then\nDo some more steps\n\nEnjoy!")

    recipe4 = Recipe(name='Fish curry', servings=4, prep_time=15, cook_time=30, category=main,
        intro='A delicious but simple curry',
        description="Start with bla bla and then\nDo some more steps\n\nEnjoy!")

    recipe5 = Recipe(name='Pasta something', servings=4, prep_time=20, cook_time=15, category=main,
        intro='Quick pasta for a working day meal',
        description="Start with bla bla and then\nDo some more steps\n\nEnjoy!")

    recipe6 = Recipe(name='Weekend tajine', servings=4, prep_time=30, cook_time=60, category=main,
        intro='Something truly the waiting for during a weekend',
        description="Start with bla bla and then\nDo some more steps\n\nEnjoy!")

    recipe7 = Recipe(name='Fish curry', servings=4, prep_time=15, cook_time=30, category=main,
        intro='A delicious but simple curry',
        description="Start with bla bla and then\nDo some more steps\n\nEnjoy!")

    recipe8 = Recipe(name='Pasta something', servings=4, prep_time=20, cook_time=15, category=main,
        intro='Quick pasta for a working day meal',
        description="Start with bla bla and then\nDo some more steps\n\nEnjoy!")

    recipe9 = Recipe(name='Weekend tajine', servings=4, prep_time=30, cook_time=60, category=main,
        intro='Something truly the waiting for during a weekend',
        description="Start with bla bla and then\nDo some more steps\n\nEnjoy!")

    recipe10 = Recipe(name='Fish curry', servings=4, prep_time=15, cook_time=30, category=main,
        intro='A delicious but simple curry',
        description="Start with bla bla and then\nDo some more steps\n\nEnjoy!")

    recipe11 = Recipe(name='Zaalouk', servings=4, prep_time=15, cook_time=0, category=side_dish,
        intro='Moroccan Vegetable side dish',
        description="Cut the eggplants to cubes, if you like you can peel the eggplant not completely you leave some skin on them for the dark look.\n\nCut the tomato to fine slices")

    recipe12 = Recipe(name='A very long title with multiple words', servings=4, prep_time=30, cook_time=60, category=main,
        intro='Something truly the waiting for during a weekend',
        description="Start with bla bla and then\nDo some more steps\n\nEnjoy!")

    session = db.session
    session.add(jurian)
    session.add(grocery_day)
    session.add(default_servings)
    session.add(allow_user_registration)
    session.add(default_language)
    session.add(starter)
    session.add(main)
    session.add(side_dish)
    session.add(desert)
    session.add(breakfast)
    session.add(lunch)
    session.add(vegetarian)
    session.add(indian)
    session.add(italian)
    session.add(moroccan)
    session.add(lactose)
    session.add(recipe1)
    session.add(recipe2)
    session.add(recipe3)
    session.add(recipe4)
    session.add(recipe5)
    session.add(recipe6)
    session.add(recipe7)
    session.add(recipe8)
    session.add(recipe9)
    session.add(recipe10)
    session.add(recipe11)
    session.add(recipe12)

    session.commit()

    recipe1.tags.append(indian)
    recipe1.tags.append(lactose)

    recipe11.tags.append(moroccan)

    session.commit()

    today = Meal(date.today(), recipe1)
    tomorrow = Meal(date.today() + timedelta(days=1), recipe2)
    tomorrow1 = Meal(date.today() + timedelta(days=1), name='Green salad', note='Use rocket salad from yesterday')
    tomorrow2 = Meal(date.today() + timedelta(days=2),
                     name='Rösti with lamb and red cabbage',
                     note='Rösti from freezer, check lamb first!')
    tomorrow3 = Meal(date.today() + timedelta(days=3), recipe3, servings=4)
    tomorrow4 = Meal(date.today() + timedelta(days=4), name='Chicken biryani')
    tomorrow5 = Meal(date.today() + timedelta(days=5), recipe9)
    tomorrow6 = Meal(date.today() + timedelta(days=5), recipe11)

    session.add(today)
    session.add(tomorrow)
    session.add(tomorrow1)
    session.add(tomorrow2)
    session.add(tomorrow3)
    session.add(tomorrow4)
    session.add(tomorrow5)
    session.add(tomorrow6)

    session.commit()

    return redirect(url_for('home'))
Beispiel #30
0
import csv

from app import app, db
from models import Category, Meal
app.app_context().push()
#Заполним таблицу категорий
if  db.session.query(Category).get(1):
    print('Вы пытаетесь выполнить инициирующую загрузку категорий повторно, очистите таблицы чтобы ее выполнить')
else:
    file_to_open = os.path.expanduser('~/projects/spepik_flask/week_5_project/flask_week_5/data/categories.csv')
    with open(file_to_open) as file:
        reader = csv.DictReader(file)
        for category in reader:
            category_add = Category(id=category['id'], title=category['title'])
            db.session.add(category_add)
        db.session.commit()

#Заполним таблицу блюд
if  db.session.query(Meal).get(1):
    print('Вы пытаетесь выполнить инициирующую загрузку блюд повторно, очистите таблицы чтобы ее выполнить')
else:
    file_to_open = os.path.expanduser('~/projects/spepik_flask/week_5_project/flask_week_5/data/meals.tsv')
    with open(file_to_open) as file:
        reader = csv.DictReader(file, delimiter='\t')
        for meal in reader:
            meal_add = Meal(id=meal['id'], title=meal['title'], price=meal['price'],\
            description=meal['description'], picture = meal['picture'])
            cat=db.session.query(Category).filter(Category.id == meal['category_id']).scalar()
            meal_add.category = cat
            db.session.add(meal_add)
        db.session.commit()
Beispiel #31
0
    def POST(self):
        data = web.input(
            req="",
            studentId="",
            studentName="",
            birthday="",
            phone="",
            sex="",
            location="",
            canteen="",
            package="",
            message=""
        )

        if data.req == 'canteen':
            web.header('Content-Type', 'application/json')
            try:
                canteens = Canteen.getAll(location=data.location)
                result = [dict(cid=item.id, name=item.name) for item in canteens]
                return json.dumps(result)
            except Exception:
                return '{}'

        elif data.req == 'package':
            web.header('Content-Type', 'application/json')
            try:
                meals = Meal.getAll(canteenId=data.canteen, active=1)
                result = [dict(id=item.id, name=item.name) for item in meals]
                return json.dumps(result)
            except Exception:
                return '{}'

        elif data.req == 'submit':
            # 验证数据有效性
            web.header('Content-Type', 'application/json')

            status = self.checkMatch(data.studentId, data.studentName)
            if status == -3:
                return json.dumps({'errinfo': "抱歉,系统出现错误."})
            elif status == -2:
                return json.dumps({'errinfo': "姓名不能为空"})
            elif status == -1:
                return json.dumps({'errinfo': "学号不能为空"})
            elif status == 0:
                return json.dumps({'errinfo': "学号与姓名不匹配!"})
            elif status == 2:
                return json.dumps({'errinfo': "您的账户被锁定,请检查是否您是否有未完成的订单!"})
            elif status == 3:  # 先注册
                User(dict(
                    studentId=data.studentId,
                    studentName=data.studentName,
                    sex=self.getSexId(data.sex),
                    birthday=data.birthday,
                    phone=data.phone,
                    shortMessage=data.message,
                    lastOrderTime="0000-00-00",
                    addTime=web.SQLLiteral("NOW()"),
                    isLock=False
                )).insert();

            # 检查 餐品是否有效是否有效
            meal = Meal.get(data.package)
            if meal == None or str(meal.canteenId) != str(data.canteen):
                return json.dumps({'errinfo': "请不要伪造请求"})

            # 检查订餐日期是否有效
            if not re.match(r'^\d{4}-\d{2}-\d{2}$', data.birthday):
                return json.dumps({'errinfo': '请输入正确的日期, 如 1990-10-01'})
            max_deltatime = datetime.timedelta(days=7)
            min_deltatime = datetime.timedelta(days=0)
            order_time = datetime.datetime.strptime(data.birthday, "%Y-%m-%d")
            now = datetime.datetime.now()

            # 提前 1 - 7 天订餐
            if order_time > now + max_deltatime or order_time < now + min_deltatime:
                return json.dumps({'errinfo': '请提前1-7天订餐!'})

            # 获取领餐人信息
            user = User.getBy(studentId=data.studentId, studentName=data.studentName)
            if user.lastOrderTime:
                last_order_time = datetime.datetime.strptime(str(user.lastOrderTime), "%Y-%m-%d")
                deltatime = datetime.timedelta(days=300)
                # 判断订餐间隔
                if last_order_time + deltatime > datetime.datetime.now():
                    return json.dumps({'errinfo': "订餐时间间隔过短, 一年内只能免费订餐一次!"})

            # 获取订餐人(当前操作者信息)
            adder = User.getBy(studentId=self.session.sid)

            Order(dict(userId=adder.id,
                       canteenId=data.canteen,
                       mealId=data.package,
                       studentId=data.studentId,
                       studentName=data.studentName,
                       phone=data.phone,
                       sex=self.getSexId(data.sex),
                       birthday=data.birthday,
                       token=self.generateToken(),
                       wish=data.message,
                       addTime=web.SQLLiteral("NOW()"),
                       isActive=True
                       )).insert()
            user.isLock = 1
            user.update()
            return json.dumps({'successinfo': "添加成功!"})

        else:
            raise web.Forbidden()
Beispiel #32
0
#already done

import csv
from flask_sqlalchemy import SQLAlchemy
from flask import Flask
from models import Meal, Category


app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///stepik.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)

with open("delivery_categories.csv", "r") as f:
    reader = csv.DictReader(f, delimiter = ",")
    for i in reader:
        category = Category(id = int(i["id"]), title = i["title"])
        db.session.add(category)
        
with open("delivery_items.csv", "r") as f:
    reader = csv.DictReader(f, delimiter = ",")
    for i in reader:
        meal = Meal(id = int(i["id"]), title = i["title"], picture = i["picture"],
                description = i["description"], category_id = int(i["category_id"]),
                price = int(i["price"]))
        db.session.add(meal)
        
db.session.commit()