Dropbox Python SDK SSL error - python

I am learning how to use the Dropbox Python SDK. However, I run into a problem when I try to generate my request token. Here is the code I am using (note that I have replaced my actual app key and secret with APP_KEY and APP_SECRET here, but I used my actual app key and secret when I try it out.)
from dropbox import client, rest, session
APP_KEY = 'APP_KEY'
APP_SECRET = 'APP_SECRET'
ACCESS_TYPE = 'app_folder'
print 'Creating session object'
sess = session.DropboxSession(APP_KEY, APP_SECRET, ACCESS_TYPE)
print 'Session created!\nCreating request token'
request_token = sess.obtain_request_token()
print 'Created request token!'
url = sess.build_authorize_url(request_token)
print url
raw_input()
access_token = sess.obtain_access_token(request_token)
client1 = client.DropboxClient(sess)
print client1.account_info()
I had the program print out messages as it was creating the different objects so that I could see where the error occurred. This is the output:
aaron#Aarons-Ubuntu-Computer:~/Twisted$ python example.py
Creating session object
Session created!
Creating request token
Traceback (most recent call last):
File "example.py", line 8, in <module>
request_token = sess.obtain_request_token()
File "/usr/local/lib/python2.7/dist-packages/dropbox-1.4-py2.7.egg/dropbox/session.py", line 160, in obtain_request_token
response = rest.RESTClient.POST(url, headers=headers, params=params, raw_response=True)
File "/usr/local/lib/python2.7/dist-packages/dropbox-1.4-py2.7.egg/dropbox/rest.py", line 140, in POST
return cls.request("POST", url, post_params=params, headers=headers, raw_response=raw_response)
File "/usr/local/lib/python2.7/dist-packages/dropbox-1.4-py2.7.egg/dropbox/rest.py", line 64, in request
conn = ProperHTTPSConnection(host, 443)
File "/usr/local/lib/python2.7/dist-packages/dropbox-1.4-py2.7.egg/dropbox/rest.py", line 214, in __init__
self.cert_reqs = ssl.CERT_REQUIRED
AttributeError: 'module' object has no attribute 'CERT_REQUIRED'
I had tried using this code before, and I didn't experience this problem. I have also removed the Dropbox SDK and reinstalled it, with no result. What is causing this problem, and how can I fix it?
UPDATE
After adding Kannan's code, the output looks like this:
Ready
Generating session
Session Generated!
Generating request token
['Certificate', 'CertificateOptions', 'CertificateRequest', 'Client', 'ClientContextFactory', 'Connector', 'ContextFactory', 'DN', 'DefaultOpenSSLContextFactory', 'DistinguishedName', 'KeyPair', 'Port', 'PrivateCertificate', 'SSL', 'Server', '__all__', '__builtins__', '__doc__', '__file__', '__name__', '__package__', 'implementedBy', 'implements', 'implementsOnly', 'interfaces', 'supported', 'tcp']
Then I get the error. I have tried re-created my SSL certificates with no luck.

I'm getting the same error. I tried what you suggested, and it turns out that ssl module has no attribute 'file', and only has ['doc', 'loader', 'name', 'package'] when I print dir(ssl). Also worth noting is that when I try print str(ssl) in google app engine, I see:
module 'ssl' (built-in)
but when I run python from the command line, I see:
module 'ssl' from '/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ssl.pyc'
and the ssl from the command line has a file attribute.
Not sure how ssl is getting hijacked... but I'm pretty sure it is.
EDIT: loader is google.appengine.tools.dev_appserver_import_hook.HardenedModulesHook object at 0x1142684d0
EDIT: found a related problem here: SSLError on Google App Engine (local dev-server)

This is strange. The Python 2.7 docs definitely mention ssl.CERT_REQUIRED.
Try modifying the SDK and, right before the line that fails, add in
print dir(ssl)
print ssl.__file__
That might help you figure out what's going wrong.

Related

Status parameter not working when using python blogger api

