Hai so i am trying to increase a number ( +1 ) in my join column on button click on flask so far i done up to this
#app.route("/joins/<name>", methods=["POST"])
def joins(name):
namess = name
owner = users.query.filter_by(name=namess).first()
if owner is not None:
#making the joins +1 if the value is already 1
owner.joins = + 1
db.session.commit()
return redirect("/")
else:
return "You are not the owner of this url"
but it is not increasing the number how can i fix this happy coding!
The line
owner.joins = + 1
is valid python but I don't think it's what you want. It just assigns 1 to owner.joins. If you want to increment you need to do it like this:
owner.joins = owner.joins + 1
Related
This program is a console application that displays an Application Title and the Menu Options for the user, displays a list of recipe categories (i.e. Beef, Chicken, Vegan, Side, Desert, etc.), displays a list of meals based on a user selected category, and displays meal information (Directions) based on a user selected meal. I only need help with displaying the list of meals for the user selected category.
I am using a website that provides free JSON API's for this program that all work fine. The program shows the categories and recipes but wont show the individual meals for each of the category.
Its weird because I put print() statements after the if statements in the function where it gets the meals by category to try to debug it but, it prints both the pint(1) and print(2) statements so it does the getting stuff right but still also prints the else statement. This section of code is part of the recipes.py file (found under) in the search_meal_by_categories function.
This is what I put in to debug it to figure out why it prints out both the if and else:
def search_meal_by_category(categories):
lookup_category = input("Enter a category: ")
found = False
for i in range(len(categories)):
category = categories[i]
if category.get_category().lower() == lookup_category.lower():
found = True
print(1)
if found:
meals = requests.get_meals_by_category(lookup_category)
list_meals_by_category(lookup_category, meals)
print(2)
else:
print("Invalid Category, please try again")
Its very weird because it shows the recipe if you type it is but not the meals in that category. In the command menu you can:
("1 - List all Categories")
("2 - List all Meals for a Category")
("3 - Search Meal by Name")
("0 - Exit the program")
Thus far, I can put in the command 1 and 3 but not 2 or 0. There are 3 different python files for this and I included each of the 3 with only that specific meals by category function from each file to make it easier (I hope?).
Basically, the goal is to ask the program to show each meal in the category you type in. Thus far, it only shows the categories and a recipes instructions if you type in the name of the recipe. However, I dint include that since its working fine.
(object.py file)
class Category:
def __init__(self, category):
self.__category = category
def get_category(self):
return self.__category
def set_category(self, category):
self.__category = category
class Meal:
def __init__(self, meal_id, meal, meal_thumb):
self.__meal_id = meal_id
self.__meal = meal
self.__meal_thumb = meal_thumb
def get_meal_id(self):
return self.__meal_id
def set_meal_id(self, meal_id):
self.__meal_id = meal_id
def get_meal(self):
return self.__meal
def set_meal(self, meal):
self.__meal = meal
def get_meal_thumb(self):
return self.__meal_thumb
def set_meal_thumb(self, meal_thumb):
self.__meal_thumb = meal_thumb
(requests.py file)
from urllib import request, parse
import json
from objects import Category, Meal
def get_categories():
url = 'https://www.themealdb.com/api/json/v1/1/list.php?c=list'
f = request.urlopen(url)
categories = []
try:
data = json.loads(f.read().decode('utf-8'))
for category_data in data['meals']:
category = Category(category_data['strCategory'])
categories.append(category)
except (ValueError, KeyError, TypeError):
print("JSON format error")
return categories
def get_meals_by_category(category):
url = 'https://www.themealdb.com/api/json/v1/1/filter.php?c=Seafood' + category
f = request.urlopen(url)
meals = []
try:
data = json.loads(f.read().decode('utf-8'))
for meal_data in data['meals']:
category = Meal(meal_data['idMeal'],
meal_data['strMeal'],
meal_data['strMealThumb'])
meals.append(category)
except (ValueError, KeyError, TypeError):
print("JSON Format error")
return meals
This is the last file of the 3 and I think where the problem lies. I put a print(1), print(2) statement after each if and it printed out both those AND the else statement? Basically, all it shows right now is "Invalid Category, please try again" like 10 times.
import requests
def show_title():
print("My recipes Program")
print()
def show_menu():
print("COMMAND MENU")
print("1 - List all Categories")
print("2 - List all Meals for a Category")
print("3 - Search Meal by Name")
print("0 - Exit the program")
print()
def list_categories(categories):
print("CATEGORIES")
for i in range(len(categories)):
category = categories[i]
print(category.get_category())
print()
def list_meals_by_category(category, meals):
print(category.upper() + " MEALS ")
for i in range(len(meals)):
meal = meals[i]
print(meal.get_meal())
print()
def search_meal_by_category(categories):
lookup_category = input("Enter a category: ")
found = False
for i in range(len(categories)):
category = categories[i]
if category.get_category().lower() == lookup_category.lower():
found = True
break
if found:
meals = requests.get_meals_by_category(lookup_category)
list_meals_by_category(lookup_category, meals)
else:
print("Invalid Category, please try again")
Please comment if you need any more information, this is my first time doing a python project this big (I know this may seem very easy to everyone because everyone on here is a genius). I have genuinely been staring at this for 2 days now. Thanks everyone for any help!
Did you mean to write this:
def search_meal_by_category(categories):
lookup_category = input("Enter a category: ")
found = False
for i in range(len(categories)):
category = categories[i]
if category.get_category().lower() == lookup_category.lower():
found = True
break
if found:
meals = requests.get_meals_by_category(lookup_category)
list_meals_by_category(lookup_category, meals)
else:
print("Invalid Category, please try again")
I have unindented the if found: part, so that when you get the found = True; break then it skips the rest of the for and detects found.
I am trying to make a code in Python for a Otree aplication.
The main idea is to add $20 to a fixed payment when a person have the same answer that I put in my constants.
For example in this code I have a value of 3 in Constants.retemv if a person put a response of 3 in the J11 form the will get the $20
I try to use the next code, payment is a constant with a $20 value.
def set_payoff(self):
self.payoff = Constants.participation_fee + Constants.iat
if self.J11 == Constants.retemv:
self.payoff += Constants.payment
I expect the output of $45 when the people put the same answer that my retemv”
This is probably what you are looking for:
def set_payoff(self):
if self.J11 == Constants.retemv:
self.payoff = Constants.participation_fee + Constants.iat + Constants.payment
else:
self.payoff = Constants.participation_fee + Constants.iat
On the function, confirmAnswer, it updates the question but doesn't display to the user whether their answer is correct or inccorrect which makes me think it is skipping straight to this line, if self.Qn < self.recordNum['text']: on the same function.
I only have two questions in the database at the moment allowing testing to be easier and when the question updates, the submit button doesnt work when an answer is inputted when really the quiz should end and display the score which is in the same function.
I included this much code as I thought it would make more sense to understand the code so sorry if it is too much and sorry if it comes across confusing. Thank you for your help!
def quiz(self):
self.newf.pack_forget()
self.head['text'] = 'Welcome to the psychology revision quiz'
self.quizf.pack()
self.quizScore = 0
self.correctAnswer = '' # <-- create it at start (and use better name)
self.Qn = 1
self.update_question()# <-- get new question
self.update_question_number()
def update_question_number(self):
# Get question's number
query = "SELECT MAX(qnumber) FROM questions"
c.execute(query)
row = c.fetchone()
self.recordNum['text'] = row[0]
def update_question(self):
# Get new question
query = "SELECT * FROM questions WHERE qnumber=?"
c.execute(query, (self.Qn,))
row = c.fetchone()
self.question['text'] = row[1]
self.answer1['text'] = row[2]
self.answer2['text'] = row[3]
self.answer3['text'] = row[4]
self.answer4['text'] = row[5]
self.correctAnswer = row[6]
def confirmAnswer(self):
self.rightOrWrong = self.enterAnswer
if self.enterAnswer == self.correctAnswer:
self.rightOrWrong['text'] = "Correct"
self.quizScore += 1
self.update_question()
else:
self.rightOrWrong['text'] = "Incorrect"
if self.Qn < self.recordNum['text']:
self.Qn += 1 # <-- get new question
self.update_question() # <-- get new question
else:
self.rightOrWrong['text'] = "Quiz Complete! Your score was: {}".format(self.quizScore)
I want to display a cart page that shows the items the user wants to buy. Before adding an item to the cart, I want to make sure that item has not been already added (as each item is singular and unique).
The way each item is modeled:
class SellModel(db.Model):
user = db.ReferenceProperty(UserModel)
amount = db.StringProperty(required = True)
price = db.StringProperty(required = True)
num = db.IntegerProperty(required = True)
def render(self):
return render_str("sellmodel.html", s = self)
The way each item displayed in the cart is modeled:
class CartModel(db.Model):
user = db.ReferenceProperty(UserModel)
num = db.IntegerProperty(required = True)
def render(self):
return render_str("cartmodel.html", c = self)
the code in the post method of the buy page where i check for item duplication includes
sells = SellModel.all().ancestor(sell_key()).order('price')
and
#did user already put the same item (num) in cart?
item_check = CartModel.all().filter("email = ", email)
item_check = item_check.filter("num = ", num)
item_count = 0
if item_check: #order already added to cart!
self.write("ELLOHAY")
item_count = 1
if item_count == 0:
cart = CartModel(parent = cart_key(), user = user, num = num)
cart.put()
numkey = SellModel.gql('where num = :num', num = num)
derp = numkey.get()
amount = derp.amount
price = derp.price
self.render('newbuy.html', first_name = first_name, amount = amount, price = price)
else:
cart_error = "this order is already in your cart"
self.render("buy.html", cart_error = cart_error, sells = sells)
The problem: no CartModel entities exist yet. Zero. The datastore viewer doesn't even show the CartModel entity kind. Yet when I run this code, sure enough, "ELLOHAY" prints and the buy page is rendered with the error message that the user has already added the order to the cart? Why is item_check returning an entity when it shouldn't?
This line of code is incorrect
if item_check: #
item_check is defined as
item_check = CartModel.all().filter("email = ", email)
item_check = item_check.filter("num = ", num)
At no point do you do a run(), fetch() or get()
At the time of the comparison if item_check item_check is a Query object and will evaluate to true. You need to actually run the query and examine the results - get() is probably a good start.
Also I see a number of other potential issues you will face with eventual consistancy but that isn't what you question is about.
you can do like this -
if item_check.exists():
self.write("ELLOHAY")
item_count = 1
This will not go inside the loop if item_check has no records.
When I increment one of my variables, it only goes up to 2 instead of 3. The default value is 1. I am not sure what I am missing. Any help is appreciated.
def unanswered(request, template ='unanswered.html'):
phone_number = Pool.objects.order_by('?')[0]
pool = Pool.objects.order_by('?')[0]
pool_list = Pool.objects.all()
number_attempts = Pool.objects.filter(phone_number=phone_number).count()
# unanswer number action
if pool_list:
if number_attempts > 3:
return number_attempts
else:
x = number_attempts
x += 1
print x 'returns 2'
store = Pool(id=phone_number.id,
phone_number = phone_number.phone_number,
un_answered=x, answered=0)
store.save()
payload = {'pool':pool,}
return render_to_response(template, payload, context_instance=RequestContext(request))
There is no any for loop or while loop in your code, so if initial number_attempts is 1, it will incremented to 2 and complete the flow.
I see you want to store attempts in the DB, but the way you are doing is not correct. You are passing id=phone_number.id to Store(...), which will try to update existing record if exists with given id. So Pool.objects.filter(phone_number=phone_number).count() always returns 1.
You may want to change it to
store = Pool(phone_number = phone_number.phone_number,
un_answered=x, answered=0)
So for the next request, Pool.objects.filter(phone_number=phone_number).count() will give you 2.
Update after the comment:
All I want is to update the un_answered field from 1,2,3.
In that case, don't use .count() to get number of failed attempts use the field from object that has that counter.
So instead of
number_attempts = Pool.objects.filter(phone_number=phone_number).count()
you can do this
try:
store = Pool.objects.get(phone_number=phone_number)
number_attempts = store.un_answered
# FIX : the original code used a bare except clause.
# Bare except clauses are EVIL. DONT use bare except clauses. NEVER.
# Or thou shall burn in the flames of hell for your eternal death....
except Pool.DoesNotExist:
store = Pool(phone_number = phone_number.phone_number,
un_answered=1, answered=0)
store.save()
number_attempts = 1
...
if pool_list:
if number_attempts > 3:
return number_attempts
else:
x = number_attempts
x += 1
print x 'returns 2'
store.un_answered = x
store.save()