Using Google Picasa API with Python - python

I have been using Google's Picasa API successfully from last 6 months or so.
Today I have started getting an error
raise GooglePhotosException(e.args[0])
GooglePhotosException: (403, 'Forbidden', 'Authorization required')
I checked my credentials.
self.gd_client = gdata.photos.service.PhotosService()
self.gd_client.email = EmailOfTheUploadingPictureAccount
self.gd_client.password = PasswordOfTheAccount
self.gd_client.source = 'destipak' #Not sure about that
self.feed_url = "/data/feed/api/user/"
self.entry_url = "/data/entry/api/user/"
self.gd_client.ProgrammaticLogin()
Everything was working well since yesterday. Anyone has any clues?
EDIT
Example given on Picasa for python is also not working.
URL
#!/usr/bin/python2.5
import gdata.photos.service
import gdata.media
import gdata.geo
gd_client = gdata.photos.service.PhotosService()
gd_client.email = '=change=' # Set your Picasaweb e-mail address...
gd_client.password = '=change=' # ... and password
gd_client.source = 'api-sample-google-com'
gd_client.ProgrammaticLogin()
albums = gd_client.GetUserFeed()
for album in albums.entry:
print 'Album: %s (%s)' % (album.title.text, album.numphotos.text)
photos = gd_client.GetFeed('/data/feed/api/user/default/albumid/%s?kind=photo' % (album.gphoto_id.text))
for photo in photos.entry:
print ' Photo:', photo.title.text
tags = gd_client.GetFeed('/data/feed/api/user/default/albumid/%s/photoid/%s?kind=tag' % (album.gphoto_id.text, photo.gphoto_id.text))
for tag in tags.entry:
print ' Tag:', tag.title.text
comments = gd_client.GetFeed('/data/feed/api/user/default/albumid/%s/photoid/%s?kind=comment' % (album.gphoto_id.text, photo.gphoto_id.text))
for comment in comments.entry:
print ' Comment:', comment.content.text
EDIT 2
Full traceback
Traceback (most recent call last):
File "/Users/mac/Picasa_API.py", line 158, in <module>
check_api()
File "/Users/mac/Picasa_API.py", line 140, in check_api
albums = gd_client.GetUserFeed()
File "/Users/mac/destipak/env/lib/python2.7/site-packages/gdata/photos/service.py", line 235, in GetUserFeed
return self.GetFeed(uri, limit=limit)
File "/Users/mac/destipak/env/lib/python2.7/site-packages/gdata/photos/service.py", line 180, in GetFeed
raise GooglePhotosException(e.args[0])
gdata.photos.service.GooglePhotosException: (403, 'Forbidden', 'Authorization required')

Here is the code I use to get OAuth2 authentication working with Picasa. First you need to create a client ID through the Google Developer Console: at https://console.developers.google.com/ and then you must download the client secrets as JSON and pass the filename to OAuth2Login.
The first time you run this code, you will have to authorize the client through your web browser, and paste the code you get there into the application. The credentials are then stored in the file specified by credential_store.
def OAuth2Login(client_secrets, credential_store, email):
scope='https://picasaweb.google.com/data/'
user_agent='myapp'
storage = Storage(credential_store)
credentials = storage.get()
if credentials is None or credentials.invalid:
flow = flow_from_clientsecrets(client_secrets, scope=scope, redirect_uri='urn:ietf:wg:oauth:2.0:oob')
uri = flow.step1_get_authorize_url()
webbrowser.open(uri)
code = raw_input('Enter the authentication code: ').strip()
credentials = flow.step2_exchange(code)
storage.put(credentials)
if (credentials.token_expiry - datetime.utcnow()) < timedelta(minutes=5):
http = httplib2.Http()
http = credentials.authorize(http)
credentials.refresh(http)
gd_client = gdata.photos.service.PhotosService(source=user_agent,
email=email,
additional_headers={'Authorization' : 'Bearer %s' % credentials.access_token})
return gd_client

I ran into this as well. Seems like email/password authentication has been turned off, and we need to switch to OAuth2. See
https://groups.google.com/forum/#!topic/Google-Picasa-Data-API/4meiAJ40l3E

Related

Python - Create album with Picasa Error