I'm trying to use google-api-python-client 1.12.5 with Service account auth under Python 3.8. It seems to me that the when specifying the status parameter, Google responds with a 404 HTTP code. I can't figure out why. I also looked in the docs but I can't relate anything to this error.
I have pasted my code. The error is happening in the third call.
This is the code:
from google.oauth2 import service_account
from googleapiclient.discovery import build
SCOPES = ['https://www.googleapis.com/auth/blogger']
SERVICE_ACCOUNT_FILE = 'new_service_account.json'
BLOG_ID = '<your_blog_id>'
credentials = service_account.Credentials.from_service_account_file(
SERVICE_ACCOUNT_FILE, scopes=SCOPES)
service = build('blogger', 'v3', credentials=credentials)
p = service.posts()
# FIRST
promise = p.list(blogId=BLOG_ID)
result = promise.execute()
# SECOND
promise = p.list(blogId=BLOG_ID, orderBy='UPDATED')
result = promise.execute()
#THIRD
promise = p.list(blogId=BLOG_ID, orderBy='UPDATED', status='DRAFT')
result = promise.execute() # <===== ERROR HAPPENS HERE!!!!
service.close()
And this is the traceback:
Traceback (most recent call last):
File "/home/madtyn/.local/share/JetBrains/Toolbox/apps/PyCharm-P/ch-0/202.7660.27/plugins/python/helpers/pydev/pydevd.py", line 1448, in _exec
pydev_imports.execfile(file, globals, locals) # execute the script
File "/home/madtyn/.local/share/JetBrains/Toolbox/apps/PyCharm-P/ch-0/202.7660.27/plugins/python/helpers/pydev/_pydev_imps/_pydev_execfile.py", line 18, in execfile
exec(compile(contents+"\n", file, 'exec'), glob, loc)
File "/home/madtyn/PycharmProjects/blogger/main.py", line 24, in <module>
result = promise.execute()
File "/home/madtyn/venvs/blogger/lib/python3.8/site-packages/googleapiclient/_helpers.py", line 134, in positional_wrapper
return wrapped(*args, **kwargs)
File "/home/madtyn/venvs/blogger/lib/python3.8/site-packages/googleapiclient/http.py", line 915, in execute
raise HttpError(resp, content, uri=self.uri)
googleapiclient.errors.HttpError: <HttpError 404 when requesting https://blogger.googleapis.com/v3/blogs/<blog_id>/posts?orderBy=UPDATED&status=DRAFT&alt=json returned "Not Found">
python-BaseException
I can reproduce this issue... Adding status=DRAFT will return 404 but any other filter is working...
Tried with service account and your code: 404
Tried with API Key like this result = requests.get('https://blogger.googleapis.com/v3/blogs/<blog_id>/posts?status=DRAFT&orderBy=UPDATED&alt=json&key=<api_key>'): 404
Extracted "access_token" from service account (credentials.token after a call): result = requests.get('https://blogger.googleapis.com/v3/blogs/<blog_id>/posts?status=DRAFT&orderBy=UPDATED&alt=json&access_token=<extracted_service_account_token>'): 404
But very strangely if I use access_token given by "Try this API" here : https://developers.google.com/blogger/docs/3.0/reference/posts/list?apix_params={"blogId"%3A"blog_id"%2C"orderBy"%3A"UPDATED"%2C"status"%3A["DRAFT"]%2C"alt"%3A"json"} it's works !
Used that token with requests give me my blog post in draft status...
Just copy/paste raw Authorization header inside that script:
import requests
blog_id = '<blog_id>'
headers = {
'Authorization' : 'Bearer <replace_here>'
}
# Using only Authorization header
result = requests.get(
'https://blogger.googleapis.com/v3/blogs/%s/posts?status=DRAFT&orderBy=UPDATED&alt=json' % (blog_id),
headers=headers
)
print(result)
# This should print DRAFT if you have at least one draft post
print(result.json()['items'][0]['status'])
# Using "access_token" param constructed with Authorization header splited to have only token
result = requests.get('https://blogger.googleapis.com/v3/blogs/%s/posts?status=DRAFT&orderBy=UPDATED&alt=json&access_token=%s' % (blog_id, headers['Authorization'][len('Bearer '):]))
print(result)
# This should print DRAFT if you have at least one draft post
print(result.json()['items'][0]['status'])
Results I have currently:
The bug doesn't seem to come from the library but rather from the token rights...However I also used the console normally to generate accesses like you.
To conclude I think it's either a bug or it's voluntary from Google... I don't know how long the "Try this API" token is valid but it is currently the only way I found to get the draft articles... Maybe you can try to open a bug ticket but I don't know specifically where it is possible to do that.

