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? - cs50

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.

Related

Python Django: deleting an object

I'm looking to delete an object in Django, but none of the other Stack Overflow questions fix mine. I looked at this one, but it doesn't seem to be working. My delete object code (in the views file) looks like this:
#login_required
def delete_entry(request, entry_id):
"""Delete an existing entry."""
if request.method != 'POST':
# No data submitted; create a blank form.
form = TopicForm()
else:
# POST data submitted; process data.
form = TopicForm(data=request.POST)
if form.is_valid():
new_topic = form.delete(commit=False) ### Code to delete object
new_topic.owner = request.user
new_topic.save()
return redirect('learning_logs:topics')
# Display a blank or invalid form.
context = {'topic': topic, 'form': form}
return render(request, 'learning_logs/new_entry.html', context)
And in URLs.py:
path('delete_entry/<int:entry_id>', views.delete_entry, name='delete_entry'),
I would like to use a Bootstrap 4 button (inside a modal) to delete the entry (so without any redirects to another confirmation page),
Unfortunately, this isn't working. I'm just getting a server error saying that NoReverseMatch at /delete_entry/6.
What does this mean?
It seems like you're trying to call the delete method on the form. If you want to delete the object, you should call it on the object:
my_object = MyModel.objects.get(id=entry_id) # Retrieve the object with the specified id
my_object.delete() # Delete it
Here is the relevant Django documentation.
I think that you're looking for a DeleteView.

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

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.

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

In this context, is there anyway I can use requests.post() without also using BeautifulSoup?

