Have Django traceback pinpoint where error occurred? - django

I have two questions about Django tracebacks.
First, if I have a traceback like the following, I can see that the error is occurring in the 'review_new_profile' view as shown in the second traceback error
below. Is it possible to tell Django to also display the line number in that view where the error occurred?
/srv/http/example.com/venvs/725be8a8537aeef8021231ba68de3184bbd547b1/local/lib/python2.7/site-packages/django/core/handlers/base.py in get_response
1. response = wrapped_callback(request, *callback_args, **callback_kwargs)
/srv/http/example.com/repo/profile/views.py in review_new_profile
1. user = User.objects.get(id=request.session['uid'])
/srv/http/example.com/venvs/725be8a8537aeef8021231ba68de3184bbd547b1/local/lib/python2.7/site-packages/django/contrib/sessions/backends/base.py in __getitem__
1. return self._session[key]
What I'd like to see is something like the following where '540' is the line number in the views.py:
/srv/http/example.com/repo/profile/views.py in review_new_profile (540)
1. user = User.objects.get(id=request.session['uid'])
Second, am I correct in in thinking that the error actually occurred at the bottom-most line? So an interpretation of this trace is that Django was trying to generate a response to a request but when it tried to get a user instance for a given uid, it couldn't find the uid in the session? In other words, the error actually occurred on the last line in the traceback, where Django was trying to get the uid (key) from the session?

For your first question, Django does show the line. In your case, those 1s are the line numbers. The real question is why they are all 1s.
Second question: you are correct. The exception occurred on the last line.
Basically, when you did request.session['uid'], it tried to call that session object's __getitem__ method. Somewhere inside that __getitem__, there is this line:
return self._session[key]
This is what gave the error.

Related

Django easypost buy returns malformed syntax when using test api key but insufficient funds with production

Using the easypost python library I call the buy function passing in the rate like the documentation says but it returns an error.
Can you use your test api key with buy for easypost or not? I didn't see anything in the documentation with it. It might seem to work with production but I am not able to test that yet so I was wondering if I could test it with the test api key?
The code is:
import easypost
def get_shipment(shipment_id):
return easypost.Shipment.retrieve(shipment_id)
......
shipment = get_shipment(shipment_id)
try:
shipment.buy(rate=shipment.lowest_rate())
except Exception as e:
raise ValidationError({'detail': e.message})
The error message I get with test key
Traceback (most recent call last):
File "/app/returns/serializers.py", line 237, in handle_shipment_purchase
shipment.buy(rate=shipment.lowest_rate())
File "/usr/local/lib/python3.6/dist-packages/easypost/__init__.py", line 725, in buy
response, api_key = requestor.request('post', url, params)
File "/usr/local/lib/python3.6/dist-packages/easypost/__init__.py", line 260, in request
response = self.interpret_response(http_body, http_status)
File "/usr/local/lib/python3.6/dist-packages/easypost/__init__.py", line 321, in interpret_response
self.handle_api_error(http_status, http_body, response)
File "/usr/local/lib/python3.6/dist-packages/easypost/__init__.py", line 383, in handle_api_error
raise Error(error.get('message', ''), http_status, http_body)
easypost.Error: The request could not be understood by the server due to malformed syntax.
I got the same issue with Python though my shipment id and API_KEY are correct. with the EasyPost python exception message, it will not show the root cause of the exception. Try to do request with curl or inside exception check e.json_body and raise ValidationError accordingly.
try:
shipment.buy(rate=shipment.lowest_rate())
except Exception as e:
# Put debugger here and Check exception e.json_body
e.json_body
raise ValidationError({'detail': e.http_body})
Yes, you can buy shipments with your TEST API key. From the code you shared, I don't see any obvious problems, but you'll obviously want to double check that your shipment_id is being set correctly and that your API key is as well. Beyond that, write to us as support#easypost.com and we can actually look into our system logs to see what may be coming in "malformed".

How to fix this python code that performs login to website