Foursquare authentication - 'No handlers could be found for logger "foursquare"'

I'm starting with the Foursquare API, in Python, and I'm not sure why I can't authenticate.
Following the tutorial, so far I have this piece of code:
import foursquare
client = foursquare.Foursquare(client_id=myid, client_secret=mysecret,
redirect_uri='http://fondu.com/oauth/authorize')
auth_uri = client.oauth.auth_url()
access_token = client.oauth.get_token('XX_CODE_RETURNED_IN_REDIRECT_XX')
client.set_access_token(access_token)
client.venues.explore(params={'near': 'New York, NY', 'time' : date})
I've created an app here:
https://foursquare.com/developers/apps
and I'm using both:
Client id
Client secret
shown in the page.
However, when running this code, I get:
No handlers could be found for logger "foursquare"
Traceback (most recent call last):
File "noiseInference.py", line 270, in <module>
getFoursquareCheckIns(date)
File "noiseInference.py", line 156, in getFoursquareCheckIns
access_token = client.oauth.get_token('XX_CODE_RETURNED_IN_REDIRECT_XX')
File "/Library/Python/2.7/site-packages/foursquare/__init__.py", line 134, in get_token
response = _request_with_retry(url)
File "/Library/Python/2.7/site-packages/foursquare/__init__.py", line 707, in _request_with_retry
return _process_request_with_httplib2(url, headers, data)
File "/Library/Python/2.7/site-packages/foursquare/__init__.py", line 730, in _process_request_with_httplib2
return _check_response(data)
File "/Library/Python/2.7/site-packages/foursquare/__init__.py", line 763, in _check_response
raise FoursquareException(errmsg)
foursquare.FoursquareException: Response format invalid, missing meta property. data: {u'error': u'invalid_client'}
Not sure what's the problem.
The handler message is just complaining you didn't set up a logger under for the foursquare namespace.
Your real error is the message at the end of the stack trace:
foursquare.FoursquareException:
Response format invalid, missing meta property. data: {u'error': u'invalid_client'}
The message indicates that your client's credentials are incorrect. The credentials aren't fully checked until you attempt to use the client for a privileged action like client.set_access_token, so the most likely culprit here is to look at what you pass for client_secret when constructing the Foursquare client object.
client_id is probably not the problem because you'd have to go through the URL-OAuth flow in order to get the access_token you use.

openstack: novaclient Python API not working