I've spent the day day and-a-half (I'm a beginner) trying to work out how to do something simple: Fill in an ID code and hit 'search'. I've read the requests docs and scoured stack overflow for examples, but none seem to help me.
What I want to do is run through a list of IDs that I have and check off which one's are valid and which are invalid. (This is for academic research)
Here's my code:
import requests
url = 'https://ndber.seai.ie/pass/ber/search.aspx'
payload = {'ctl00$DefaultContent$BERSearch$dfSearch$txtBERNumber':'100000000'
}
#the above dictionary key corresponds to the name , found using Firefox inspector in the source code.
#I have tried using input ID too with no difference in outcome
#enter in arbitrary number of '100000000'- expect to see 'Invalid ID Number' printed
r = requests.post(url, data = payload)
print(r.status_code, r.reason)
print(r.text)
if 'Number.'in r.text: #'Number' is an arbitrary word that happens to be in the page if a correct ID code is entered
print('Valid ID Number')
elif 'No results found.' in r.text: #as above, 'No results found' is in the page if an incorrect ID is entered
print('Invalid ID Number') #with the aboove number entered, I would expect this line to be printed
else:
print('Code Failure') #this line gets printed
I've tried to comment it as much as possible, so you can see what I'm at.
The output I get is Code Failure
The reason why BeautifulSoup comes into all this is because I asked for help on Reddit's excellent 'learn python' subreddit yesterday. A Redditor generously took the time to try to explain where I went wrong and what I should do differently. Here's what (s)he suggested I do:
enter image description here, which involves BS4.
So, is the Redditor right, or can this be done in a simple and 'light' way using the requests library?
Cheers!
Make sure to simulate exact same post with parameters, you can use firefox's firebug to see what parameters are beeing sent.
Below you can see the parameters, I've seen.
__EVENTARGUMENT=
__EVENTTARGET=
__EVENTVALIDATION=/wEdAAUFK13s0OHvBcOmXYSKCCYAA5nYY19nD30S2PPC/bgb6yltaY6CwJw6+g9S5X73j5ccPYOXbBJVHSWhVCIjHWYlwa4c5fa9Qdw0vorP2Y9f7xVxOMmbQICW5xMXXERtE7U18lHqXqDZVqJ8R/A9h66g
__SCROLLPOSITIONX=0
__SCROLLPOSITIONY=114
__VIEWSTATE=/wEPDwULLTE2MDEwODU4NjAPFgIeE1ZhbGlkYXRlUmVxdWVzdE1vZGUCARYCZg9kFgICAw9kFgICAw8WAh4FY2xhc3MFC21haW53cmFwcGVyFgQCBQ8PFgIeB1Zpc2libGVnZGQCCQ9kFgICAQ9kFgxmD2QWAgIBD2QWAgIBD2QWAmYPZBYCZg9kFgQCAQ8WAh4JaW5uZXJodG1sZWQCAw9kFgICAg9kFgJmD2QWBAIBD2QWAgIDDw8WCh4EXyFTQgKAAh4MRGVmYXVsdFdpZHRoHB4EVGV4dAUFY3RsMDAeB1Rvb2xUaXAFPlBsZWFzZSBlbnRlciBhIHZhbHVlLCB3aXRoIG5vIHNwZWNpYWwgY2hhcmFjdGVycywgd2l0aCBubyB0ZXh0HgVXaWR0aBxkZAIDD2QWAgIDDw8WCh8EAoACHwUcHwYFCTEwMDAwMDAwMB8HBT5QbGVhc2UgZW50ZXIgYSB2YWx1ZSwgd2l0aCBubyBzcGVjaWFsIGNoYXJhY3RlcnMsIHdpdGggbm8gdGV4dB8IHGRkAgQPFCsAAmQQFgAWABYAFgJmD2QWAgICD2QWAmYPPCsAEQIBEBYAFgAWAAwUKwAAZAIGDxYCHwJoFgQCAQ8WAh8CaGQCAw9kFgJmD2QWAmYPZBYCAgMPZBYCZg9kFgJmD2QWAgIBDxYCHwJoZAIIDxYCHwJoFgQCAQ8WAh8CaGQCAw9kFgJmD2QWAmYPZBYCAgMPZBYCZg9kFgJmD2QWAgIBDxYCHwJoZAIKDxYCHwJoFgQCAQ8WAh8CaGQCAw9kFgJmD2QWAmYPZBYCAgMPZBYCZg9kFgJmD2QWAgIBDxYCHwJoZAIMDxYCHwJoFgQCAQ8WAh8CaGQCAw9kFgJmD2QWAmYPZBYCAgMPZBYCZg9kFgJmD2QWAgIBDxYCHwJoZBgBBTNjdGwwMCREZWZhdWx0Q29udGVudCRCRVJTZWFyY2gkZ3JpZFJhdGluZ3MkZ3JpZHZpZXcPZ2QPHVcTs3MrN3SZqli/KiHgWASd1DRvCLPuS7Rs+GRQAQ==
__VIEWSTATEGENERATOR=1F9CCB97
ctl00$DefaultContent$BERSearch$dfSearch$Bottomsearch=Search
ctl00$DefaultContent$BERSearch$dfSearch$txtBERNumber=2313131
ctl00$DefaultContent$BERSearch$dfSearch$txtMPRN=11111111111
And belowe code just worked,
from __future__ import unicode_literals
import requests
url = 'https://ndber.seai.ie/pass/ber/search.aspx'
payload = {'__EVENTVALIDATION':'/wEdAAUFK13s0OHvBcOmXYSKCCYAA5nYY19nD30S2PPC/bgb6yltaY6CwJw6+g9S5X73j5ccPYOXbBJVHSWhVCIjHWYlwa4c5fa9Qdw0vorP2Y9f7xVxOMmbQICW5xMXXERtE7U18lHqXqDZVqJ8R/A9h66g',
'__VIEWSTATE':'/wEPDwULLTE2MDEwODU4NjAPFgIeE1ZhbGlkYXRlUmVxdWVzdE1vZGUCARYCZg9kFgICAw9kFgICAw8WAh4FY2xhc3MFC21haW53cmFwcGVyFgQCBQ8PFgIeB1Zpc2libGVnZGQCCQ9kFgICAQ9kFgxmD2QWAgIBD2QWAgIBD2QWAmYPZBYCZg9kFgQCAQ8WAh4JaW5uZXJodG1sZWQCAw9kFgICAg9kFgJmD2QWBAIBD2QWAgIDDw8WCh4EXyFTQgKAAh4MRGVmYXVsdFdpZHRoHB4EVGV4dAUFY3RsMDAeB1Rvb2xUaXAFPlBsZWFzZSBlbnRlciBhIHZhbHVlLCB3aXRoIG5vIHNwZWNpYWwgY2hhcmFjdGVycywgd2l0aCBubyB0ZXh0HgVXaWR0aBxkZAIDD2QWAgIDDw8WCh8EAoACHwUcHwYFCTEwMDAwMDAwMB8HBT5QbGVhc2UgZW50ZXIgYSB2YWx1ZSwgd2l0aCBubyBzcGVjaWFsIGNoYXJhY3RlcnMsIHdpdGggbm8gdGV4dB8IHGRkAgQPFCsAAmQQFgAWABYAFgJmD2QWAgICD2QWAmYPPCsAEQIBEBYAFgAWAAwUKwAAZAIGDxYCHwJoFgQCAQ8WAh8CaGQCAw9kFgJmD2QWAmYPZBYCAgMPZBYCZg9kFgJmD2QWAgIBDxYCHwJoZAIIDxYCHwJoFgQCAQ8WAh8CaGQCAw9kFgJmD2QWAmYPZBYCAgMPZBYCZg9kFgJmD2QWAgIBDxYCHwJoZAIKDxYCHwJoFgQCAQ8WAh8CaGQCAw9kFgJmD2QWAmYPZBYCAgMPZBYCZg9kFgJmD2QWAgIBDxYCHwJoZAIMDxYCHwJoFgQCAQ8WAh8CaGQCAw9kFgJmD2QWAmYPZBYCAgMPZBYCZg9kFgJmD2QWAgIBDxYCHwJoZBgBBTNjdGwwMCREZWZhdWx0Q29udGVudCRCRVJTZWFyY2gkZ3JpZFJhdGluZ3MkZ3JpZHZpZXcPZ2QPHVcTs3MrN3SZqli/KiHgWASd1DRvCLPuS7Rs+GRQAQ==',
'__VIEWSTATEGENERATOR':'1F9CCB97',
'ctl00$DefaultContent$BERSearch$dfSearch$Bottomsearch':'Search',
'ctl00$DefaultContent$BERSearch$dfSearch$txtBERNumber':'2313131',
'ctl00$DefaultContent$BERSearch$dfSearch$txtMPRN':'11111111111'
}
session = requests.session()
r = requests.post(url, data=payload)
if 'Number.'in r.text: #'Number' is an arbitrary word that happens to be in the page if a correct ID code is entered
print('Valid ID Number')
elif 'No results found.' in r.text: #as above, 'No results found' is in the page if an incorrect ID is entered
print('Invalid ID Number') #with the aboove number entered, I would expect this line to be printed
else:
print('Code Failure') #this line gets printed"""
Just put your parameters in the payload dictionary, rest of the parameters can stay they I think
BER/DEC Number > ctl00$DefaultContent$BERSearch$dfSearch$txtBERNumber
MPRN > ctl00$DefaultContent$BERSearch$dfSearch$txtMPRN

