Django KeyError at 'HTTP_HOST' - django

In my Django project sometimes I get two kinds of errors by mail and I don't know where they are coming from. So far I can see, the user is not logged in.
First kind of error:
Internal Server Error: /
KeyError at /
'HTTP_HOST'
File "./core/views/iam.py", line 45, in prepare_django_request
'http_host': request.META['HTTP_HOST'],
Exception Type: KeyError at /
Exception Value: 'HTTP_HOST'
Request information:
USER: AnonymousUser
Second type of error:
Internal Server Error: /
OneLogin_Saml2_Error at /
SAML Response not found, Only supported HTTP_POST Binding
File "var/www/schoolbox/venv/lib64/python3.6/site-packages/onelogin/saml2/auth.py", line 139, in process_response
OneLogin_Saml2_Error.SAML_RESPONSE_NOT_FOUND
Exception Type: OneLogin_Saml2_Error at /
Exception Value: SAML Response not found, Only supported HTTP_POST Binding
Request information:
USER: AnonymousUser
But users are able to login but, or maybe only some, I don't know where this error is coming from. Maybe I need to post more code in order to help me. Any help will be appreciated.

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".

Django password reset with MongoDB - DatabaseError with no exception message

I've connected my Django app with MongoDB, register/login/logout are all working fine. But when I use the Django default password reset email it throws a database error.
What I've tired:
sqlite3 - register/login/logout (Working)
MongoDB - register/login/logout (Working)
sqlite3 - password reset email (Working)
MongoDB - password reset email (NOT Working)
I was able to land on the Django password reset page, but when I hit confirm it return the error on the browser
DatabaseError at /pw_reset/
No exception message supplied
Request Method: POST
Request URL: http://localhost:8000/pw_reset/
Django Version: 3.2.6
Exception Type: DatabaseError
Exception Location:
C:...venv\lib\site-packages\djongo\cursor.py, line 59, in execute
The above exception ( Keyword: None Sub SQL: None FAILED SQL: ('SELECT "accounts_user"."id", "accounts_user"."password", "accounts_user"."last_login", "accounts_user"."is_superuser", "accounts_user"."username", "accounts_user"."first_name", "accounts_user"."last_name", "accounts_user"."email", "accounts_user"."is_staff", "accounts_user"."is_active", "accounts_user"."date_joined" FROM "accounts_user" WHERE ("accounts_user"."email" iLIKE %(0)s AND "accounts_user"."is_active")',) Params: (('test#test.com',),) Version: 1.3.6) was the direct cause of the following exception:
Console log:
Traceback (most recent call last):
File "C:...\lib\site-packages\django\template\base.py", line 850, in _resolve_lookup
(bit, current)) # missing attribute
django.template.base.VariableDoesNotExist: Failed lookup for key [name] in <URLResolver <URLPattern list> (admin:admin) 'admin/'>
URL Path:
path('pw_reset/', auth_views.PasswordResetView.as_view(), name="reset_password"),
The Views I defined myself (register/login/logout) are all working fine. But the built-in one PasswordRestView is not. I've tried dropping the DB, reinstall djongo, I run out of ideas... Please help!
Fixed by downgrading versions on:
Django==3.0.5
djongo==1.3.4
sqlparse==0.2.4

I'm getting a DoesNotExist error with django rest auth password reset

I've installed and configured django-rest-auth, everything seems to be working properly except the /rest-auth/password/reset/ endpoint.
When I do a POST to it, passing the email via JSON, a 500 - DoesNotExist error is returned:
DoesNotExist at /rest-auth/password/reset/
Site matching query does not exist.
Request Method: POST
Request URL: http://.../rest-auth/password/reset/
Django Version: 1.9.5
Exception Type: DoesNotExist
Exception Value: Site matching query does not exist.
Exception Location: /home/.../.local/lib/python2.7/site-packages/django/db/models/query.py in get, line 387
Python Executable: /usr/bin/python
Python Version: 2.7.10
What could be causing this?
django-allauth (used internally by DRA) looks for the domain name by searching for Site object.
Please follow these steps to set up sites framework:
https://docs.djangoproject.com/en/1.9/ref/contrib/sites/#enabling-the-sites-framework

linkedin api - python - get_connections()

I am working on a simple python scraping script, I am trying to get connections from LinkedIn using their API without a redirect_uri. I worked once with some APIs, that don't require the redirect url or just https://localhost. I got the consumer_key, consumer_secret, user_secret, consumer_secret. Here's the code i am using from https://github.com/ozgur/python-linkedin:
RETURN_URL = ''
url = 'https://api.linkedin.com/v1/people/~'
# Instantiate the developer authentication class
authentication = linkedin.LinkedInDeveloperAuthentication(CONSUMER_KEY, CONSUMER_SECRET,
USER_TOKEN, USER_SECRET,
RETURN_URL, linkedin.PERMISSIONS.enums.values())
# Pass it in to the app...
application = linkedin.LinkedInApplication(authentication)
print application.get_profile() # works
print application.get_connections()
And here's the error I get:
Traceback (most recent call last):
File "getContacts.py", line 20, in <module>
print application.get_connections()
File "/home/imane/Projects/prjL/env/local/lib/python2.7/site-packages/linkedin/linkedin.py", line 219, in get_connections
raise_for_error(response)
File "/home/imane/Projects/prjL/env/local/lib/python2.7/site-packages/linkedin/utils.py", line 63, in raise_for_error
raise LinkedInError(message)
linkedin.exceptions.LinkedInError: 403 Client Error: Forbidden for url: https://api.linkedin.com/v1/people/~/connections: Unknown Error
This is my first question here, so excuse me if I didn't make it clear enough, and thank you for helping me out.
Here's what i tried with python_oauth2:
import oauth2 as oauth
import requests
url = 'https://api.linkedin.com/v1/people/~'
params = {}
token = oauth.Token(key=USER_TOKEN, secret=USER_SECRET)
consumer = oauth.Consumer(key=CONSUMER_KEY, secret=CONSUMER_SECRET)
# Set our token/key parameters
params['oauth_token'] = token.key
params['oauth_consumer_key'] = consumer.key
oauth_request = oauth.Request(method="GET", url=url, parameters=params)
oauth_request.sign_request(oauth.SignatureMethod_HMAC_SHA1(), consumer, token)
signed_url = oauth_request.to_url()
response = requests.get(signed_url)
Connections API calls are a restricted endpoint as of March, 2015. It's possible you're using sample code/documentation that was written at a time when anyone could access those endpoints. You are receiving a 403 response because your application legitimately does not have the permission required to make that request.

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).