Trying to follow a simple tutorial for the openstack python API I found at http://docs.openstack.org/developer/python-novaclient/api.html but doesn't seem to be working. When I try to run
nova.servers.list()
or
nova.flavors.list()
from the tutorial on the python interpreter, I get following error:
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/dist-packages/novaclient/v2/servers.py", line 617, in list
return self._list("/servers%s%s" % (detail, query_string), "servers")
File "/usr/lib/python2.7/dist-packages/novaclient/base.py", line 64, in _list
_resp, body = self.api.client.get(url)
File "/usr/lib/python2.7/dist-packages/novaclient/client.py", line 440, in get
return self._cs_request(url, 'GET', **kwargs)
File "/usr/lib/python2.7/dist-packages/novaclient/client.py", line 399, in _cs_request
self.authenticate()
File "/usr/lib/python2.7/dist-packages/novaclient/client.py", line 569, in authenticate
self._v2_auth(auth_url)
File "/usr/lib/python2.7/dist-packages/novaclient/client.py", line 634, in _v2_auth
return self._authenticate(url, body)
File "/usr/lib/python2.7/dist-packages/novaclient/client.py", line 647, in _authenticate
**kwargs)
File "/usr/lib/python2.7/dist-packages/novaclient/client.py", line 392, in _time_request
resp, body = self.request(url, method, **kwargs)
File "/usr/lib/python2.7/dist-packages/novaclient/client.py", line 386, in request
raise exceptions.from_response(resp, body, url, method)
novaclient.exceptions.NotFound: The resource could not be found. (HTTP 404)
I'm using the same credentials as admin_openrc.sh, which works. Can't figure out what might be the problem.
You're using the python-novaclient as a library and it was never designed to be used that way. It's a CLI that people unfortunately use as a library.
Give the official Python OpenStack SDK a try.
pip install openstacksdk
The code for listing servers or flavors.
import sys
from openstack import connection
from openstack import profile
from openstack import utils
utils.enable_logging(True, stream=sys.stdout)
prof = profile.Profile()
prof.set_region(prof.ALL, 'RegionOne')
conn = connection.Connection(
auth_url='http://my.openstack.com:5000/v2.0',
profile=prof,
username='demo',
project_name='demo',
password='demo')
for server in conn.compute.servers():
print(server)
for flavor in conn.compute.flavors():
print(flavor)
More info that might be helpful too:
http://python-openstacksdk.readthedocs.org/en/latest/users/guides/compute.html
https://pypi.python.org/pypi/openstacksdk
From your description, CLI works fine but script/interpreter fail, so it definitely because you initialize the novaclient.client.Client in a wrong way.
The usage of novaclient.client.Client depends on what version you are using, but your question doesn't provide such information, so currently I cannot provide an example for you, you can check it by run command 'nova --version'.
you can get help from developer documents for python-novaclient http://docs.openstack.org/developer/python-novaclient/api.html
Remember that, it is a good practice to use keyword argument instead of normal argument, which means
nc = client.Client(version=2, user='admin', password='password',
project_id='12345678', auth_url='http://127.0.0.1:5000')
is encouraged, it will expose problem when you try to do something in a wrong way.
Solved the issue: not sure why, openstack complained of missing user domain in auth (don't remember the exactly message error). Couldn't find how to inform user domain in nova, but I do found it on keystone!
from keystoneclient.auth.identity import v3
from keystoneclient import session
from keystoneclient.v3 import client
auth_url = 'http://10.37.135.89:5000/v3/'
username = 'admin'
user_domain_name = 'Default'
project_name = 'admin'
project_domain_name = 'Default'
password = '123456'
auth = v3.Password(auth_url=auth_url,
username=username,
password=password,
project_id='d5eef1aae54742e787d0653eea57254b',
user_domain_name=user_domain_name)
sess = session.Session(auth=auth)
keystone = client.Client(session=sess)
keystone.projects.list()
and after that I used keystone for authenticating in nova:
from novaclient import client
nova = client.Client(2, session=keystone.session)
nova.flavors.list()
Some usefull links that I used for this answer:
http://docs.openstack.org/developer/python-keystoneclient/authentication-plugins.html
http://docs.openstack.org/developer/python-keystoneclient/using-api-v3.html
http://docs.openstack.org/developer/python-novaclient/api.html

Google Adwords API authentication issue

Just getting started on the Adwords API, for some reason I can't seem to connect at all.
The code below, straight from the tutorial throws the error:
Traceback (most recent call last):
File "<pyshell#12>", line 1, in <module>
client = AdWordsClient(path=os.path.join('Users', 'ravinthambapillai', 'Google Drive', 'client_secrets.json'))
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/adspygoogle/adwords/AdWordsClient.py", line 151, in __init__
self._headers = self.__LoadAuthCredentials()
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/adspygoogle/adwords/AdWordsClient.py", line 223, in __LoadAuthCredentials
return super(AdWordsClient, self)._LoadAuthCredentials()
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/adspygoogle/common/Client.py", line 94, in _LoadAuthCredentials
raise ValidationError(msg)
**ValidationError: Authentication data is missing.**
from adspygoogle.adwords.AdWordsClient import AdWordsClient
from adspygoogle.common import Utils
client = AdWordsClient(path=os.path.join('Users', 'this-user', 'this-folder', 'client_secrets.json'))
It looks like there's two issues. First, try removing the last path element, as far as I recall, the path parameter expects a directory that contains the authentication pickle, logs etc. This approach requires that you already have a valid auth_token.pkl.
Second, it appears that you're using OAuth2 for authentication (I'm guessing by the client_secrets.json file). For this to work, you'll need to use the oauth2client library and provide an oauth2credentials instance in the headers parameter to AdWordsClient.
The following is straight from the file examples/adspygoogle/adwords/v201302/misc/use_oauth2.py in the client distribution and should give you an idea how it works:
# We're using the oauth2client library:
# http://code.google.com/p/google-api-python-client/downloads/list
flow = OAuth2WebServerFlow(
client_id=oauth2_client_id,
client_secret=oauth2_client_secret,
# Scope is the server address with '/api/adwords' appended.
scope='https://adwords.google.com/api/adwords',
user_agent='oauth2 code example')
# Get the authorization URL to direct the user to.
authorize_url = flow.step1_get_authorize_url()
print ('Log in to your AdWords account and open the following URL: \n%s\n' %
authorize_url)
print 'After approving the token enter the verification code (if specified).'
code = raw_input('Code: ').strip()
credential = None
try:
credential = flow.step2_exchange(code)
except FlowExchangeError, e:
sys.exit('Authentication has failed: %s' % e)
# Create the AdWordsUser and set the OAuth2 credentials.
client = AdWordsClient(headers={
'developerToken': '%s++USD' % email,
'clientCustomerId': client_customer_id,
'userAgent': 'OAuth2 Example',
'oauth2credentials': credential
})
I am not familiar with the AdWordsClient api but are you sure your path is correct?
your current join produces a relative path, do you need an absolute one?
>>> import os
>>> os.path.join('Users', 'this-user')
'Users/this-user'
For testing you could hardcode the absoulte path in to make sure it is not a path issue
I would also make sure that 'client_secrets.json exists, and that it is readable by the user executing python

