django-paypal deprecation error : Use of the initial['return_url'] is Deprecated - django-paypal

I am trying to integrate django-paypal payment in my app but I keep getting this error even though I am using the latest version.
Please use initial['return'] instead""", DeprecationWarning)
DeprecationWarning: The use of the initial['return_url'] is Deprecated.
Please use initial['return'] instead
This happens after the call to PayPalPaymentsForm
form = PayPalPaymentsForm(initial=paypal_dict, button_type="subscribe")
Is there any fix for this ?

Just do what it says, change that return_url to just return.
You can reveal that from the related code:
def _fix_deprecated_return_url(self, initial_args):
if 'return_url' in initial_args:
warn("""The use of the initial['return_url'] is Deprecated.
Please use initial['return'] instead""", DeprecationWarning)
initial_args['return'] = initial_args['return_url']
del initial_args['return_url']
return initial_args

Related

ascending=True not working in django-mptt

Hi good day I'm currently following Django-MPTT documentation and I have a problem using ascending=True. Here's my code:
views.py
def show_genres(request):
Try01 = Genre.objects.filter(name="Rock")
context = {'genres': Genre.objects.all(),
'sample_ancestor': Try01.get_ancestors(ascending=True, include_self=True)}
return render(request, "sampletemp/startup.html", context)
when I'm using ascending=True an error occurs saying:
Exception Value: get_queryset_ancestors() got an unexpected keyword argument 'ascending'
How can I fix it. Thank you in advance!
You are using the wrong method
models.get_ancestors has an ascending field see here
managers.TreeManager.get_queryset_ancestors howerver has not, as shown here

Supress warnings of 4xx response code of views in Django

I am trying to suppress some specific warning message of a view that's returning a 404 when the object is not found. I have tried:
try:
city = Cities.objects.get(id='abcd')
except ObjectDoesNotExist:
with warnings.catch_warnings():
return bad_request_response(_('City not found.'), resp_status=HTTP_404_NOT_FOUND)
But django seems to go around that and shows in the logs:
WARNING Not Found: /cities/abcd/
I am working with Django 1.11. I see it the docs that this is the expected behavior https://docs.djangoproject.com/en/1.11/topics/logging/#django-request but I am trying to go around that. Any hint is welcome

How to fetch and assert and REST API in Python Unittests?

while trying to fetch and assert a REST API, throwing a "TypeError". The following is the code which I am running
def test_get_action(self):
action_id = self._get_action_id()
"""Get actions, Successful with response status 200"""
resp = self.test_client.get_action(action_id)
self.assertEqual(resp.response['status'], '200')
self.assertEqual(resp.values()[0][0]['action_id'], action_id)
And I'm seeing the error as "TypeError: 'dict_values' object does not support indexing"
Further investigations:
* Running this test in Python 2.7 and seeing the above error
* I change the code differently as follow, but not able to derive this.
self.assertListEqual(resp.values()[0][0]['action_id'], action_id)
self. assertSequenceEqual(resp.values()[0][0]['action_id'], action_id)
I'm new to Python and unittests, please help.
Thanks in advance.
The error message suggests that resp.values() is returning a dict_values object rather than a list.
Try wrapping the call to resp.values() in a call to list():
self.assertEqual(list(resp.values())[0][0]['action_id'], action_id)

Google API Scope Changed

edit: I solved it easily by adding "https://www.googleapis.com/auth/plus.me" to my scopes, but I wanted to start a discussion on this topic and see if anyone else experienced the same issue.
I have a service running on GCP, an app engine that uses Google API. This morning, I've received this "warning" message which threw an 500 error.
It has been working fine for the past month and only threw this error today (5 hours prior to this post).
Does anyone know why Google returned an additional scope at the oauth2callback? Any additional insight is very much appreciated. Please let me know if you've seen this before or not. I couldn't find it anywhere.
Exception Type: Warning at /oauth2callback
Exception Value:
Scope has changed from
"https://www.googleapis.com/auth/userinfo.email" to
"https://www.googleapis.com/auth/userinfo.email
https://www.googleapis.com/auth/plus.me".
This line threw the error:
flow.fetch_token(
authorization_response=authorization_response,
code=request.session["code"])
The return url is https://my_website.com/oauth2callback?state=SECRET_STATE&scope=https://www.googleapis.com/auth/userinfo.email+https://www.googleapis.com/auth/plus.me#
instead of the usual https://my_website.com/oauth2callback?state=SECRET_STATE&scope=https://www.googleapis.com/auth/userinfo.email#
edit: sample code
import the required things
SCOPES = ['https://www.googleapis.com/auth/userinfo.email',
'https://www.googleapis.com/auth/calendar',
# 'https://www.googleapis.com/auth/plus.me' <-- without this, it throws the error stated above. adding it, fixes the problem. Google returns an additional scope (.../plus.me) which causes an error.
]
def auth(request):
flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file(
CLIENT_SECRETS_FILE, scopes=SCOPES)
flow.redirect_uri = website_url + '/oauth2callback'
authorization_url, state = flow.authorization_url(
access_type='offline', include_granted_scopes='true',
prompt='consent')
request.session["state"] = state
return redirect(authorization_url)
def oauth2callback(request):
...
# request.session["code"] = code in url
authorization_response = website_url + '/oauth2callback' + parsed.query
flow.fetch_token(
authorization_response=authorization_response,
code=request.session["code"])
...
We discovered the same issue today. Our solution has been working without any hiccups for the last couple of months.
We solved the issue by updating our original scopes 'profile email' to https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile and by doing some minor changes to the code.
When initiating the google_auth_oauthlib.flow client, we previously passed in the scopes in a list with only one item which contained a string in which the scopes were separated by spaces.
google_scopes = 'email profile'
self.flow = Flow.from_client_secrets_file(secret_file, scopes=[google_scopes], state=state)
Now, with the updated scopes, we send in a list where each element is a separate scope.
google_scopes = 'https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile'
self.flow = Flow.from_client_secrets_file(secret_file, scopes=google_scopes.split(' '), state=state)
Hope it helps, good luck!
I am using requests_oauthlib extension and I had the same error. I fix the issue by adding OAUTHLIB_RELAX_TOKEN_SCOPE: '1' to environment variables. So my app.yaml file is similar to this:
#...
env_variables:
OAUTHLIB_RELAX_TOKEN_SCOPE: '1'
For my case I added the following line in that function that the authentication is happening in
os.environ['OAUTHLIB_RELAX_TOKEN_SCOPE'] = '1'
flow = InstalledAppFlow.from_client_config(client_config, scopes=SCOPES)
At a guess from your error it looks like you're using a depreciated scope. See:
https://developers.google.com/+/web/api/rest/oauth#deprecated-scopes
I'm also guessing that you may be using the Google+ Platform Web library and maybe the People:Get method. Perhaps try using one of the following scopes instead:
https://www.googleapis.com/auth/plus.login
or
https://www.googleapis.com/auth/plus.me
Given the timing, you might be effected by this change by Google:
"Starting July 18, 2017, Google OAuth clients that request certain sensitive OAuth scopes will be subject to review by Google."
https://developers.google.com/apps-script/guides/client-verification

how show personalized error with get_object_or_404

I would like to know how to show personalized errors with the get_object_or_404 method. I don't want the normal Http404 pages, but I want to display a custom message with the message: the result is none.
Thanks :)
The get_object_or_404() is essentially a simple 5-line function. Unless you have some specific reason for using it, just do:
try:
instance = YourModel.objects.get(pk=something)
except YourModel.DoesNotExist:
return render_to_response('a_template_with_your_error_message.html')
If for whatever reason you have to use get_object_or_404(), you can try putting it in a try: ... except Http404: ... block, but I honestly can't think of a plausible reason for that.
As stated by michael, when using get_object_or_404 you cannot customize the message given on http 404. The message provided in DEBUG does offer information about the exception however: "No MyModel matches the given query."
Check out the doc on this. There are three arguments: Model, *args, and **kwargs. The last two are used to build an argument for either get() or filter() on the Model.
The reason I wrote, however, is to address the question of why we would want to use a helper function such as get_object_or_404() instead of, for example, catching it with an exception like Model.DoesNotExist.
The later solution couples the view layer to the model layer. In an effort to relax this coupling we can take advantage of the controlled coupling offered in the django.shortcuts module[1].
And why exactly aren't you using your server's capeability to do just that?
get_object_or_404() is redirecting to the default 404 page right?
If you are on debug mode you won't see it but when deployed django will just refer to the server's 404 html page.
That can't be done with that shortcut. It will only raise a Http404 exception. Your best bet is a try catch if you want full control. Eg.
try:
obj = Model.objects.get(pk = foo)
except:
return HttpResponseRedirect('/no/foo/for/you')
#or
return render_to_response ...