Google have recently shifted to OAuth2.0 and we need to change our previous auth macanisms (i.e. from ProgrammaticLogin to OAuth2.0).
I can successfully access the albums and read the data / comments on photos. Its when i try to add new album/photo or try to write data i get the following error.
client = PhotosService(email="xxxx")
...
...
...
#After successfull OAuth
album = client.InsertAlbum(title="Temp album", summary="My summary", access="public")
This line causing the following error.
File "/Users/mac/destipak/env/lib/python2.7/site-packages/gdata/photos/service.py", line 358, in InsertAlbum
raise GooglePhotosException(e.args[0])
gdata.photos.service.GooglePhotosException: (403, 'Forbidden', 'Modification only allowed with api authentication.')
I wasn't quite sure but did you actually make the change over OAuth2? I used the following code and it worked.
def OAuth2Login(client_secrets, credential_store, email):
scope='https://picasaweb.google.com/data/'
user_agent='testingApp'
storage = Storage(credential_store)
credentials = storage.get()
if credentials is None or credentials.invalid:
flow = flow_from_clientsecrets(client_secrets, scope=scope, redirect_uri='urn:ietf:wg:oauth:2.0:oob')
uri = flow.step1_get_authorize_url()
webbrowser.open(uri)
code = raw_input('Enter the authentication code: ').strip()
credentials = flow.step2_exchange(code)
storage.put(credentials)
if (credentials.token_expiry - datetime.utcnow()) < timedelta(minutes=5):
http = httplib2.Http()
http = credentials.authorize(http)
credentials.refresh(http)
gd_client = gdata.photos.service.PhotosService(source=user_agent,
email=email,
additional_headers={'Authorization' : 'Bearer %s' % credentials.access_token})
return gd_client
album = gd_client.InsertAlbum('test', 'My Test Album', access='protected')
I did have to create an API Key in the Google developer portal and download the json secret but after doing that I was able to create an album successfully. This repo was very helpful https://github.com/MicOestergaard/picasawebuploader.

Using Google API Python client with SignedJwtAssertionCredentials

I am trying to get a list of users from Google using google_api_python_client-1.4.0. I getting the access_denied error even through I have domain wide delegation authority.
Interesting thing is that.. when I use the same certificate/credentials with .net client library, it works.
The error I am getting is
File "/Library/Python/2.7/site-packages/oauth2client-1.4.6-py2.7.egg/oauth2client/client.py", line 807, in _do_refresh_request
oauth2client.client.AccessTokenRefreshError: access_denied: Requested client not authorized.
# Load the key in PKCS 12 format that you downloaded from the Google API
# Console when you created your Service account.
f = file('Gkeys/87ty8g87-privatekey.p12', 'rb')
key = f.read()
f.close()
# Create an httplib2.Http object to handle our HTTP requests and authorize it
# with the Credentials. Note that the first parameter, service_account_name,
# is the Email address created for the Service account. It must be the email
# address associated with the key that was created.
credentials = SignedJwtAssertionCredentials(
'889h98h98h98h98h9lurk#developer.gserviceaccount.com',
key,
scope=['https://www.googleapis.com/auth/admin.directory.group.readonly','https://www.googleapis.com/auth/admin.directory.user.readonly'],
private_key_password='notasecret',
sub='admin.user#domain.com'
)
http = httplib2.Http()
http = credentials.authorize(http)
directory_service = build('admin', 'directory_v1', http=http)
all_users = []
page_token = None
params = {'groupKey': 'groupname#domain.com'}
while True:
try:
if page_token:
params['pageToken'] = page_token
#current_page = directory_service.users().list(**params).execute()
#current_page = directory_service.members().list(**params).execute()
current_page = directory_service.members().list(groupKey='groupname#domain.com').execute()
all_users.extend(current_page['users'])
page_token = current_page.get('nextPageToken')
if not page_token:
break
except errors.HttpError as error:
print 'An error occurred: %s' % error
break
for user in all_users:
print user['primaryEmail']
Are you sure the scopes you authorized in the control panel exactly match those you're requesting here? If you authorized the read/write scope and are using the readonly scope here I believe that would cause your error.

how to access gmail use python?

