python dropbox api error - python

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.

Related

Twitter API Redirects After Authorization But Won't Give Me a PIN

I am trying to block a user account with the Twitter API through Python. Here's what my method looks like:
def block_user():
payload = {"target_user_id": "amazon"}
# Get request token
request_token_url = "https://api.twitter.com/oauth/request_token"
oauth = OAuth1Session(consumer_key, client_secret=consumer_secret,)
try:
fetch_response = oauth.fetch_request_token(request_token_url)
except ValueError:
print(
"There may have been an issue with the consumer_key or consumer_secret you entered."
)
resource_owner_key = fetch_response.get("oauth_token")
resource_owner_secret = fetch_response.get("oauth_token_secret")
print("Got OAuth token: %s" % resource_owner_key)
# Get authorization
base_authorization_url = "https://api.twitter.com/oauth/authorize"
authorization_url = oauth.authorization_url(base_authorization_url)
print("Please go here and authorize: %s" % authorization_url)
verifier = input("Paste the PIN here: ")
# Get the access token
access_token_url = "https://api.twitter.com/oauth/access_token"
oauth = OAuth1Session(
consumer_key,
client_secret=consumer_secret,
resource_owner_key=resource_owner_key,
resource_owner_secret=resource_owner_secret,
verifier=verifier,
# I tried this, it didn't work
#oauth_callback='oob',
)
oauth_tokens = oauth.fetch_access_token(access_token_url)
access_token = oauth_tokens["oauth_token"]
access_token_secret = oauth_tokens["oauth_token_secret"]
# Make the request
oauth = OAuth1Session(
consumer_key,
client_secret=consumer_secret,
resource_owner_key=access_token,
resource_owner_secret=access_token_secret,
)
# Making the request
response = oauth.post(
"https://api.twitter.com/2/users/{}/blocking".format(id), json=payload
)
if response.status_code != 200:
raise Exception(
"Request returned an error: {} {}".format(response.status_code, response.text)
)
print("Response code: {}".format(response.status_code))
# Saving the response as JSON
json_response = response.json()
print(json.dumps(json_response, indent=4, sort_keys=True))
In the terminal when I run the script, I get this:
Got OAuth token: 9SL...BGo
Please go here and authorize: https://api.twitter.com/oauth/authorize?oauth_token=9SL...BGo
Paste the PIN here:
So I go to the URL and it asks me to authorize the app. I authorize it, and then get redirected immediately to the redirect page of the Twitter API app settings (default.com in this case). I don't get shown a PIN to put into the prompt, I don't see any success message or anything, it just redirects immediately. Can't find anyone else with that issue using traditional search terms.
Anyone got any ideas?
I found the answer myself. So you need to add the following URL parameters to your auth/request_token URL. For me, that meant changing this line (the third line in my code block):
request_token_url = "https://api.twitter.com/oauth/request_token"
to this:
request_token_url = "https://api.twitter.com/oauth/request_token?oauth_callback=oob&x_auth_access_type=write"
I had tried using oauth_callback=oob in a few other places including my OAuth1Session object and on the authentication URL. Needs to be on the request_token URL.
sorry i can't comment right now so i will type this here :
i really recommend using the Twitter library :
Twitter python library

JIRA request token fetch error using Python

I am trying to configure and use OAuth to authenticate and request token using Python. I have generated jira private key.
import requests
from oauthlib.oauth1 import SIGNATURE_RSA,SIGNATURE_HMAC
from requests_oauthlib import OAuth1Session
from jira.client import JIRA
import time
def read(file_path):
with open(file_path) as f:
return f.read()
CONSUMER_KEY = "OauthKey"
RSA_KEY = read("jira_privatekey.pem")
JIRA_SERVER = "http://rhtstngjira012:8080"
REQUEST_TOKEN_URL = JIRA_SERVER + "/plugins/servlet/oauth/request-token"
AUTHORIZE_URL = JIRA_SERVER + "/plugins/servlet/oauth/authorize"
ACCESS_TOKEN_URL = JIRA_SERVER + "/plugins/servlet/oauth/access-token"
oauth = OAuth1Session(CONSUMER_KEY, signature_type="auth_header", signature_method=SIGNATURE_RSA, rsa_key=RSA_KEY)
request_token = oauth.fetch_request_token(REQUEST_TOKEN_URL)
But while requesting tokens, I am getting the following error -
Traceback (most recent call last):
File "Access_Tokens_JIRA.py", line 23, in <module>
request_token = oauth.fetch_request_token(REQUEST_TOKEN_URL)
File "/PYTHON_SCRIPTS/Environments/TESTING/lib/python3.6/site-packages/requests_oauthlib/oauth1_session.py", line 287, in fetch_request_token
token = self._fetch_token(url, **request_kwargs)
File "/PYTHON_SCRIPTS/Environments/TESTING/lib/python3.6/site-packages/requests_oauthlib/oauth1_session.py", line 369, in _fetch_token
raise TokenRequestDenied(error % (r.status_code, r.text), r)
requests_oauthlib.oauth1_session.TokenRequestDenied: Token request failed with code 401, response was 'oauth_problem=signature_invalid&oauth_signature=ABC&oauth_signature_base_string=POST%26http%253A%252F%252Frhtstngjira012%253A8080%252Fplugins%252Fservlet%252Foauth%252Frequest-token%26oauth_consumer_key%253DOauthKey%2526oauth_nonce%123%2526oauth_signature_method%253DRSA-SHA1%2526oauth_timestamp%253D1630512420%2526oauth_version%253D1.0&oauth_signature_method=RSA-SHA1'
I have installed all latest libraries and have generated keys too. Could you please advise what I can change to request tokens from JIRA?
You should create API token and encode to base64 the whole String email:your-api-token.
You have to create API token for your user as described here: https://confluence.atlassian.com/cloud/api-tokens-938839638.html.