Twython: Error running the examples

Hi i have just started to evaluate different options for python>Twitter api:s.
I have written some code looking at the examples in the Twython package but i always end up getting the same error.
AttributeError: 'Twython' object has no attribute 'auth'
I also get the same error running the included core_example files.
I am running "2.0.0" from git.
/System/Library/Frameworks/Python.framework/Versions/2.7/bin/python /Users/skjortan/dev/trunk/3rdPartyLibs/twython/core_examples/current_trends.py
Traceback (most recent call last):
File "/Users/skjortan/dev/trunk/3rdPartyLibs/twython/core_examples/current_trends.py", line 5, in <module>
trends = twitter.getCurrentTrends()
File "/Library/Python/2.7/site-packages/twython-2.0.0-py2.7.egg/twython/twython.py", line 167, in <lambda>
return lambda **kwargs: self._constructFunc(key, **kwargs)
File "/Library/Python/2.7/site-packages/twython-2.0.0-py2.7.egg/twython/twython.py", line 188, in _constructFunc
content = self._request(url, method=method, params=kwargs)
File "/Library/Python/2.7/site-packages/twython-2.0.0-py2.7.egg/twython/twython.py", line 205, in _request
response = func(url, data=myargs, auth=self.auth)
AttributeError: 'Twython' object has no attribute 'auth'
Process finished with exit code 1
I noticed your question - I'm the author of Twython. A fix has been committed and pushed out for a 2.0.1 release. If you update your installation this should no longer be an issue.
Thanks, sorry for the hassle! Bug that slipped by our 2.0.0 release.
But its really has no attribute 'auth' but it has methods like:
def get_authentication_tokens(self):
"""Returns an authorization URL for a user to hit."""
def get_authorized_tokens(self):
"""Returns authorized tokens after they go through the auth_url phase."""
And this is sample from django-twython how its author make auth
def begin_auth(request):
"""
The view function that initiates the entire handshake.
For the most part, this is 100% drag and drop.
"""
# Instantiate Twython with the first leg of our trip.
twitter = Twython(
twitter_token = settings.TWITTER_KEY,
twitter_secret = settings.TWITTER_SECRET,
callback_url = request.build_absolute_uri(reverse('twython_django_oauth.views.thanks')))
# Request an authorization url to send the user to...
auth_props = twitter.get_authentication_tokens()
# Then send them over there, durh.
request.session['request_token'] = auth_props
return HttpResponseRedirect(auth_props['auth_url'])
apparently twitter api and does not allow normal login, just for oauth, creates the application on Twitter and OAuth Settings tab from there takes the data from OAuth Settings, and methods of oauth in:
http://pydoc.net/twython/1.4.5/twython.twitter_endpoints

Categories

Resources