I wanna access gmail use python and oauth2.0,so I download the oauth2.py from "http://google-mail-oauth2-tools.googlecode.com/svn/trunk/python/oauth2.py". And this is my demo:
import oauth2
import imaplib
import email
from oauth2client.client import OAuth2WebServerFlow
from launchpadlib.credentials import access_token_page
email = 'karlvorndoenitz#gmail.com'
client_id = 'client_id'
client_secret = 'client_secret'
# Check https://developers.google.com/drive/scopes for all available scopes
OAUTH_SCOPE = 'https://mail.google.com/'
# Redirect URI for installed apps
REDIRECT_URI = 'urn:ietf:wg:oauth:2.0:oob'
flow = OAuth2WebServerFlow(client_id, client_secret, OAUTH_SCOPE, REDIRECT_URI)
authorize_url = flow.step1_get_authorize_url()
print 'Go to the following link in your browser: ' + authorize_url
authorization_code = raw_input("Please input the code:").strip()
response = oauth2.AuthorizeTokens(client_id, client_secret, authorization_code)
access_token = response['access_token']
auth_string = oauth2.GenerateOAuth2String(email,access_token,base64_encode=True)
print auth_string
imap_conn = imaplib.IMAP4_SSL('imap.gmail.com')
imap_conn.debug = 4
imap_conn.authenticate('XOAUTH2',lambda x:auth_string)
imap_conn.select('INBOX')
But the demo has some bugs,I don't know how to debug it.The information from console:
16:58.52 > KOMN1 AUTHENTICATE XOAUTH2
16:58.79 < +
16:58.79 write literal size 204
16:59.27 < + eyJzdGF0dXMiOiI0MDAiLCJzY2hlbWVzIjoiQmVhcmVyIiwic2NvcGUiOiJodHRwczovL21haWwuZ29vZ2xlLmNvbS8ifQ==
16:59.27 write literal size 204
16:59.27 < KOMN1 NO Invalid SASL argument. d10if1169757igr.56
16:59.27 NO response: Invalid SASL argument. d10if1169757igr.56
Traceback (most recent call last):
File "/home/karl/workspace/Gmail/download_gmail/download_gmail_api.py", line 33, in <module>
imap_conn.authenticate('XOAUTH2',lambda x:auth_string)
File "/usr/lib/python2.7/imaplib.py", line 351, in authenticate
raise self.error(dat[-1])
imaplib.error: Invalid SASL argument. d10if1169757igr.56
I need help.
The auth_string should not be base64encoded. I believe the IMAP4.authenticate encodes it for you. It worked for me anyways.
For example:
auth_string = 'user=%s\1auth=Bearer %s\1\1' % (user, access_token)

403 Forbidden error google plus python

