Ilya Bibik
Ilya Bibik

Reputation: 4124

During setup of django with sendgrid getting error 401

I have added sendgrid to my django app Followed the simple steps from here https://github.com/elbuo8/sendgrid-django

generated acount and and copied the api at sengrid site

Added code to my view

 sg = sendgrid.SendGridAPIClient(apikey=os.environ.get('SENDGRID_API_KEY'))
            from_email = Email("[email protected]")
            to_email = Email("[email protected]")
            subject = "Sending with SendGrid is Fun"
            content = Content("text/plain", "and easy to do anywhere, even with Python")
            mail = Mail(from_email, subject, to_email, content)
            response = sg.client.mail.send.post(request_body=mail.get())
            messages.add_message(request, messages.SUCCESS, str(payment.id) + response.status_code + response.body + response.headers) 

And getting Error

HTTP Error 401: Unauthorized

What could be the problem?

> Traceback  Traceback: File
> "C:\Users\PAPA\DEV\rent_unit\rent_unit_venv\lib\site-packages\django\core\handlers\base.py"
> in get_response
>   132.                     response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\PAPA\DEV\rent_unit\rent_unit_venv\lib\site-packages\django\contrib\auth\decorators.py"
> in _wrapped_view
>   22.                 return view_func(request, *args, **kwargs) File "C:\Users\PAPA\DEV\rent_unit\src\payment\views.py" in payment_new
>   251.             response = sg.client.mail.send.post(request_body=mail.get()) File
> "C:\Users\PAPA\DEV\rent_unit\rent_unit_venv\lib\site-packages\python_http_client\client.py"
> in http_request
>   204.                 return Response(self._make_request(opener, request)) File
> "C:\Users\PAPA\DEV\rent_unit\rent_unit_venv\lib\site-packages\python_http_client\client.py"
> in _make_request
>   138.         return opener.open(request) File "c:\python27\Lib\urllib2.py" in open
>   435.             response = meth(req, response) File "c:\python27\Lib\urllib2.py" in http_response
>   548.                 'http', request, response, code, msg, hdrs) File "c:\python27\Lib\urllib2.py" in error
>   473.             return self._call_chain(*args) File "c:\python27\Lib\urllib2.py" in _call_chain
>   407.             result = func(*args) File "c:\python27\Lib\urllib2.py" in http_error_default
>   556.         raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
> 
> Exception Type: HTTPError at
> /payment/new/28/http://127.0.0.1:8000/lease/payment_details/28/
> Exception Value: HTTP Error 401: Unauthorized

Upvotes: 2

Views: 2896

Answers (3)

joe-khoa
joe-khoa

Reputation: 610

I have faced same error, I use this cli to solve: e.g(my_api_key) set SENDGRID_API_KEY=SG.FHWXmV68Td2cEYJQrPjDdQ.I1VEkE2CBg7--r7QfS-AzhfSU5 ( !!! do not use ' ' like : 'SG.FHWXmV68Td2cEYJQrPjDdQ.I1VEkE2CBg7--r7QfS-AzhfSU5' ). also. Do not replace SENDGRID_API_KEY line with your API_KEY : sg =SendGridAPIClient(os.environ.get('SENDGRID_API_KEY')) . And you should refer this document : https://github.com/sendgrid/sendgrid-python I think this problem is because the window user,see this and you will understand . Acc to this doc :  instruction_from_git

Upvotes: 0

Ali Raja
Ali Raja

Reputation: 53

Just update your code to use the one you want if you prefer not to use environment variable or settings

SENDGRID_API_KEY = '*sendgrid***api*'

sg = sendgrid.SendGridAPIClient(apikey=SENDGRID_API_KEY )

Upvotes: 0

Soviut
Soviut

Reputation: 91585

The problem is exactly what it says; You're not authorized. Most likely you're API key isn't set.

The instructions you added to your question show the SENDGRID_API_KEY being added to the Django settings.py, while you're code shows you fetching from an environment variable.

Environment Variable Approach

If you're using the environment variable approach, make sure you've set an environment variable called SENDGRID_API_KEY. You can check it it's set by opening a python console and typing:

import os
os.environ.get('SENDGRID_API_KEY')

If a key isn't printed out, that means it's missing. Each OS has a different way of setting environment variables permanently, so I'm not going to list them all out here.

Settings.py Approach

If you're going with the Django settings.py approach, simply replace:

sg = sendgrid.SendGridAPIClient(apikey=os.environ.get('SENDGRID_API_KEY'))

with

from django.conf import settings

sg = sendgrid.SendGridAPIClient(apikey=settings.SENDGRID_API_KEY)

Environment Variable in Settings.py Approach

Finally, since settings.py is an executable python file, you can also perform an environment variable import there. This has the benefit of being adjustable from a system level or a Heroku console, but still uses settings.py.

# inside settings.py
import os    
SENDGRID_API_KEY = os.environ.get('SENDGRID_API_KEY')

Upvotes: 2

Related Questions