Doing cs50 Finance and "buy" is generating a run time error - cs50

My error is where I adjust cash to reflect the purchase of stock. The command line error is: RuntimeError: near "['user_id']": syntax error. I have used both " " and ' ' correctly within the line of code. Also further up in command line I got: ERROR: Exception on /buy [POST], which I don't understand. Please let me know if you have any thought. Thanks.
#app.route("/buy", methods=["GET", "POST"])
#login_required
def buy():
"""Buy shares of stock"""
if request.method == "POST":
# Ensure ticker was submitted
if not request.form.get("symbol"):
return apology("must input stock symbol")
# Get symbol and make sure it exists
symbol = lookup(request.form.get("symbol"))
if not symbol:
return apology("symbol does not exist")
# Ensure shares entered greater than zero
number=int(request.form.get("shares"))
if number <= 0:
return apology("must enter number of shares to buy")
# set up dict to store purchase info: name, price, symbol
quote = lookup(request.form.get("symbol"))
# Dollars needed for purchase
pcash=number * quote["price"]
# Is there enough cash in account to purchase
ecash = db.execute("SELECT cash FROM users WHERE id = ?", session["user_id"])
if pcash >= ecash[0]["cash"]:
return apology("Not enough cash to buy that amount of stock")
# Record buy in trades.db for user-id
x=datetime.datetime.now()
db.execute("INSERT INTO trades (datetime, symbol, shares, price, total, id) VALUES(?, ?, ?, ?, ?, ?)", x, quote["symbol"], number, quote["price"], pcash, session["user_id"])
# Adjust cash to reflect purchase
y=ecash[0]["cash"]-pcash
db.execute("UPDATE users SET cash=? WHERE id=session['user_id']", y)
# Redirect user to home page
return redirect("/")
# User reached route via GET (as by clicking a link or via redirect)
else:
return render_template("buy.html")

This UPDATE users SET cash=? WHERE id=session['user_id'] is the query that sqlite is trying to execute. sqlite doesn't know from session['user_id'] (it's a python variable). The method will accept multiple placeholders (ie ?). Use a placeholder for the WHERE clause, and send the value as an additional argument.

Related

How to Clear Odoo 15 Cart

Good day,
We want to only allow one product order in Odoo Cart, although we are selling all products on our website.
We want a customer to only order one product at a time, so my question is How can I clear the cart in Odoo 15 when it is not empty every time a customer click Add to Cart.
We have thought of changing the add to cart function but we have failed please help.
#http.route(['shop/cart/update'], type='http', auth="public", methods=['POST'], website=True)
def cart_update(self, product_id, add_qty=1, set_qty=0, **kw):
"""This route is called when adding a product to cart (no options)."""
sale_order = request.website.sale_get_order(force_create=True)
if sale_order.state != 'draft':
request.session['sale_order_id'] = None
sale_order = request.website.sale_get_order(force_create=True)
product_custom_attribute_values = None
if kw.get('product_custom_attribute_values'):
product_custom_attribute_values = json_scriptsafe.loads(kw.get('product_custom_attribute_values'))
no_variant_attribute_values = None
if kw.get('no_variant_attribute_values'):
no_variant_attribute_values = json_scriptsafe.loads(kw.get('no_variant_attribute_values'))
sale_order._cart_update(
product_id=int(product_id),
add_qty=add_qty,
set_qty=set_qty,
product_custom_attribute_values=product_custom_attribute_values,
no_variant_attribute_values=no_variant_attribute_values
)
if kw.get('express'):
return request.redirect("/checkout?express=1")
return request.redirect("/cart")
You could simple always delete the order_line records from the order in the add_to_cart function.
Would be something like this :
#http.route(['shop/cart/update'], type='http', auth="public", methods=['POST'], website=True)
def cart_update(self, product_id, add_qty=1, set_qty=0, **kw):
"""This route is called when adding a product to cart (no options)."""
sale_order = request.website.sale_get_order(force_create=True)
if sale_order.state != 'draft':
request.session['sale_order_id'] = None
sale_order = request.website.sale_get_order(force_create=True)
# Delete the lines if there are some:
if sale_order.order_line:
sale_order.order_line.unlink()
# ...
In case you have an error for unauthorized operation, you'll have to sudo() your sale_order so sale_order.sudo().order_line.unlink()

When I try to get a quote for nflx my code tells me symbol does not exist. Below is my code. I can not find my error. Thoughts?

Here is the code to check symbol inputed correctly, then to show name, price and symbol on the quoted template.
#app.route("/quote", methods=["GET", "POST"])
#login_required
def quote():
"""Get stock quote."""
if request.method == "POST":
# Ensure ticker was submitted
if not request.form.get("symbol"):
return apology("must input stock symbol")
# Get symbol and make sure it exists
quote = lookup(request.form.get("symbol"))
if not quote:
return apology("symbol does not exist")
# to show company name, price, symbol
else:
return render_template("quoted.html", quote=quote)
# User reached route via GET (as by clicking a link or via redirect)
else:
return render_template("quote.html")
IEX changed the API. You can find the new code for lookup function in helpers.py at this reddit post
No, lookup() is correct in helpers.py. And I could get a quote from CS50 answer. Is there some way to check if my token is correct? I can log on to my finance app, but can't get a quote.