url redirect with kwargs no NoReverseMatch

main-project urls.py :
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'', include('data.urls')),
]
urls.py :
urlpatterns = [
url(r'^doll/$', views.doll_describer),
url(r'^yourdolldata/(?P<id>\d+)/$', views.yourDollData),
url(r'^connexion/$', views.connexion),
url(r'^logout/$', views.deconnexion),
]
views.py
def doll_describer(request):
# if this is a POST request we need to process the form data
if request.method == 'POST':
# create a form instance and populate it with data from the request:
form = DollForm(request.POST)
print(form)
# check whether it's valid:
if form.is_valid():
print("was valid")
doll = form.save(commit=False)
doll.save()
print("DOG.ID=",doll.id)
return HttpResponseRedirect(reverse('yourDollData', kwargs={'id': doll.id}))
else :
print("form is not valid")
# if a GET (or any other method) we'll create a blank form
else:
form = DollForm()
print("wasn't valid")
return render(request, 'data/doll.html', {'form':DollForm})
def yourDollData(request,id):
doll = DollData.objects.get(id=id)
print("Doll=",doll)
print("DOG_TYPE=",type(doll))
return render(request, 'data/save.html', {'doll': doll})
I can't understand why i'm getting the following error :
NoReverseMatch at /doll/
And it concerns the HttpResponseRedirect(reverse('yourDollData', kwargs={'id': doll.id}))
Tough, everything's fine with the doll.id which is printed out correctly one line before.
Of course when I hard access in my browser to 127.0.0.1:8000/yourdolldata/15/ it works perfectly. So it's all about this reversing process. I guess it has something to do with my url regex not matching what I think I'm reversing ...
How can i get that fixed ? I know it's a common mistake but I can't see any thing done the wrong way after I've done my internet research.
Add a name to the url attached to the view you are trying to reverse :
url(r'^yourdolldata/(?P<id>\d+)/$', views.yourDollData, name='check_doll_data')
Take the previous name as the argument of reversefunction .
return HttpResponseRedirect(reverse('check_doll_data',kwargs={'id': dog.id}))
Reverse can take an url, a view name, or the name of a view attached to an url as first argument.

Resources