How to use refresh_access_token in the Yahoo Social Python SDK - python

I'm trying to use the Yahoo Social Python SDK to get a users contacts through oAuth. This is for a webapp running on App Engine. SO, I have everything set up to run through the oAuth dance, exchanging consumer keys and verifiers and all that jazz. I store the token and can reuse it to retrieve a users contacts until the token the expires an hour later. So, is there anyone out there who has used the Python SDK and can tell me what is wrong with this simple code:
import yahoo.application
CONSUMER_KEY = '####'
CONSUMER_SECRET = '##'
APPLICATION_ID = '##'
CALLBACK_URL = '##'
oauthapp = yahoo.application.OAuthApplication(CONSUMER_KEY, CONSUMER_SECRET, APPLICATION_ID, CALLBACK_URL)
oauthapp.token = yahoo.oauth.AccessToken.from_string(access_token) #access_token is legit string pulled from datastore
oauthapp.token = oauthapp.refresh_access_token(oauthapp.token)
contacts = oauthapp.getContacts()
Running this throws the following error:
'oauth_token'<br>
Traceback (most recent call last):<br>
File "/base/python_runtime/python_lib/versions/1/google/appengine/ext/webapp/__init__.py", line 513, in __call__<br>
handler.post(*groups)<br>
File "/base/data/home/apps/testproj/2.345270664321958961/scripteditor.py", line 1249, in post<br>
oauthapp.token = oauthapp.refresh_access_token(oauthapp.token)<br>
File "/base/data/home/apps/testproj/2.345270664321958961/yahoo/application.py", line 90, in refresh_access_token<br>
self.token = self.client.fetch_access_token(request)<br>
File "/base/data/home/apps/testproj/2.345270664321958961/yahoo/oauth.py", line 165, in fetch_access_token<br>
return AccessToken.from_string(self.connection.getresponse().read().strip())<br>
File "/base/data/home/apps/testproj/2.345270664321958961/yahoo/oauth.py", line 130, in from_string<br>
key = params['oauth_token'][0]<br>
KeyError: 'oauth_token'<br>
Basically, if I comment out the line with refresh_access_token, and the token has not expired, this code works and I get the users contacts. But with refresh_acces_token, it fails at that line. Can anyone give a hand?

Looks like something wrong with passing params. Try to debug oauth_token variable.

Solved. For reasons I can't understand, the above code now just works. It might have been a problem on yahoo's end, but I really can't be sure. It's been running fine for two weeks.

Related

How to delete all favorites using python? Can't delete, getting errors. Need solution

I've tried to make a python script that can delete / undo favorite all my twitter favorites for me. I have seen MATHEW INKSON's post to do the job. I don't need to delete my tweets, just want to clear the favorites. Besides that script is almost two years old and incompatible with latest python. So I've edited a little to run it with python 3.6.0 and my script look like this:
import tweepy
from datetime import datetime, timedelta
test_mode = False
verbose = False
delete_favs = True
days_to_keep = 7
consumer_key = 'my consumer key'
consumer_secret = 'my consumer secret'
access_token = 'my access token'
access_token_secret = 'my access token secret'
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)
cutoff_date = datetime.utcnow() - timedelta(days=days_to_keep)
if delete_favs:
print ("Retrieving favorited tweets")
favorites = tweepy.Cursor(api.favorites).items()
unfav_count = 0
kept_count = 0
for tweet in favorites:
if tweet.created_at < cutoff_date:
if verbose:
print ("Unfavoring %d: [%s] %s % (tweet.created_at,tweet.text)")
if not test_mode:
api.destroy_favorite(tweet.id)
unfav_count += 1
else:
kept_count += 1
print ("Unfavored %d tweets, ignored %d" % (unfav_count, kept_count))
But, everytime by running the script on my windows command I am getting this following error:
Traceback (most recent call last):
File "C:\Users\xyz\Desktop\New folder\Unfavorite.py", line 25, in <module>
for tweet in favorites:
File "C:\Users\xyz\AppData\Local\Programs\Python\Python36\lib\site-packages\tweepy-3.6.0-py3.6.egg\tweepy\cursor.py", line 49, in __next__
File "C:\Users\xyz\AppData\Local\Programs\Python\Python36\lib\site-packages\tweepy-3.6.0-py3.6.egg\tweepy\cursor.py", line 197, in next
File "C:\Users\xyz\AppData\Local\Programs\Python\Python36\lib\site-packages\tweepy-3.6.0-py3.6.egg\tweepy\cursor.py", line 108, in next
File "C:\Users\xyz\AppData\Local\Programs\Python\Python36\lib\site-packages\tweepy-3.6.0-py3.6.egg\tweepy\binder.py", line 250, in _call
File "C:\Users\xyz\AppData\Local\Programs\Python\Python36\lib\site-packages\tweepy-3.6.0-py3.6.egg\tweepy\binder.py", line 234, in execute
tweepy.error.TweepError: Twitter error response: status code = 429
I am using Python 3.6, my app's permissions are all correct. Everything is fine with my twitter app. I guess something is wrong with my script.
Please someone help fix my code. I've seen some other script too. Those didn't work out. Suggestions will be appreciated.
Thanks is advance.
As per Twitter response codes, Code 429 is Returned in when a request cannot be served due to the application’s rate limit having been exhausted for the resource. Which means your app has made too many requests and you have to look into API Rate limits.

