CS50 finance (pset9)- My buy function and index is not working properly - cs50

My buy function cannot seem to update the transaction and also after the purchase is complete it does not return to the render template. I would really appreciate some help. Thank you so much!!
This is my app.py code
#app.route("/buy", methods=["GET", "POST"])
#login_required
def buy():
"""Buy shares of stock"""
if request.method == "POST":
symbol = request.form.get("symbol")
item = lookup(symbol)
if not symbol:
return apology("Please give Symbol")
elif not item:
return apology("Invalid Symbol")
try:
shares = int(request.form.get("shares"))
except:
return apology("Shares should be an integer")
if shares < 0:
return apology("Shares should be positive")
user_id = session["user_id"]
cash = db.execute("SELECT cash FROM users WHERE id = ?", user_id)[0]["cash"]
item_name = item["name"]
item_price = item["price"]
total_price = item_price * shares
if cash < total_price:
return apology("Not enough money")
else:
db.execute("UPDATE users SET cash = ? WHERE id = ?",cash - total_price, user_id)
db.execute("INSERT INTO transactions (user_id, names, shares, prices, type, symbol) VALUES(?, ?, ?, ?, ?, ?)", session["user_id"], item_name, shares, item_price, "buy", symbol)
flash("Transaction complete")
return redirect("/")
else:
return render_template("buy.html")

Related

In Django filter argument key not define error