How to set daily update limit for django model(db)?

Hi I'm having one Django web app where My model A contains 1000 records and I want to set a daily update limit for example if users are updating that data by uploading a .xls file then it should count how many records updated and once it is more than 500 then the user should get an Error message(Is there Any easy way to implement this at file processing level).
Can Anyone help me how to implement this (Is there an SQLite parameter that I can mention in settings.py)
below is my upload code. (Here I have tried to store the count value and comparing it with half of the record but again how to reset it after 12/certain time/hrs?)
def CTA_upload(request):
try:
if request.method == 'POST':
movie_resource = CTAResource()
##we will get data in movie_resources####
dataset = Dataset()
new_movie = request.FILES['file']
if not new_movie.name.endswith('xls'):
messages.info(request, 'Sorry Wrong File Format.Please Upload valid format')
return render(request, 'apple/uploadinfosys.html')
messages.info(request, 'Uploading Data Line by Line...')
imported_data = dataset.load(new_movie.read(), format='xls')
count = 1
for data in imported_data:
value = CTA(
data[0],
data[1],
data[2],
data[3],
data[4],
data[5],
data[6],
data[7],
data[8],
)
count = count + 1
value.save()
# messages.info(request, count)
# time.sleep(1)
messages.info(request, 'File Uploaded Successfully...')
except:
messages.info(request,
'Same Email ID has been observed more than once.Except that other records has been added../nPlease Make sure Email field should be unique.')
return render(request, 'app/cta.html')

CS50 Finance : Issue with code for Register

I am unable to execute Register. Everytime i try to Register, it moves me to Apology.html even when the credentials are correct. Can anyone please review below excerpt from my application.py and help me resolve this?
if request.method == "POST":
# Ensure username was submitted
if not request.form.get("username"):
return apology("must provide username", 400)
# Ensure password was submitted
elif not request.form.get("password"):
return apology("must provide password", 400)
# Ensure password and confirmation match
elif not request.form.get("password") == request.form.get("confirmation"):
return apology("passwords do not match", 400)
# hash the password and insert a new user in the database
hash = generate_password_hash(request.form.get("password"))
new_user_id = db.execute("INSERT INTO users (username, hash) VALUES(:username, :hash)",
username=request.form.get("username"),
hash=hash)
# unique username constraint violated?
if not new_user_id:
return apology("username taken", 400)
# Remember which user has logged in
session["user_id"] = new_user_id
# Display a flash message
flash("Registered!")
# Redirect user to home page
return redirect(url_for("index"))
# User reached route via GET (as by clicking a link or via redirect)
else:
return render_template("register.html")
It looks like your confirm password has a space in it. If a request is coming via HTML, this may be causing you trouble (as it will have to convert to HTML URL encoding, which is %20 for a space).
Try changing your HTML and your code to use a hyphen, or an underscore, or simply make it one word.
HTH
Hey I think that your code is meant to say
elif not request.form.get("password") **!=** request.form.get("confirmation"):
However currently it says
elif not request.form.get("password") **==** request.form.get("confirmation"):
Therefore even when it matches it is still returning an apology

Accessing a database of ID numbers to validate against an entered number Python3

I'm trying to get the user to enter in a pin number (four numbers) which the database will then validate by looking at the customer ID's. At the moment, it works if I get the user to enter any of the ID pins and I program it so they can enter any ID for them to access, but I want them to access their own accounts. So if I enter, for example, Jeremy's unique pin, it will prompt me with a hello Jeremy message. At the moment, if I enter a four digit number, nothing simply happens. The code I have so far is :
def entryID():
print("Hello")
print()
print()
print("Welcome to the Northern Frock ATM system")
time.sleep(2)
print("In order for you to access the machine, you must enter a correct PIN")
with sqlite3.connect("ATM.db") as db:
cursor = db.cursor()
cursor.execute("select CustomerID from ATM")
userIDs = cursor.fetchall()
print(userIDs)
UserID = input("Please enter your Customer ID. If you want to quit, type in 99999\n")
if UserID == userIDs[0]:
print('Hello smack')
elif UserID == userIDs[1]:
print("Hello joe")
elif UserID == userIDs[2]:
print("Hellow Snow")
elif UserID == userIDs[3]:
print("Hellow Moe")
fetchall() returns a list of rows. Each row is a list of column values.
So userIDs[0] is the first row, i.e., something like (1234,).
To access the actual value, you have to extract the first column from the row:
if UserID == userIDs[0][0]:
...
Please note that a query can return results in a random order unless you are using ORDER BY.
And it might be a better idea to store the customer names in the database, and load only the one you want:
cursor.execute('SELECT Name FROM ATM WHERE CustomerID = ?', [UserID])
for (name,) in cursor:
print("Hello " + name)
else:
print("wrong!")

Resources