There are my codes:
import pprint
import httplib2
from apiclient.discovery import build
from oauth2client.client import OAuth2WebServerFlow
SCOPES = ['https://www.googleapis.com/auth/plus.me',
'https://www.googleapis.com/auth/plus.stream.write']
REDIRECT_URI = 'urn:ietf:wg:oauth:2.0:oob'
CLIENT_ID = "my client id"
CLIENT_SECRET = "my client secret"
flow = OAuth2WebServerFlow(client_id=CLIENT_ID,
client_secret=CLIENT_SECRET,
scope=SCOPES,
redirect_uri=REDIRECT_URI)
auth_uri = flow.step1_get_authorize_url()
print 'Please paste this URL in your browser to authenticate this program.'
print auth_uri
code = raw_input('Enter the code it gives you here: ')
credentials = flow.step2_exchange(code)
http = httplib2.Http()
http = credentials.authorize(http)
service = build('plusDomains', 'v1', http=http)
user_id = 'me'
print('Insert activity')
result = service.activities().insert(
userId = user_id,
body = {
'object' : {
'originalContent' : 'Happy Monday! #caseofthemondays'
},
'access' : {
'items' : [{
'type' : 'domain'
}],
'domainRestricted': True
}
}).execute()
print('result = %s' % pprint.pformat(result))
and there are my error:
Traceback (most recent call last):
File "/home/karl/workspace/googleplus/google_plus/google_plus_pic.py", line 44, in <module>
'domainRestricted': False
File "/usr/local/lib/python2.7/dist-packages/oauth2client/util.py", line 128, in positional_wrapper
return wrapped(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/apiclient/http.py", line 680, in execute
raise HttpError(resp, content, uri=self.uri)
apiclient.errors.HttpError: <HttpError 403 when requesting https://www.googleapis.com/plusDomains/v1/people/me/activities?alt=json returned "Forbidden">
I have read a lot of information,but I don't know how to solve the problem.
Where is the bug?
To use the Google+ Domains API, you need to make sure that the Domain for the user you are acting on behalf of has been set up with the right permissions for your app. These instructions are under the "Delegate domain-wide authority to your service account" section of Step 1 of the quick-start guide.
Specifically, you need to associate your app's Client ID with the scopes your app will use in the control panel for the domain. The domain administrator is the only person who can do this--so if you are working with another domain, be sure you get in contact with that person. Also, the scopes listed in the control panel must match EXACTLY with the scopes you request in your app.

python dropbox api error

I'm following the tutorial here
So far so good but the upload example give me errors. The code:
from dropbox import client, rest, session
f = open('txt2.txt') # upload a file
response = client.put_file('/magnum-opus.txt', f)
print "uploaded:", response
The error:
Traceback (most recent call last):
File "dropbox_ul.py", line 4, in <module>
response = client.put_file('/magnum-opus.txt', f)
AttributeError: 'module' object has no attribute 'put_file'
Where did I go wrong?
EDIT: The new code I'm trying. This is actually from the dropbox developer website. As I stated earlier, I did go through the authentication and setup:
# Include the Dropbox SDK libraries
from dropbox import client, rest, session
# Get your app key and secret from the Dropbox developer website
APP_KEY = 'iqxjea6s7ctxv9j'
APP_SECRET = 'npac0nca3p3ct9f'
# ACCESS_TYPE should be 'dropbox' or 'app_folder' as configured for your app
ACCESS_TYPE = 'dropbox'
sess = session.DropboxSession(APP_KEY,APP_SECRET, ACCESS_TYPE )
request_token = sess.obtain_request_token()
# Make the user sign in and authorize this token
url = sess.build_authorize_url(request_token)
print "url:", url
print "Please authorize in the browser. After you're done, press enter."
raw_input()
# This will fail if the user didn't visit the above URL and hit 'Allow'
access_token = sess.obtain_access_token(request_token)
client = client.DropboxClient(sess)
print "linked account:", client.account_info()
f = open('txt2.txt')
response = client.put_file('/magnum-opus.txt', f)
print "uploaded:", response
folder_metadata = client.metadata('/')
print "metadata:", folder_metadata
f, metadata = client.get_file_and_metadata('/magnum-opus.txt',rev='362e2029684fe')
out = open('magnum-opus.txt', 'w')
out.write(f)
print(metadata)
and the error:
url: https://www.dropbox.com/1/oauth/authorize?oauth_token=jqbasca63c0a84m
Please authorize in the browser. After you're done, press enter.
linked account: {'referral_link': 'https://www.dropbox.com/referrals/NTMxMzM4NjY5', 'display_name': 'Greg Lorincz', 'uid': 3133866, 'country': 'GB', 'quota_info': {'shared': 78211, 'quota': 28185722880, 'normal': 468671581}, 'email': 'alkopop79#gmail.com'}
Traceback (most recent call last):
File "dropb.py", line 28, in <module>
response = client.put_file('/magnum-opus.txt', f)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/dropbox-1.4-py2.7.egg/dropbox/client.py", line 149, in put_file
return RESTClient.PUT(url, file_obj, headers)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/dropbox-1.4-py2.7.egg/dropbox/rest.py", line 146, in PUT
return cls.request("PUT", url, body=body, headers=headers, raw_response=raw_response)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/dropbox-1.4-py2.7.egg/dropbox/rest.py", line 113, in request
raise ErrorResponse(r)
dropbox.rest.ErrorResponse: [403] 'The provided token does not allow this operation'
You haven't initialized the client object. Refer to the tutorial again and you'll see this:
client = client.DropboxClient(sess)
The sess object must also be initialized before calling the client module's DropboxClient method:
sess = session.DropboxSession(APP_KEY, APP_SECRET, ACCESS_TYPE)
You should have all the required parameters (i.e., APP_KEY, APP_SECRET, ACCESS_TYPE) assigned to you when you register your application.
I followed the edited code of yours and things worked out perfectly.
from dropbox import client, rest, session
# Get your app key and secret from the Dropbox developer website
app_key = 'enter-your-app_key'
app_secret = 'enter-your-app_secret'
ACCESS_TYPE = 'dropbox'
sess = session.DropboxSession(app_key, app_secret, ACCESS_TYPE )
request_token = sess.obtain_request_token()
# Make the user sign in and authorize this token
url = sess.build_authorize_url(request_token)
print "url:", url
print "Please authorize in the browser. After you're done, press enter."
raw_input()
# This will fail if the user didn't visit the above URL and hit 'Allow'
access_token = sess.obtain_access_token(request_token)
client = client.DropboxClient(sess)
print "linked account:", client.account_info()
f = open('/home/anurag/Documents/sayan.odt')
response = client.put_file('/sayan.odt', f)
print "uploaded:", response
Notice the response and file location on your system, in your code that doesn't matches.
Thanks.

Categories