Obtaining access token error 401 in Twython - python

I am trying to veify Twitter account of user via Twython
def twitter_view(request):
twitter = Twython(APP_KEY, APP_SECRET)
auth = twitter.get_authentication_tokens(callback_url='http://127.0.0.1:8000/confirm/', force_login=True)
request.session['oauth_token'] = auth['oauth_token']
request.session['oauth_token_secret'] = auth['oauth_token_secret']
return HttpResponseRedirect(auth['auth_url'])
def redirect_view(request):
oauth_verifier = request.GET['oauth_verifier']
twitter = Twython(APP_KEY, APP_SECRET)
final_step = twitter.get_authorized_tokens(oauth_verifier)
request.user.twitter_oauth_token = final_step['oauth_token']
request.user.twitter_oauth_token_secret = final_step['oauth_token_secret']
request.user.save()
return redirect('twitterapp:homepage')
I am getting
Twitter API returned a 401 (Unauthorized), Invalid / expired Token
Traceback (most recent call last):
File
"/Users/bharatagarwal/my-venv/lib/python2.7/site-packages/django/core/handlers/base.py",
line 149, in get_response
response = self.process_exception_by_middleware(e, request)
File
"/Users/bharatagarwal/my-venv/lib/python2.7/site-packages/django/core/handlers/base.py",
line 147, in get_response response = wrapped_callback(request,
*callback_args, **callback_kwargs)
File
"/Users/bharatagarwal/projects/twitterproject/mysite/twitterapp/views.py",
line 100, in redirect_view
final_step = twitter.get_authorized_tokens(str(oauth_verifier))
File
"/Users/bharatagarwal/my-venv/lib/python2.7/site-packages/twython/api.py",
line 379, in get_authorized_tokens
ken'), error_code=response.status_code)
TwythonError: Twitter API returned a 401 (Unauthorized), Invalid /
expired To ken

On the second Twython instantiation, you have to include the OAUTH_TOKEN and the OAUTH_SECRET_TOKEN obtained in the first step.
twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET)
It is returning Invalid Token because the instantiation you're using didn't include the tokens you received.

Related

Google Calendar API HttpError 404 when using service account

I am trying to get a list of events on my calendar from a service account so that I do not have to authenticate myself to display my calendar. When I run the following code I get a 404 error:
SCOPES = ['https://www.googleapis.com/auth/calendar.readonly']
SERVICE_ACCOUNT_FILE = os.path.join(os.path.dirname(
os.path.realpath(__file__)), 'static/calendarSync/service-account.json')
calId = "blakewright1021#gmail.com"
credentials = service_account.Credentials.from_service_account_file(
SERVICE_ACCOUNT_FILE, scopes=SCOPES)
google_account = googleapiclient.discovery.build(
'calendar', 'v3', credentials=credentials)
cal_list = google_account.calendarList() # pylint: disable=no-member
#page_token = None
#calendar_list = cal_list.list(pageToken=page_token).execute()
# for calendar_list_entry in calendar_list['items']:
# print("Here: ")
# print(calendar_list_entry['summary'])
calendar = cal_list.get(
calendarId=calId)
output = calendar.execute()['summary']
When I use the code that is commented out to try and print a list of calendars, it does not print anything so the list must be empty.
Here is the traceback:
Internal Server Error: /
Traceback (most recent call last):
File "C:\Python38\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
response = get_response(request)
File "C:\Python38\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Python38\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\blake\djangoCalendar\locallibrary\calendarSync\views.py", line 40, in index
output = calendar.execute()['summary']
File "C:\Python38\lib\site-packages\googleapiclient\_helpers.py", line 134, in positional_wrapper
return wrapped(*args, **kwargs)
File "C:\Python38\lib\site-packages\googleapiclient\http.py", line 907, in execute
raise HttpError(resp, content, uri=self.uri)
googleapiclient.errors.HttpError: <HttpError 404 when requesting https://www.googleapis.com/calendar/v3/users/me/calendarList/blakewright1021%40gmail.com?alt=json returned "Not Found">
I have shared my calendar with the service account. I am also able to access the calendar when I authenticate without a service account. What am I doing wrong?
CalendarList is the list on the bottom left of the google calendar web application.
Unless you have inserted the calendar into the service accounts calendarlist using clanedarlist.insert, its not going to show up in that list.
Once you have shared a calendar with the service account just do a calendar.get on the calendar id you shared and you will be able to access it. You can then do a calendarlist.insert if you really want it in the calendar list.

how can i check if value is exist in redis-database using python-redis

Here is my python code:
def check(request):
import redis
R = redis.StrictRedis(host='127.0.0.1', port=6379, db=0)
R.set("name","srk")
r = R.HSET("name","srk")
print(r)
It encounters an error with this error message:
Internal Server Error: /get_user/
Traceback (most recent call last):
File "/home/soubhagya/.local/share/virtualenvs/pipenv-r-zifbiy/lib/python3.5/site-packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File "/home/soubhagya/.local/share/virtualenvs/pipenv-r-zifbiy/lib/python3.5/site-packages/django/core/handlers/base.py", line 126, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/home/soubhagya/.local/share/virtualenvs/pipenv-r-zifbiy/lib/python3.5/site-packages/django/core/handlers/base.py", line 124, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/soubhagya/Desktop/Dev/rango/backend/access/views.py", line 103, in get_user
r = R.HSET("name","srk")
AttributeError: 'StrictRedis' object has no attribute 'HSET'
In py-redis, how can I check if a value exists or not in redis database.
A raw query will be helpful.
Please have a look into my code.
StrictRedis has no HSET function, but it does have the hset function for setting fields in Redis Hashes. That is the cause for the error you're getting.
To check whether a key exists in Redis with redis-py, use r = R.exists("name").