Using Google Picasa API with 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

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.

How to use linkedin API with python

I tried so many methods, but none seem to work. Help me make a connection with linkedin using python. I have all the tokens. I have python 2.7.5. Please post a sample of basic code that establishes a connection and gets a user's name.
Below, I have done character for character like the example said, but it doesn't work.
https://github.com/ozgur/python-linkedin <---This is where I got the api and I copied it exactly. See below:
CONSUMER_KEY = '9puxXXXXXXXX' # This is api_key
CONSUMER_SECRET = 'brtXoXEXXXXXXXX' # This is secret_key
USER_TOKEN = '27138ae8-XXXXXXXXXXXXXXXXXXXXXXXXXXX' # This is oauth_token
USER_SECRET = 'ca103e23XXXXXXXXXXXXXXXXXXXXXXXXXXX' # This is oauth_secret
from linkedin import linkedin
# Define CONSUMER_KEY, CONSUMER_SECRET,
# USER_TOKEN, and USER_SECRET from the credentials
# provided in your LinkedIn application
# 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)
# Use the app....
application.get_profile()
I get this error:
Traceback (most recent call last):
File "C:/Documents and Settings/visolank/Desktop/Python/programs/linkedinapi.py", line 8, in <module>
from linkedin import linkedin
File "C:/Documents and Settings/visolank/Desktop/Python/programs\linkedin\linkedin.py", line 2, in <module>
from requests_oauthlib import OAuth1
File "C:\Python27\lib\site-packages\requests_oauthlib\__init__.py", line 1, in <module>
from .core import OAuth1
File "C:\Python27\lib\site-packages\requests_oauthlib\core.py", line 4, in <module>
from oauthlib.oauth1 import (Client, SIGNATURE_HMAC, SIGNATURE_TYPE_AUTH_HEADER)
File "C:\Python27\lib\site-packages\requests_oauthlib\oauthlib\oauth1\__init__.py", line 12, in <module>
from .rfc5849 import Client
File "C:\Python27\lib\site-packages\requests_oauthlib\oauthlib\oauth1\rfc5849\__init__.py", line 26, in <module>
from oauthlib.common import Request, urlencode, generate_nonce
ImportError: No module named oauthlib.common
Got it. For future reference you need to download the oauthlib from here https://github.com/idan/oauthlib
here is the full functional code:
CONSUMER_KEY = '9pux1XcwXXXXXXXXXX' # This is api_key
CONSUMER_SECRET = 'brtXoXEXXXXXXXXXXXXX' # This is secret_key
USER_TOKEN = '27138ae8-XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXb' # This is oauth_token
USER_SECRET = 'ca103e23-XXXXXXXXXXXXXXXXXXXXXXXX7bba512625e' # This is oauth_secret
RETURN_URL = 'http://localhost:8000'
from linkedin import linkedin
from oauthlib import *
# Define CONSUMER_KEY, CONSUMER_SECRET,
# USER_TOKEN, and USER_SECRET from the credentials
# provided in your LinkedIn application
# 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)
# Use the app....
g = application.get_profile()
print g
You can get USER_TOKEN & USER_SECRET in such way (if you have CONSUMER_KEY & CONSUMER_SECRET):
import oauth2 as oauth
import urllib
consumer_key = '' #from Linkedin site
consumer_secret = '' #from Linkedin site
consumer = oauth.Consumer(consumer_key, consumer_secret)
client = oauth.Client(consumer)
request_token_url = 'https://api.linkedin.com/uas/oauth/requestToken'
resp, content = client.request(request_token_url, "POST")
if resp['status'] != '200' :
raise Exception('Invalid response %s.' % resp['status'])
content_utf8 = str(content,'utf-8')
request_token = dict(urllib.parse.parse_qsl(content_utf8))
authorize_url = request_token['xoauth_request_auth_url']
print('Go to the following link in your browser:', "\n")
print(authorize_url + '?oauth_token=' + request_token['oauth_token'])
accepted='n'
while accepted.lower() == 'n' :
accepted = input('Have you authorized me? (y/n)')
oauth_verifier = input('What is the PIN?')
access_token_url = 'https://api.linkedin.com/uas/oauth/accessToken'
token = oauth.Token(request_token['oauth_token'], request_token['oauth_token_secret'])
token.set_verifier(oauth_verifier)
client = oauth.Client(consumer, token)
resp, content = client.request(access_token_url, 'POST')
content8 = str(content,'utf-8')
access_token = dict(urllib.parse.parse_qsl(content8))
print('Access Token:', "\n")
print('- oauth_token = ' + access_token['oauth_token']+'\n')
print('- oauth_token_secret = ' + access_token['oauth_token_secret'])
print('You may now access protected resources using the access tokens above.')

Categories