use google translate premium API by json

I am new to google translate api premium edition and json. I have the service account and the key credentials save in a json file. I want to use the 'nmt' model. The following are my python code. I can get the access token but still cannot make it run correctly. Please let me know which part I did wrong. I appreciate your help.
from oauth2client.client import GoogleCredentials
from googleapiclient.discovery import build
base_url = ['https://www.googleapis.com/language/translate/v2']
# load json credential keys
my_credentials = GoogleCredentials.from_stream('./data/TranslateAPI-cbe083d405fe.json')
# get access token
access_token = my_credentials.get_access_token(base_url)
# build service
service = build('translate', 'v2', credentials=access_token, model='nmt')
text = u'So let us begin anew--remembering on both sides that civility is not a sign of weakness, and sincerity is always subject to proof. Let us nevernegotiate out of fear. But let us never fear to negotiate.'
test = service.translations().list(q=text, target='es')
results = test.execute()
I got the following errors:
Traceback (most recent call last):
File "C:\Users\ying\workspace\GoogleTranslateAPI_v3\test1.py", line 32, in <module>
test = service.translations().list(q=text, target='es')
File "C:\Anaconda\lib\site-packages\googleapiclient\discovery.py", line 778, in method
headers, params, query, body = model.request(headers,
AttributeError: 'str' object has no attribute 'request'
You should use Google Cloud Translate Client
The client you are using doesn't support "NMT". The error you got in this case is about you entered wrong type of value to "model" parameter. The correct value should be a googleapiclient.Model

Python: how to login on Youtube

So, I'm a bit confused on how I get past authentication on Youtube using Python and successfully login. I always get error 403 when I try to PragmaticLogin():
yt_service = gdata.youtube.service.YouTubeService()
service.developer_key = 'MY Key'
service.client_id='My ID'
service.email = 'myemail#yahoo.gr'
service.password = 'mypassword'
service.source = 'my_program'
service.ProgrammaticLogin()
What do I have to do?
Update:
I think that it has to do with authentication. Do I need both developer_key and client_id? Where do I get each? I want to have rights to add comments to my videos etc.
Full error:
Traceback (most recent call last):
File "/home/bodhi32/Documents/bot.py", line 9, in <module>
client.ClientLogin(USERNAME, PASSWORD)
File "/usr/lib/pymodules/python2.7/gdata/service.py", line 833, in ClientLogin
self.ProgrammaticLogin(captcha_token, captcha_response)
File "/usr/lib/pymodules/python2.7/gdata/service.py", line 796, in ProgrammaticLogin
raise Error, 'Server responded with a 403 code'
gdata.service.Error: Server responded with a 403 code
ClientLogin is deprecated and has all sorts of errors. Don't use it.
Use OAuth2.
This sample should get you started:
https://github.com/youtube/api-samples/blob/master/python/my_uploads.py
Use your code but make sure you fill the developer_key and client_id fields ( check below how to get them).
yt_service = gdata.youtube.service.YouTubeService()
service.developer_key = 'MY Key'
service.client_id='My ID'
service.email = 'myemail#yahoo.gr'
service.password = 'mypassword'
service.source = 'my_program'
service.ProgrammaticLogin()
To obtain a youtube api go to
https://cloud.google.com/console/project and create a new project, then enable youtube.
Check this video for more info Obtaining a simple API key for use with the YouTube API

Python Youtube API: Attempt to access Watch Later results in invalid URI

BELIEVED SOLVED: Python API only supports v1, while watch later was added in v2. SOURCE
SOLUTION: Use "Experimental" API v3
I am attempting to use the Youtube API to access my Watch Later playlist. Below is the code I am using.
import gdata.youtube
import gdata.youtube.service
yt_service = gdata.youtube.service.YouTubeService()
yt_service.ssl = True
yt_service.developer_key = 'REDACTED'
yt_service.email = 'REDACTED'
yt_service.password = 'REDACTED'
yt_service.ProgrammaticLogin()
playlist_uri = 'https://gdata.youtube.com/feeds/api/users/default/watch_later?v=2'
playlist_video_feed = yt_service.GetYouTubePlaylistVideoFeed(uri=playlist_uri)
for playlist_video_entry in playlist_video_feed.entry:
print playlist_video_entry.title.text
I am receiving the following error.
Traceback (most recent call last):
File "Youtube.py", line 21, in <module>
playlist_video_feed = yt_service.GetYouTubePlaylistVideoFeed(uri=playlist_uri)
File "/Library/Python/2.6/site-packages/gdata/youtube/service.py", line 393, in GetYouTubePlaylistVideoFeed
uri, converter=gdata.youtube.YouTubePlaylistVideoFeedFromString)
File "/Library/Python/2.6/site-packages/gdata/service.py", line 1108, in Get
'reason': server_response.reason, 'body': result_body}
gdata.service.RequestError: {'status': 400, 'body': 'Invalid request URI', 'reason': 'Bad Request'}
It would seem the URI https://gdata.youtube.com/feeds/api/users/default/watch_later?v=2 is invalid. However this is the one stated to be used in the google documents. Am I using it wrong, or is there another issue here?
In addition if I change the URI to http://gdata.youtube.com/feeds/api/playlists/63F0C78739B09958 it works as expected.
You should check your authentication. According to Retrieving and updating a user's 'Watch Later' playlist:
Again, the link will only be present in a profile entry if either of
the following conditions is true:
You submit an authenticated request to retrieve the logged-in user's
own profile.
The watch_later playlist is publicly available for the user whose
profile you are retrieving.
The API server will return a 40x HTTP response code if you try to
retrieve a watch_later playlist and neither of the above conditions is
true.
The second link would work most likely due to the second publicly available condition being met. One thing I do notice missing from your example is the client id/source:
# A complete client login request
yt_service.email = 'jo#gmail.com'
yt_service.password = 'mypassword'
yt_service.source = 'my-example-application'
yt_service.developer_key = 'ABC123...'
yt_service.client_id = 'my-example-application'
yt_service.ProgrammaticLogin()
You should look into that and ensure that your authentication is happening properly.

ValidationError while running Google adwords client library examples

I get the following error when I try to run sample example of Google adwords
[root#some v200909]# python get_related_keywords.py Traceback (most recent call last): File "get_related_keywords.py", line 53, in
page = targeting_idea_service.Get(selector)[0] File "../../aw_api/TargetingIdeaService.py", line 105, in Get
'TargetingIdea', self.__loc, request) File "../../aw_api/WebService.py", line 350, in CallMethod
raise ValidationError(error['data']) aw_api.Errors.ValidationError: Invalid headers for 'https://adwords-sandbox.google.com', see http://code.google.com/apis/adwords/docs/developer/adwords_api_sandbox.html#requestheaders. [root#some v200909]#
This sounds like an issue with the headers you're providing. The headers must be especially formatted for the sandbox, so make sure that:
a) You're formatting the headers as specified in http://code.google.com/apis/adwords/docs/developer/adwords_api_sandbox.html#requestheaders , as Goose Bumper mentioned. This applies to both v2009 and v13, as you still need to format the developer token and client email according to the instructions (the application token is now obsolete).
b) You're choosing the right endpoint, namely adwords-sandbox.google.com for v2009 and sandbox.google.com for v13
If this still doesn't work for you, the SOAP logs for your request might be useful.

Categories