my model is
class Employee(models.Model):
first_name=models.CharField(max_length=100, null=False)
last_name=models.CharField(max_length=100)
dept = models.ForeignKey(Department,on_delete=models.CASCADE)
salary = models.IntegerField(default=0)
bonus = models.IntegerField(default=0)
role = models.ForeignKey(Role, on_delete=models.CASCADE)
phone = models.IntegerField(default=0,max_length=12)
hire_date = models.DateField(default=datetime.now()
and my view is as
def fil_emp(request):
if request.method == "POST":
# print("post received")
# print(request.POST)
name = request.POST['first_name']
d = request.POST['department']
role = request.POST['role']
emps = Employee.objects.all()
if name:
emps = emps.filter(Q(first_name__icontains== name) | Q(last_name__icontains == d))
if d:
pass
if role:
pass
return render(request, 'fil_emp.html')
but at this time i received error
like
**
"first_name__icontains" is not defined
**
You are given == to check the condition. Change the following line like this:
emps = emps.filter(Q(first_name__icontains = name) | Q(last_name__icontains = d))
For more, you can see the official doc of Django: https://docs.djangoproject.com/en/4.0/ref/models/querysets/#django.db.models.Q

Flask-SQLAlchemy loop transaction

I am building a wallet balance management system. I use Flask-SQLAlchemy with Python 3.8.
In this case I need to add multiple products in a loop (I have simplified the function).
For each added product I first create a transaction line, then I create a product line in different tables.
After completing the loop I reduce the total price from the wallet.
I check that the new balance is more than 0, otherwise I cancel the transactions (All the added lines and the wallet action).
Now the loop portion works just fine. But the user.balance = user.balance - price does not get executed. user is a database object that I get from get_user_details.
There is no errors.
What am I missing?
def put_data(data, pproduct, price):
user = get_user_details()
multi_product = data.get(MULTI_PR, 1) if data.get(MULTI_PR, 1) != -1 else 1
product_number = int(get_product_num(pproduct))
# Start transaction
db.session.begin()
for index, product_id in enumerate(list(range(product_number, product_number + multi_product))):
transaction_id = gen_trn_uid()
transaction = transactions.Transaction()
transaction.transaction_id = transaction_id
transaction.status = "init"
transaction.user_id = user.id
transaction.sum = price / multi_product
transaction.transaction_date = datetime.now()
db.session.add(transaction)
db.session.flush()
product = game_products.ProductForm()
product.product = pproduct
product.data = str(data)
product.status = 'init'
product.time = datetime.now()
product.user_id = user.id
games_form.product_number = product_id
product.transaction_id = transaction.id
db.session.add(product)
db.session.flush()
user.balance = user.balance - price
db.session.flush()
if user.balance < 0:
db.session.rollback()
raise HTTPException(HTTPStatus.PAYMENT_REQUIRED, 'insufficient balance',
name='Err 713')
db.session.commit()
session.flush() communicates a series of operations to the database (insert, update, delete). The database maintains them as pending operations in a transaction. The changes aren't persisted permanently to disk, or visible to other transactions until the database receives a COMMIT for the current transaction (which is what session.commit() does).
can you try to commit first then use user.balance = user.balance - price ?
something like this.
def put_data(data, pproduct, price):
user = get_user_details()
multi_product = data.get(MULTI_PR, 1) if data.get(MULTI_PR, 1) != -1 else 1
product_number = int(get_product_num(pproduct))
# Start transaction
db.session.begin()
for index, product_id in enumerate(list(range(product_number, product_number + multi_product))):
transaction_id = gen_trn_uid()
transaction = transactions.Transaction()
transaction.transaction_id = transaction_id
transaction.status = "init"
transaction.user_id = user.id
transaction.sum = price / multi_product
transaction.transaction_date = datetime.now()
db.session.add(transaction)
db.session.flush()
product = game_products.ProductForm()
product.product = pproduct
product.data = str(data)
product.status = 'init'
product.time = datetime.now()
product.user_id = user.id
games_form.product_number = product_id
product.transaction_id = transaction.id
db.session.add(product)
db.session.flush()
db.session.commit()
user.balance = user.balance - price
if user.balance < 0:
db.session.rollback()
raise HTTPException(HTTPStatus.PAYMENT_REQUIRED, 'insufficient balance',
name='Err 713')
db.session.flush()
db.session.commit()

Updating information in database issue

Hi I'm trying to update some entries in my database but I having a problem updating the correct information specified in a value.
My code block below shows a command that allows users to give a user XP. What I am trying to achieve is to update both values val_1 and val_2 however val_2 xp-amount, total_xp-amount is incorrectly deducting a bigger amount (number) from than the specified amount when the command is invoked. For example when !xp #user 5 is invoked it should give the mentioned #user 5 XP and also take 5XP from the user who invoked the command.
Here is what I'm working with:
async def xp(self, ctx, user: discord.Member, amount: int):
conn = psycopg2.connect(DATABASE_URL, sslmode='require')
cursor = conn.cursor()
cursor.execute(f"SELECT lvl, xp, total_xp FROM levels WHERE guild_id = {ctx.guild.id} AND user_id = {user.id}")
result2 = cursor.fetchone()
xp = int(result2[1])
total_xp = int(result2[2])
if user.id == ctx.message.author.id:
await ctx.send("You can't give yourself XP.")
return
if int(amount) > 50:
await ctx.send("You can only give a maximum of 50 XP.")
return
#SQL
sql = ("UPDATE levels SET xp=%s, total_xp=%s WHERE guild_id=%s and user_id=%s")
#The member recieving XP
val_1 = (xp+amount, total_xp+amount, str(ctx.guild.id), str(user.id))
cursor.execute(sql, val_1)
#The member giving XP
val_2 = (xp-amount, total_xp-amount, str(ctx.guild.id), str(ctx.message.author.id))
cursor.execute(sql, val_2)
conn.commit()
cursor.close()
conn.close()
#return something here
await ctx.send(f"{ctx.message.author.name} has given {amount} XP to
{user.mention}.")
Help would be appreciated
first of all, you aren't getting the total-xp of both users, only the person who is invoking the command.
Before:
cursor.execute(f"SELECT lvl, xp, total_xp FROM levels WHERE guild_id = {ctx.guild.id} AND user_id = {user.id}")
result2 = cursor.fetchone()
xp = int(result2[1])
total_xp = int(result2[2])
if user.id == ctx.message.author.id:
await ctx.send("You can't give yourself XP.")
return
if int(amount) > 50:
await ctx.send("You can only give a maximum of 50 XP.")
return
#SQL
sql = ("UPDATE levels SET xp=%s, total_xp=%s WHERE guild_id=%s and user_id=%s")
#The member recieving XP
val_1 = (xp+amount, total_xp+amount, str(ctx.guild.id), str(user.id))
cursor.execute(sql, val_1)
#The member giving XP
val_2 = (xp-amount, total_xp-amount, str(ctx.guild.id), str(ctx.message.author.id))
cursor.execute(sql, val_2)
Fixed:
cursor.execute(f"SELECT lvl, xp, total_xp FROM levels WHERE guild_id = {ctx.guild.id} AND user_id = {ctx.message.author.id}")
result2 = cursor.fetchone()
xp = int(result2[1])
sender_total_xp = int(result2[2])
if user.id == ctx.message.author.id:
await ctx.send("You can't give yourself XP.")
return
if int(amount) > 50:
await ctx.send("You can only give a maximum of 50 XP.")
return
cursor.execute(f"SELECT lvl, xp, total_xp FROM levels WHERE guild_id = {ctx.guild.id} AND user_id = {user.id}")
result = cursor.fetchone()
receiver_total_xp = int(result[2])
#SQL
sql = ("UPDATE levels SET xp=%s, total_xp=%s WHERE guild_id=%s and user_id=%s")
#The member recieving XP
val_1 = (xp+amount, receiver_total_xp+amount, str(ctx.guild.id), str(user.id))
cursor.execute(sql, val_1)
#The member giving XP
val_2 = (xp-amount, sender_total_xp-amount, str(ctx.guild.id), str(ctx.message.author.id))
cursor.execute(sql, val_2)
as you can see, you've been requesting the incorrect data from the database because you were using user.id (which is the target id, i.e. the person receiving the xp) instead of ctx.message.author.id which is the person who invoked the command.
there was also the issue of you setting the sender's xp to be -5 the receiver's xp.

How to get a certain value from an array of objects in python

ok so this is my program so far to operate as an ordering system of a cafe with multiple items. My goal is to calculate the price of an order, store that order to keep count of which coffee was ordered and how many of that coffee was ordered. Right now I am stuck on calculating the order total for an order. The main problem im stuck on is getting the coffee price of a coffee based on what the user wants, say if i want x coffee, i need to get the price of that coffee. I've stored instances of coffee in an array and right now I am not sure of how to get the price of a coffee to be used in the calculation of the total price
class Coffee(object):
def __init__ (self, coffee_type, price):
self.coffee_type = coffee_type
self.price = price
class Order(object):
def __init__(self, coffee_type, coffee_amount):
self.coffee_type = coffee_type
self.coffee_amount = coffee_amount
if name =="main":
coffee_available=[Coffee("1 : Flat White", 3.50),
Coffee("2 : Long Black", 3.50),
Coffee("3 : Cappuccino", 4.00),
Coffee("4 : Espresso", 3.25),
Coffee("5 : Latte", 3.50)]
ordering = 'Y'
total_cost = 0
while ordering == 'Y':
print("Coffee Type\t\tPrice")
print("-----------\t\t-----")
for coffee in coffee_available:
print("{}\t- - -\t$ {}".format(coffee.coffee_type,coffee.price))
print()
order_coffee = int(input("What is the number of the coffee you want? "))
order_amount = input("How many would you like to order? ")
new_order = None
if order_coffee >= 1 and order_coffee <=5:
coffee_choice = coffee_available[coffee.price]
new_order = Order(coffee_choice, order_amount)
total_cost = new_order.coffee_type * order_amount
else:
print ("Please enter a valid number")
dine_in = input('You like to dine in? (Y/N)')
dine_in = dine_in.upper()
if dine_in == 'Y' or 'YES':
total_cost = total_cost + (total_cost * 0.1)
print (total_cost)
Ordering = 'N'
elif dine_in == 'N' or 'No':
total_cost = total_cost
else:
print("Please enter a valid input")
continue
It's better to split the id of the coffee from the name:
class Coffee(object):
def __init__ (self, coffee_id, coffee_type, price):
self.coffee_id = coffee_id
self.coffee_type = coffee_type
self.price = price
Then when you create object use:
Coffee(1, "Flat White", 3.5)
And when you want the price use:
def get_price(coffee_available, coffee_id):
for coffee in coffee_available:
if coffee.coffee_id == coffee_id:
return coffee.price
return None

How do i use input variables to locate ids with UPDATE in sqlite3?

I'm trying to make a contacts list manageable by user input. Program asks what the user wants to do, either to add a new contact, edit a contact, delete a contact or show a list of contacts, if the user wants to edit contacts then he's asked for the id of the contact he wants to change, and then the row he wants to change(name, lastname or number).. What i don't know is, how do i go into using the sql UPDATE command together with that id the user gave, and then how do i use the new name, or last name or number given by the user with the same command, update? So that i the user can actually pick which contact to edit and what parameter to edit from the menu.
Here's my code.
import sqlite3
asd = True
while asd:
conn = sqlite3.connect('contactsdb.db')
c = conn.cursor()
c.execute('''DROP TABLE IF EXISTS contacts''')
c.execute('''CREATE TABLE contacts
(id INTEGER PRIMARY KEY, Nombre TEXT, Apellido TEXT, Numero de celular INTEGER)''')
# def agregarconbg():
# global nombre
# global apellido
# global numero
def agregarcon():
nombre = input("Add name")
apellido = input("Add lastname")
numero = input("Add number")
# c = conn.cursor()
c.execute("INSERT INTO contacts (nombre, apellido, numero) VALUES(?,?,?);",(nombre,apellido,numero))
conn.commit()
def editnom():
nuevonom = input("Add new name")
###################################################
###################################################
#########What do i do around here?!################
c.execute("UPDATE contacts set nombre where ID=1",(nuevonom))
conn.commit
# def editap():
#
# def editnum():
def editarcon():
print ("What id do you want to change?")
cambiar = input("Introduce the id you want to change:")
print("""What do you want to change
1 - Name
2 - Lastname
3 - Number""")
cambiarpar = int(input("Seleccion:"))
if cambiarpar == 1:
editnom()
elif cambiarpar == 2:
editap()
elif cambiarpar == 3:
editnum()
else:
print("Wrong INPUT")
# c = conn.cursor()
#def borrarcon():
# c = conn.cursor()
def printsql():
# c = conn.cursor()
c.execute('SELECT * FROM contacts ORDER BY id')
listT = ["ID","Nombre:","Apellido:","Numero:"]
k = 0
for i in c:
print("\n")
for j in i:
print (listT[k])
print(j)
if k < 3: k+=1
else: k = 0
conn.commit()
print('Agenda de contactos')
print('''Que deseas hacer?
1 - Add a contact
2 - Edit a contact
3 - Delete a contact
4 - Show contacts''')
seleccion = int(input("Seleccion:"))
if seleccion == 1:
agregarcon()
elif seleccion == 2:
editarcon()
conn.commit()
elif seleccion == 3:
borrarcon()
conn.commit
elif seleccion == 4:
printsql()
Pass Cambiar(ID) through as a parameter to editnom() and use that as part of the update statement, plus use nombre = variable to actually update the record
See this page for SQLite3 UPDATE
See this for how to pass variables through to functions in Python
def editnom(cambiar):
nuevonom = input("Add new name")
###################################################
###################################################
#########What do i do around here?!################
c.execute("UPDATE contacts set nombre = ? where ID=?",(nuevonom,cambiar))
conn.commit
if cambiarpar == 1:
editnom(cambiar)

Resources