Can't get users from G Suite in Python 3

I'm trying to solve a task using Admin SDK API
- Get the user-list from domain
- Сhange users password
For my case i created a service user in G Suite and wrote the script from the example below:
from oauth2client.service_account import ServiceAccountCredentials
from httplib2 import Http
from apiclient.discovery import build
def main():
scopes = ['https://www.googleapis.com/auth/admin.directory.user']
credentials = ServiceAccountCredentials.from_json_keyfile_name('paswd.json', scopes=scopes)
http_auth = credentials.authorize(Http())
service = build('admin', 'directory_v1', http=http_auth)
print('Getting the first 10 users in the domain')
results = service.users().list(customer='my_customer', maxResults=10, orderBy='email', domain='nnn.nn').execute()
print(results)
if __name__ == '__main__':
main()
When I execute script, I got the next exception:
Getting the first 10 users in the domain
Traceback (most recent call last):
File "./run-2.py", line 25, in <module>
main()
File "./run-2.py", line 21, in main
results = service.users().list(customer='my_customer', maxResults=10, orderBy='email', domain='nnn.nn').execute()
File "/usr/local/lib/python3.4/dist-packages/oauth2client/_helpers.py", line 133, in positional_wrapper
return wrapped(*args, **kwargs)
File "/usr/local/lib/python3.4/dist-packages/googleapiclient/http.py", line 840, in execute
raise HttpError(resp, content, uri=self.uri)
googleapiclient.errors.HttpError: <HttpError 403 when requesting https://www.googleapis.com/admin/directory/v1/users?customer=my_customer&domain=g.nsu.ru&alt=json&maxResults=10&orderBy=email returned "Not Authorized to access this resource/api">
What could be the problem?
As far as I have been able to figure out, what you are missing is:
credentials = ServiceAccountCredentials.from_json_keyfile_name('paswd.json', scopes=scopes)
delegated_credentials = credentials.create_delegated(DELEGATED_ACCOUNT)
http_auth = delegated_credentials.authorize(Http())
Where DELEGATED_ACCOUNT is an admin for your domain.

dropbox.rest.ErrorResponse: [400] u'invalid_client' dropbox api fom python

Following the tutorial from the python api I get this error
Traceback (most recent call last):
File "/home/user/PycharmProjects/api/apid.py", line 17, in <module>
access_token, user_id = flow.finish(code)
File "/usr/local/lib/python2.7/dist-packages/dropbox/client.py", line 1398, in finish
return self._finish(code, None)
File "/usr/local/lib/python2.7/dist-packages/dropbox/client.py", line 1265, in _finish
response = self.rest_client.POST(url, params=params)
File "/usr/local/lib/python2.7/dist-packages/dropbox/rest.py", line 316, in POST
return cls.IMPL.POST(*n, **kw)
File "/usr/local/lib/python2.7/dist-packages/dropbox/rest.py", line 254, in POST
post_params=params, headers=headers, raw_response=raw_response)
File "/usr/local/lib/python2.7/dist-packages/dropbox/rest.py", line 227, in request
raise ErrorResponse(r, r.read())
dropbox.rest.ErrorResponse: [400] u'invalid_client'
And the code its the same of the tutorial
#!/usr/bin/env python
import dropbox
app_key = 'key'
app_secret = 'secret'
flow = dropbox.client.DropboxOAuth2FlowNoRedirect(app_key, app_secret)
authorize_url = flow.start()
print '1. Go to: ' + authorize_url
print '2. Click "Allow" (you might have to log in first)'
print '3. Copy the authorization code.'
code = raw_input("Enter the authorization code here: ").strip()
access_token, user_id = flow.finish(code)
client = dropbox.client.DropboxClient(access_token)
print 'linked account: ', client.account_info()
I haven't changed anything from the original code

twitter login: 401 Client Error: Authorization Required

I'm using python-social-auth to implement twitter login locally but I get the 401 client error. My django version is 1.6.
Traceback:
File "/Library/Python/2.7/site-packages/django/core/handlers/base.py" in get_response
112. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Library/Python/2.7/site-packages/social/apps/django_app/utils.py" in wrapper
45. return func(request, backend, *args, **kwargs)
File "/Library/Python/2.7/site-packages/social/apps/django_app/views.py" in auth
12. return do_auth(request.social_strategy, redirect_name=REDIRECT_FIELD_NAME)
File "/Library/Python/2.7/site-packages/social/actions.py" in do_auth
25. return strategy.start()
File "/Library/Python/2.7/site-packages/social/strategies/base.py" in start
66. return self.redirect(self.backend.auth_url())
File "/Library/Python/2.7/site-packages/social/backends/oauth.py" in auth_url
99. token = self.set_unauthorized_token()
File "/Library/Python/2.7/site-packages/social/backends/oauth.py" in set_unauthorized_token
158. token = self.unauthorized_token()
File "/Library/Python/2.7/site-packages/social/backends/oauth.py" in unauthorized_token
177. method=self.REQUEST_TOKEN_METHOD)
File "/Library/Python/2.7/site-packages/social/backends/base.py" in request
205. response.raise_for_status()
File "/Library/Python/2.7/site-packages/requests/models.py" in raise_for_status
808. raise HTTPError(http_error_msg, response=self)
Exception Type: HTTPError at /login/twitter/
Exception Value: 401 Client Error: Authorization Required
In documentation it suggests to install ntp.I have no clue how to install ntp.
It turns out I left the callback url field blank in the twitter app console. Although, it's not required, but putting http://127.0.0.1:8000/complete/twitter/ (Note the slash at the end) did the job.
Note also that if you leave the final '/' off the end of the call back URL, you will get this error. It should read
http://127.0.0.1:8000/complete/twitter/

Categories