am novice in python.Extracted below code to login to website from an online post, but getting error.
Please help to fix it and an explanation will help me
import requests
with requests.Session() as c:
EMAIL = 'noob.python#gmail.com'
PASSWORD = 'Dabc#123'
URL = 'https://www.linkedin.com/'
c.get(URL)
token = c.cookies['CsrfParam']
# This is the form data that the page sends when logging in
login_data = {loginCsrfParam:token, session_key:EMAIL, session_password:PASSWORD}
# Authenticate
r = c.post(URL, data=login_data)
# Try accessing a page that requires you to be logged in
r = c.get('https://www.linkedin.com/feed/')
print r.content
Am stuck with below Error:
C:\Python27>python website.py
Traceback (most recent call last):
File "website.py", line 8, in <module>
token = c.cookies['CsrfParam']
File "C:\Python27\lib\site-packages\requests\cookies.py", line 329, in __getitem__
return self._find_no_duplicates(name)
File "C:\Python27\lib\site-packages\requests\cookies.py", line 400, in _find_no_duplicates
raise KeyError('name=%r, domain=%r, path=%r' % (name, domain, path))
KeyError: "name='CsrfParam', domain=None, path=None"
The reason you're getting the error is that you're calling a value from a list which is empty. To call the first item in the list you say list[0]. In this case the list you're calling is empty so the first value doesn't exist hence the error.
I've ran your code and there is no #id value of 'recaptcha-token' which is why the code is returning an empty list. The only place a recaptcha token is needed is for signing up so I would suggest trying to log in without creating the authenticity_token.

praw.errors.Forbidden: HTTP error when using Reddit get_flair_list

I am trying to get the comments for each Reddit post.
This is the way I am using to get flair list:
import praw
import webbrowser
r = praw.Reddit('OAuth testing example by u/_Daimon_ ver 0.1 see '
'https://praw.readthedocs.org/en/latest/'
'pages/oauth.html for source')
r.set_oauth_app_info(client_id='[client id]',
client_secret='[client secret]',
redirect_uri='http://localhost/authorize_callback')
url = r.get_authorize_url('uniqueKey', 'modflair', True)
webbrowser.open(url)
Then I got the code from the returned url, and I put the code in the access information, like this:
access_information = r.get_access_information('[returned code]')
Then when I am trying to call get_fliar_list() just like PRAW tutorial, like this:
item = next(r.get_subreddit('travel').get_flair_list())
It gives me an error, showing:
Traceback (most recent call last):
File "", line 1, in
File "/Library/Python/2.7/site-packages/praw-3.4.0-py2.7.egg/praw/init.py", line 565, in get_content
page_data = self.request_json(url, params=params)
File "", line 2, in request_json
File "/Library/Python/2.7/site-packages/praw-3.4.0-py2.7.egg/praw/decorators.py", line 116, in raise_api_exceptions
return_value = function(*args, **kwargs)
File "/Library/Python/2.7/site-packages/praw-3.4.0-py2.7.egg/praw/init.py", line 620, in request_json
retry_on_error=retry_on_error)
File "/Library/Python/2.7/site-packages/praw-3.4.0-py2.7.egg/praw/init.py", line 452, in _request
_raise_response_exceptions(response)
File "/Library/Python/2.7/site-packages/praw-3.4.0-py2.7.egg/praw/internal.py", line 208, in _raise_response_exceptions
raise Forbidden(_raw=response)
praw.errors.Forbidden: HTTP error
Here's the link of that PRAW tutorial: PRAW tutorial
Do you know how to solve this problem? How can I call get_flair_list() to get all the comments of a Reddit post?
There are a few things potentially going on here.
The first issue (And the most likely) Is that you are logging in wrong.
r = praw.Reddit('OAuth testing example by u/_Daimon_ ver 0.1 see '
'https://praw.readthedocs.org/en/latest/'
'pages/oauth.html for source')
DONT DO THIS, EVER
Even if the syntax in this command was correct (you dont have the commas), this makes your code INCREDIBLY hard to read. The most readable way is to have r = praw.Reddit('OAuth-testing') (the OAuth-testing bit can be whatever you want, as long as it is the same as in your praw.ini file.), then setup your praw.ini file as such:
[DEFAULT]
# A boolean to indicate whether or not to check for package updates.
check_for_updates=True
# Object to kind mappings
comment_kind=t1
message_kind=t4
redditor_kind=t2
submission_kind=t3
subreddit_kind=t5
# The URL prefix for OAuth-related requests.
oauth_url=https://oauth.reddit.com
# The URL prefix for regular requests.
reddit_url=https://www.reddit.com
# The URL prefix for short URLs.
short_url=https://redd.it
[OAuth-testing]
user_agent=USER-AGENT-HERE
username=REDDIT-ACCOUNT-USERNAME
password=REDDIT-ACCOUNT-PASSWORD
client_id=REDDIT-APP-CLIENT-ID
client_secret=REDDIT-APP-CLIENT-SECRET
Just as an additional note, get_flair_list() also requires moderator access, as documented here
Also, you ask at the bottom:
How can I call get_flair_list() to get all the comments of a Reddit post?
This would not be how you get all the comments of a post, if that is what you want to do you can read this tutorial in the PRAW docs.
If you have any further questions don't hesitate to comment on this answer and I or somebody else can answer it!

Gearman Submit Multiple Jobs AttributeError: 'str' object has no attribute 'get'

What I'm trying to achieve here is to submit multiple jobs to Gearman and print the results returned by the workers once they are done with processing the job.
I've read through the examples on:
https://pythonhosted.org/gearman/1to2.html#client-multiple-tasks
https://pythonhosted.org/gearman/client.html
I then tried to implement the check_request_status in the following way:
list_of_jobs = []
for i in xrange(1,4,1):
list_of_jobs.extend(dict(task='run_task', data=str(i)))
completed_requests = gm_client.wait_until_jobs_completed(submitted_requests,
poll_timeout=30.0)
for job_request in completed_requests:
if job_request.complete:
print job_request.result
elif job_request.timed_out:
print "Job %s timed out!" % job_request.unique
elif job_request.state == JOB_UNKNOWN:
print "Job %s connection failed!" % job_request.unique
I'm getting the following error which I can't seem to figure out even after much Google-fu, searching through the Gearman Google Groups and poring through other people's implementation of Gearman:
Traceback (most recent call last):
File "supervisor.py", line 16, in <module>
completed_requests = gm_client.submit_multiple_jobs(list_of_jobs)
File "/usr/local/lib/python2.7/dist-packages/gearman/client.py", line 48, in submit_multiple_jobs
requests_to_submit = [self._create_request_from_dictionary(job_info, background=background, max_retries=max_retries) for job_info in jobs_to_submit]
File "/usr/local/lib/python2.7/dist-packages/gearman/client.py", line 169, in _create_request_from_dictionary
job_unique = job_info.get('unique')
AttributeError: 'str' object has no attribute 'get'
Does anyone know what's going on here?
Turns out the error is a simple one. In the for-loop above, simply use the append function instead of extend for adding a dict to the list_of_jobs array:
list_of_jobs.append(dict(task='run_task', data=str(i)))

Problems with Stripe, Django and Cartridge / Mezzanine

My It is a cartridge/mezzanine app and is running fine with https set up properly. Its working fine until I get to the end of the checkout process, I get the following debug error in the browser:
Exception Type: AuthenticationError
Exception Value:
No API key provided. (HINT: set your API key using "stripe.api_key = "). You can generate API keys from the Stripe web interface. See https://stripe.com/api for details, or email support#stripe.com if you have any questions.
Exception Location: /home/jamesgilbert/lib/python2.7/stripe/api_requestor.py in request_raw, line 183
Traceback:
File "/home/johnsmith/webapps/cartridgeshop/lib/python2.7/Django-1.8.4-py2.7.egg/django/core/handlers/base.py" in get_response
132. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/johnsmith/webapps/cartridgeshop/lib/python2.7/Django-1.8.4-py2.7.egg/django/views/decorators/cache.py" in _wrapped_view_func
57. response = view_func(request, *args, **kwargs)
File "/home/johnsmith/lib/python2.7/cartridge/shop/views.py" in checkout_steps
282. transaction_id = payment_handler(request, form, order)
File "/home/johnsmith/lib/python2.7/cartridge_stripe/init.py" in payment_handler
34. description=order)
File "/home/johnsmith/lib/python2.7/stripe/resource.py" in create
344. response, api_key = requestor.request('post', url, params, headers)
File "/home/johnsmith/lib/python2.7/stripe/api_requestor.py" in request
140. method.lower(), url, params, headers)
File "/home/johnsmith/lib/python2.7/stripe/api_requestor.py" in request_raw
183. 'No API key provided. (HINT: set your API key using '
I then got the following in the apache error logs:
/home/johnsmith/lib/python2.7/cartridge/shop/views.py:226:
UserWarning: The SHOP_CHECKOUT_FORM_CLASS setting is deprecated - please define your own urlpattern for the checkout_steps view, passing in your own form_class argument.
I have the correct stripe api keys in the settings and everything set up as it should be, I have looked in other places and coming to a dead end?
Many Thanks
You need to add the Stripe API key to your settings.py file (which you said you had already done). Something like the following line but with your own API key from the Stripe developer web site.
STRIPE_API_KEY="sk_test_XXXXXXXXXXXXXXXXXXXXXXXX"
You also need to reference the python interface file (which you must have been doing to get this error message).
SHOP_HANDLER_PAYMENT = "cartridge.shop.payment.stripe_api.process"
And, you need to install the strip-python module.
Seems like you did all this so I'm not sure if this will help but maybe it will trigger something to get you over this.
Cartridge-stripe doesn't seem to be maintained. I'd advise using the stripe payment handler built into cartridge, which will be documented in cartridge's next docs release (PR).