There is error in tweepy and google colab - python

This is the error
ValueError Traceback (most recent call last)
/usr/local/lib/python3.6/dist-packages/tweepy/auth.py in _get_request_token(self, access_type)
65 url += '?x_auth_access_type=%s' % access_type
---> 66 return self.oauth.fetch_request_token(url)
67 except Exception as e:
17 frames
/usr/local/lib/python3.6/dist-packages/requests_oauthlib/oauth1_session.py in fetch_request_token(self, url, realm, **request_kwargs)
286 self._client.client.realm = " ".join(realm) if realm else None
--> 287 token = self._fetch_token(url, **request_kwargs)
288 log.debug("Resetting callback_uri and realm (not needed in next phase).")
/usr/local/lib/python3.6/dist-packages/requests_oauthlib/oauth1_session.py in _fetch_token(self, url, **request_kwargs)
364 log.debug("Fetching token from %s using client %s", url, self._client.client)
--> 365 r = self.post(url, **request_kwargs)
366
/usr/local/lib/python3.6/dist-packages/requests/sessions.py in post(self, url, data, json, **kwargs)
577
--> 578 return self.request('POST', url, data=data, json=json, **kwargs)
579
/usr/local/lib/python3.6/dist-packages/requests/sessions.py in request(self, method, url, params, data, headers, cookies, files, auth, timeout, allow_redirects, proxies, hooks, stream, verify, cert, json)
515 )
--> 516 prep = self.prepare_request(req)
517
/usr/local/lib/python3.6/dist-packages/requests/sessions.py in prepare_request(self, request)
458 cookies=merged_cookies,
--> 459 hooks=merge_hooks(request.hooks, self.hooks),
460 )
/usr/local/lib/python3.6/dist-packages/requests/models.py in prepare(self, method, url, headers, files, data, params, auth, cookies, hooks, json)
317 self.prepare_body(data, files, json)
--> 318 self.prepare_auth(auth, url)
319
/usr/local/lib/python3.6/dist-packages/requests/models.py in prepare_auth(self, auth, url)
548 # Allow auth to make its changes.
--> 549 r = auth(self)
550
/usr/local/lib/python3.6/dist-packages/requests_oauthlib/oauth1_auth.py in __call__(self, r)
108 r.url, headers, _ = self.client.sign(
--> 109 unicode(r.url), unicode(r.method), None, r.headers
110 )
/usr/local/lib/python3.6/dist-packages/oauthlib/oauth1/rfc5849/__init__.py in sign(self, uri, http_method, body, headers, realm)
312 request.oauth_params.append(
--> 313 ('oauth_signature', self.get_oauth_signature(request)))
314
/usr/local/lib/python3.6/dist-packages/oauthlib/oauth1/rfc5849/__init__.py in get_oauth_signature(self, request)
126
--> 127 uri, headers, body = self._render(request)
128
/usr/local/lib/python3.6/dist-packages/oauthlib/oauth1/rfc5849/__init__.py in _render(self, request, formencode, realm)
209 headers = parameters.prepare_headers(
--> 210 request.oauth_params, request.headers, realm=realm)
211 elif self.signature_type == SIGNATURE_TYPE_BODY and request.decoded_body is not None:
/usr/local/lib/python3.6/dist-packages/oauthlib/oauth1/rfc5849/utils.py in wrapper(params, *args, **kwargs)
31 params = filter_oauth_params(params)
---> 32 return target(params, *args, **kwargs)
33
/usr/local/lib/python3.6/dist-packages/oauthlib/oauth1/rfc5849/parameters.py in prepare_headers(oauth_params, headers, realm)
58 escaped_name = utils.escape(oauth_parameter_name)
---> 59 escaped_value = utils.escape(value)
60
/usr/local/lib/python3.6/dist-packages/oauthlib/oauth1/rfc5849/utils.py in escape(u)
56 raise ValueError('Only unicode objects are escapable. ' +
---> 57 'Got %r of type %s.' % (u, type(u)))
58 # Letters, digits, and the characters '_.-' are already treated as safe
ValueError: Only unicode objects are escapable.
Got <generator object to_unicode.. at 0x7f1a83f1cf68> of type <class 'generator'>.
During handling of the above exception, another exception occurred:
TweepError Traceback (most recent call last)
/usr/local/lib/python3.6/dist-packages/tweepy/auth.py in get_authorization_url(self, signin_with_twitter, access_type)
84 url = self._get_oauth_url('authorize')
---> 85 self.request_token = self._get_request_token(access_type=access_type)
86 return self.oauth.authorization_url(url)
/usr/local/lib/python3.6/dist-packages/tweepy/auth.py in _get_request_token(self, access_type)
67 except Exception as e:
---> 68 raise TweepError(e)
69
TweepError: Only unicode objects are escapable. Got <generator object to_unicode.<locals>.<genexpr> at 0x7f1a83f1cf68> of type <class 'generator'>.
During handling of the above exception, another exception occurred:
TweepError Traceback (most recent call last)
<ipython-input-8-0d2d0c4ff837> in <module>()
1 auth = tweepy.OAuthHandler(a ,apis ,callbackurl)
----> 2 redirecurl = auth.get_authorization_url()
3 print(redirecurl)
/usr/local/lib/python3.6/dist-packages/tweepy/auth.py in get_authorization_url(self, signin_with_twitter, access_type)
86 return self.oauth.authorization_url(url)
87 except Exception as e:
---> 88 raise TweepError(e)
89
90 def get_access_token(self, verifier=None):
TweepError: Only unicode objects are escapable. Got <generator object to_unicode.<locals>.<genexpr> at 0x7f1a83f1cf68> of type <class 'generator'>.
This is the code
i use google colab so i am including this
!pip install tweepy
this is all not real i have modified it
a = ["uAtzGszfcP0J1jTebtkjrgntuhvbnkuteghvk,erhnfoqi2j1289747865432565BGzfBjrjAAAAAAA"]
apis = ["rabefnO5bypwuV5KTcuS766ncZs8ctrNtrh6pJfMwDFvrwuHprtgjivruiohgbtvuhrgyuvydgfugdryehfguirdjbvyurgfy"]
b = ["AAAAAAAAAAAAAAAAAgregregergrehyrjrtksjgnyrfuykrguyrthviurjgoierghfuywehnidf3yiueghf6yregAAAAAAAAAAAL5AKgEAAAAA3wLIE6HWAXgMPcTZ8L9t1K9Lu1I%3D6SpRSXAtJF248GnzzdJ79BSyoaDMFqfPTFe8rKnxjgm5eMCQxs"]
at = ["1333671816829rehtrTNTYGBILTEJMNGUNIOERHNGVKJRHFUKERGJNVIUDFHV.NTOBN;GUONTLR8908329407837645669377-SUFHAAynfZh8DeSx3w4yVveKm5D5Ct"]
As = ["7wYChDbdN36sGf2FJSCWBEMqk65x1I7nJ4k3B#GHKJKDVHNHIUERKNVJI.UY%$VDJKRGVNEK,FVNUIDRVBKDGUH ,KER JVKUDFHBKREJVBYDIGBGKERUFVHBKJFBRKJCNzkOmfrLA"]
importing tweepy,google,time
import tweepy
import webbrowser
import time
this is also not real
callbackurl = 'oob' # https://cybemchi.000webhostapp.com/
auth = tweepy.OAuthHandler(a ,apis ,callbackurl)
redirecurl = auth.get_authorization_url()
print(redirecurl)

Problem is because you keep it as lists
a = [ "uAtz...." ]
apis = [ "rabefn..." ]
But it should be directly string
a = "uAtz...."
apis = "rabefn..."
tweepy.OAuthHandler( a, apis, ...)
Or you should use index [0] to get string from list
a = [ "uAtz...." ]
apis = [ "rabefn..." ]
tweepy.OAuthHandler( a[0], apis[0], ... )

Related

TypeError: expected string or bytes-like object When Trying to Use Windows Authentication ( Python NTLM) with Suds

I am trying to connect to a SOAP API and authenticate using Windows Authentication. I am using suds-py3 and have installed python-ntlm3. I tried following what was outlined in this Stack Exchange post
but am getting the following error: TypeError: expected string or bytes-like object. I am relatively new to this and not sure how to diagnose this problem...my code and the full traceback are below. Can anyone see what I am doing wrong?
TypeError Traceback (most recent call last)
<ipython-input-3-d1f3f5890266> in <module>
2 ntlm = WindowsHttpAuthenticated(username='user', password='pass')
3 url = 'https://xxxxxremovedforpostxxx/winauthwebservices/sswinauthwebservice.asmx'
----> 4 client = Client(url, transport=ntlm)
c:\program files\alteryx\bin\miniconda3\envs\jupytertool_venv\lib\site-packages\suds\client.py in __init__(self, url, **kwargs)
108 self.set_options(**kwargs)
109 reader = DefinitionsReader(options, Definitions)
--> 110 self.wsdl = reader.open(url)
111 plugins = PluginContainer(options.plugins)
112 plugins.init.initialized(wsdl=self.wsdl)
c:\program files\alteryx\bin\miniconda3\envs\jupytertool_venv\lib\site-packages\suds\reader.py in open(self, url)
149 d = cache.get(id)
150 if d is None:
--> 151 d = self.fn(url, self.options)
152 cache.put(id, d)
153 else:
c:\program files\alteryx\bin\miniconda3\envs\jupytertool_venv\lib\site-packages\suds\wsdl.py in `__init__(self, url, options)`
133 log.debug('reading wsdl at: %s ...', url)
134 reader = DocumentReader(options)
--> 135 d = reader.open(url)
136 root = d.root()
137 WObject.__init__(self, root)
c:\program files\alteryx\bin\miniconda3\envs\jupytertool_venv\lib\site-packages\suds\reader.py in open(self, url)
76 d = cache.get(id)
77 if d is None:
---> 78 d = self.download(url)
79 cache.put(id, d)
80 self.plugins.document.parsed(url=url, document=d.root())
c:\program files\alteryx\bin\miniconda3\envs\jupytertool_venv\lib\site-packages\suds\reader.py in download(self, url)
92 fp = store.open(url)
93 if fp is None:
---> 94 fp = self.options.transport.open(Request(url))
95 content = fp.read()
96 fp.close()
c:\program files\alteryx\bin\miniconda3\envs\jupytertool_venv\lib\site-packages\suds\transport\https.py in open(self, request)
59 def open(self, request):
60 self.addcredentials(request)
---> 61 return HttpTransport.open(self, request)
62
63 def send(self, request):
c:\program files\alteryx\bin\miniconda3\envs\jupytertool_venv\lib\site-packages\suds\transport\http.py in open(self, request)
61 u2request = u2.Request(url, None, headers)
62 self.proxy = self.options.proxy
---> 63 return self.u2open(u2request)
64 except HTTPError as e:
65 raise TransportError(str(e), e.code, e.fp)
c:\program files\alteryx\bin\miniconda3\envs\jupytertool_venv\lib\site-packages\suds\transport\http.py in u2open(self, u2request)
117 return url.open(u2request)
118 else:
--> 119 return url.open(u2request, timeout=tm)
120
121 def u2opener(self):
c:\program files\alteryx\bin\miniconda3\envs\jupytertool_venv\lib\urllib\request.py in open(self, fullurl, data, timeout)
530 for processor in self.process_response.get(protocol, []):
531 meth = getattr(processor, meth_name)
--> 532 response = meth(req, response)
533
534 return response
c:\program files\alteryx\bin\miniconda3\envs\jupytertool_venv\lib\urllib\request.py in http_response(self, request, response)
640 if not (200 <= code < 300):
641 response = self.parent.error(
--> 642 'http', request, response, code, msg, hdrs)
643
644 return response
c:\program files\alteryx\bin\miniconda3\envs\jupytertool_venv\lib\urllib\request.py in error(self, proto, *args)
562 http_err = 0
563 args = (dict, proto, meth_name) + args
--> 564 result = self._call_chain(*args)
565 if result:
566 return result
c:\program files\alteryx\bin\miniconda3\envs\jupytertool_venv\lib\urllib\request.py in _call_chain(self, chain, kind, meth_name, *args)
502 for handler in handlers:
503 func = getattr(handler, meth_name)
--> 504 result = func(*args)
505 if result is not None:
506 return result
c:\program files\alteryx\bin\miniconda3\envs\jupytertool_venv\lib\site-packages\ntlm3\HTTPNtlmAuthHandler.py in http_error_401(self, req, fp, code, msg, headers)
133
134 def http_error_401(self, req, fp, code, msg, headers):
--> 135 return self.http_error_authentication_required('www-authenticate', req, fp, headers)
136
137
c:\program files\alteryx\bin\miniconda3\envs\jupytertool_venv\lib\site-packages\ntlm3\HTTPNtlmAuthHandler.py in http_error_authentication_required(self, auth_header_field, req, fp, headers)
38 if auth_header_value is not None and 'ntlm' in auth_header_value.lower():
39 fp.close()
---> 40 return self.retry_using_http_NTLM_auth(req, auth_header_field, None, headers)
41
42 def retry_using_http_NTLM_auth(self, req, auth_header_field, realm, headers):
c:\program files\alteryx\bin\miniconda3\envs\jupytertool_venv\lib\site-packages\ntlm3\HTTPNtlmAuthHandler.py in retry_using_http_NTLM_auth(self, req, auth_header_field, realm, headers)
100 # some Exchange servers send two WWW-Authenticate headers, one with the NTLM challenge
101 # and another with the 'Negotiate' keyword - make sure we operate on the right one
--> 102 m = re.match('(NTLM [A-Za-z0-9+\-/=]+)', auth_header_value)
103 if m:
104 auth_header_value, = m.groups()
c:\program files\alteryx\bin\miniconda3\envs\jupytertool_venv\lib\re.py in match(pattern, string, flags)
170 """Try to apply the pattern at the start of the string, returning
171 a match object, or None if no match was found."""
--> 172 return _compile(pattern, flags).match(string)
173
174 def fullmatch(pattern, string, flags=0):
TypeError: expected string or bytes-like object

TransportError while deleting elasticsearch index by Python script

I have installed elasticsearch2.1.1 in my windows machine and i have an elasticsearch index which is hosted in my machine locally as i am trying to understand it better. Name of the index is library. Below is how it looks like.
I am trying to delete the existing index using python library elasticsearch and below is the code to do so.
from elasticsearch import Elasticsearch
es = Elasticsearch('localhost:9200')
if es.indices.exists(index='library'):
es.delete('library')
When i execute this code, i end up getting below error.
---------------------------------------------------------------------------
TransportError Traceback (most recent call last)
<ipython-input-22-2a4b3642a164> in <module>()
1 from elasticsearch import Elasticsearch
2 es = Elasticsearch('localhost:9200')
----> 3 if es.indices.exists(index='library'):
4 es.delete('library')
c:\python27\lib\site-packages\elasticsearch\client\utils.pyc in _wrapped(*args, **kwargs)
71 if p in kwargs:
72 params[p] = kwargs.pop(p)
---> 73 return func(*args, params=params, **kwargs)
74 return _wrapped
75 return _wrapper
c:\python27\lib\site-packages\elasticsearch\client\indices.pyc in exists(self, index, params)
222 raise ValueError("Empty value passed for a required argument 'index'.")
223 return self.transport.perform_request('HEAD', _make_path(index),
--> 224 params=params)
225
226 #query_params('allow_no_indices', 'expand_wildcards', 'ignore_unavailable',
c:\python27\lib\site-packages\elasticsearch\transport.pyc in perform_request(self, method, url, params, body)
310
311 try:
--> 312 status, headers, data = connection.perform_request(method, url, params, body, ignore=ignore, timeout=timeout)
313
314 except TransportError as e:
c:\python27\lib\site-packages\elasticsearch\connection\http_urllib3.pyc in perform_request(self, method, url, params, body, timeout, ignore)
126 if not (200 <= response.status < 300) and response.status not in ignore:
127 self.log_request_fail(method, full_url, url, body, duration, response.status, raw_data)
--> 128 self._raise_error(response.status, raw_data)
129
130 self.log_request_success(method, full_url, url, body, response.status,
c:\python27\lib\site-packages\elasticsearch\connection\base.pyc in _raise_error(self, status_code, raw_data)
123 logger.warning('Undecodable raw error response from server: %s', err)
124
--> 125 raise HTTP_EXCEPTIONS.get(status_code, TransportError)(status_code, error_message, additional_info)
126
127
TransportError: TransportError(500, u'')
Edit: I tried as per suggestion by Slam and used below code
a = elasticsearch.client.IndicesClient('localhost:9200')
a.delete(index = 'library')
However, i am now getting a new error as follows
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-30-dc5154b36ad8> in <module>()
----> 1 a.delete(index = 'library')
c:\python27\lib\site-packages\elasticsearch\client\utils.pyc in _wrapped(*args, **kwargs)
71 if p in kwargs:
72 params[p] = kwargs.pop(p)
---> 73 return func(*args, params=params, **kwargs)
74 return _wrapped
75 return _wrapper
c:\python27\lib\site-packages\elasticsearch\client\indices.pyc in delete(self, index, params)
197 if index in SKIP_IN_PATH:
198 raise ValueError("Empty value passed for a required argument 'index'.")
--> 199 return self.transport.perform_request('DELETE', _make_path(index),
200 params=params)
201
c:\python27\lib\site-packages\elasticsearch\client\utils.pyc in transport(self)
82 #property
83 def transport(self):
---> 84 return self.client.transport
85
86 class AddonClient(NamespacedClient):
AttributeError: 'str' object has no attribute 'transport'
Elasticsearch.delete is made for deleting documents, not indexes.
To operate over idexes, you need IndicesClient.delete. Indices client is abstraction that works on top of basic ES client, with same transport. Invocation can be
>>> es = Elasticsearch('localhost:9200')
>>> es.indices.delete(index='test')
{'acknowledged': True}

gspread error: SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] in python

I have a few line of codes that used to work very well until today (using gspread). I get an certificate verification error whenever I run this code:
json_key = json.load(open('Sheetmodification_abc.json'))
scope = ['https://spreadsheets.google.com/feeds']
credentials = SignedJwtAssertionCredentials(json_key['client_email'], json_key['private_key'].encode(), scope)
gc = gspread.authorize(credentials)
wks = gc.open("googlespreadsheets").sheet1
What could be the reason for this and how do I fix it? I've been looking here for a solution: https://github.com/burnash/gspread/issues/223
But don't understand the solution offered.
Here's the traceback:
---------------------------------------------------------------------------
SSLError Traceback (most recent call last)
C:\Users\Nathan\App_Finder_2.0.1.py in <module>()
142 gc = gspread.authorize(credentials)
143
--> 144 wks = gc.open("googlespreadsheets").sheet1
145
146 # 1. Retrieve app name
C:\Users\Nathan\AppData\Local\Enthought\Canopy\User\lib\site-packages\gspread\client.pyc in open(self, title)
143
144 """
--> 145 feed = self.get_spreadsheets_feed()
146
147 for elem in feed.findall(_ns('entry')):
C:\Users\Nathan\AppData\Local\Enthought\Canopy\User\lib\site-packages\gspread\client.pyc in get_spreadsheets_feed(self, visibility, projection)
229 visibility=visibility, projection=projection)
230
--> 231 r = self.session.get(url)
232 return ElementTree.fromstring(r.content)
233
C:\Users\Nathan\AppData\Local\Enthought\Canopy\User\lib\site-packages\gspread\httpsession.pyc in get(self, url, **kwargs)
73
74 def get(self, url, **kwargs):
---> 75 return self.request('GET', url, **kwargs)
76
77 def delete(self, url, **kwargs):
C:\Users\Nathan\AppData\Local\Enthought\Canopy\User\lib\site-packages\gspread\httpsession.pyc in request(self, method, url, data, headers)
65 except AttributeError:
66 raise Exception("HTTP method '{}' is not supported".format(method))
---> 67 response = func(url, data=data, headers=request_headers)
68
69 if response.status_code > 399:
C:\Users\Nathan\AppData\Local\Enthought\Canopy\User\lib\site-packages\requests\api.pyc in get(url, params, **kwargs)
67
68 kwargs.setdefault('allow_redirects', True)
---> 69 return request('get', url, params=params, **kwargs)
70
71
C:\Users\Nathan\AppData\Local\Enthought\Canopy\User\lib\site-packages\requests\api.pyc in request(method, url, **kwargs)
48
49 session = sessions.Session()
---> 50 response = session.request(method=method, url=url, **kwargs)
51 # By explicitly closing the session, we avoid leaving sockets open which
52 # can trigger a ResourceWarning in some cases, and look like a memory leak
C:\Users\Nathan\AppData\Local\Enthought\Canopy\User\lib\site-packages\requests\sessions.pyc in request(self, method, url, params, data, headers, cookies, files, auth, timeout, allow_redirects, proxies, hooks, stream, verify, cert, json)
463 }
464 send_kwargs.update(settings)
--> 465 resp = self.send(prep, **send_kwargs)
466
467 return resp
C:\Users\Nathan\AppData\Local\Enthought\Canopy\User\lib\site-packages\requests\sessions.pyc in send(self, request, **kwargs)
571
572 # Send the request
--> 573 r = adapter.send(request, **kwargs)
574
575 # Total elapsed time of the request (approximately)
C:\Users\Nathan\AppData\Local\Enthought\Canopy\User\lib\site-packages\requests\adapters.pyc in send(self, request, stream, timeout, verify, cert, proxies)
429 except (_SSLError, _HTTPError) as e:
430 if isinstance(e, _SSLError):
--> 431 raise SSLError(e, request=request)
432 elif isinstance(e, ReadTimeoutError):
433 raise ReadTimeout(e, request=request)
SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:581)
First of all, I should mention that I am using Python 2.7 on Windows. I found that if I run a script very similar to yours without "Administrator Privileges" Python throws a SSLError exception (in my case, ssl.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:590)). Running the same exact script with "Administrator Privileges" (CMD, "Run as Administrator") doesn't raise any exception.
It is possible that this could be related to Windows Firewall.

gspread: SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] in python

I have a few line of codes that used to work very well until today (using gspread). I get an certificate verification error whenever I run this code:
json_key = json.load(open('Sheetmodification_abc.json'))
scope = ['https://spreadsheets.google.com/feeds']
credentials = SignedJwtAssertionCredentials(json_key['client_email'], json_key['private_key'].encode(), scope)
gc = gspread.authorize(credentials)
wks = gc.open("googlespreadsheets").sheet1
What could be the reason for this and how do I fix it? I've been looking here for a solution: https://github.com/burnash/gspread/issues/223
But don't understand the solution offered.
EDIT: Here's the traceback:
---------------------------------------------------------------------------
SSLError Traceback (most recent call last)
C:\Users\Nathan\App_Finder_2.0.1.py in <module>()
142 gc = gspread.authorize(credentials)
143
--> 144 wks = gc.open("googlespreadsheets").sheet1
145
146 # 1. Retrieve app name
C:\Users\Nathan\AppData\Local\Enthought\Canopy\User\lib\site-packages\gspread\client.pyc in open(self, title)
143
144 """
--> 145 feed = self.get_spreadsheets_feed()
146
147 for elem in feed.findall(_ns('entry')):
C:\Users\Nathan\AppData\Local\Enthought\Canopy\User\lib\site-packages\gspread\client.pyc in get_spreadsheets_feed(self, visibility, projection)
229 visibility=visibility, projection=projection)
230
--> 231 r = self.session.get(url)
232 return ElementTree.fromstring(r.content)
233
C:\Users\Nathan\AppData\Local\Enthought\Canopy\User\lib\site-packages\gspread\httpsession.pyc in get(self, url, **kwargs)
73
74 def get(self, url, **kwargs):
---> 75 return self.request('GET', url, **kwargs)
76
77 def delete(self, url, **kwargs):
C:\Users\Nathan\AppData\Local\Enthought\Canopy\User\lib\site-packages\gspread\httpsession.pyc in request(self, method, url, data, headers)
65 except AttributeError:
66 raise Exception("HTTP method '{}' is not supported".format(method))
---> 67 response = func(url, data=data, headers=request_headers)
68
69 if response.status_code > 399:
C:\Users\Nathan\AppData\Local\Enthought\Canopy\User\lib\site-packages\requests\api.pyc in get(url, params, **kwargs)
67
68 kwargs.setdefault('allow_redirects', True)
---> 69 return request('get', url, params=params, **kwargs)
70
71
C:\Users\Nathan\AppData\Local\Enthought\Canopy\User\lib\site-packages\requests\api.pyc in request(method, url, **kwargs)
48
49 session = sessions.Session()
---> 50 response = session.request(method=method, url=url, **kwargs)
51 # By explicitly closing the session, we avoid leaving sockets open which
52 # can trigger a ResourceWarning in some cases, and look like a memory leak
C:\Users\Nathan\AppData\Local\Enthought\Canopy\User\lib\site-packages\requests\sessions.pyc in request(self, method, url, params, data, headers, cookies, files, auth, timeout, allow_redirects, proxies, hooks, stream, verify, cert, json)
463 }
464 send_kwargs.update(settings)
--> 465 resp = self.send(prep, **send_kwargs)
466
467 return resp
C:\Users\Nathan\AppData\Local\Enthought\Canopy\User\lib\site-packages\requests\sessions.pyc in send(self, request, **kwargs)
571
572 # Send the request
--> 573 r = adapter.send(request, **kwargs)
574
575 # Total elapsed time of the request (approximately)
C:\Users\Nathan\AppData\Local\Enthought\Canopy\User\lib\site-packages\requests\adapters.pyc in send(self, request, stream, timeout, verify, cert, proxies)
429 except (_SSLError, _HTTPError) as e:
430 if isinstance(e, _SSLError):
--> 431 raise SSLError(e, request=request)
432 elif isinstance(e, ReadTimeoutError):
433 raise ReadTimeout(e, request=request)
SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:581)

When posting a photo, TypeError: 'unicode' does not have the buffer interface

I'm trying to use the tumblpy package to queue a photo. I recently changed from the Canopy python distro (on Windows, version 2.7.6 IIRC) to Anaconda (with Python 2.7.7), and this error never occurred.
When I run this:
import tumblpy
t = tumblpy.Tumblpy(hidden_key1, hidden_key2, hidden_key3, hidden_key4)
photo = open('C:/Users/David/Documents/Images_API/med_aerotransport.jpg', 'rb')
photo
output is:
<open file 'C:/Users/David/Documents/Images_API/med_aerotransport.jpg', mode 'rb' at 0x0000000006161270>
Now when I try to post the photo:
response = t.post('post',
blog_url='http://postersvintage.tumblr.com/',
params={'type':'photo',
'state':'queue',
'caption': 'Vintage Med Aerotransport poster',
'tags':'vintage, poster',
'data': photo})
Here's the entire error trace, leading to TypeError: 'unicode' does not have the buffer interface:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-32-c560435c7a77> in <module>()
5 'caption': 'Vintage Med Aerotransport poster',
6 'tags':'vintage, poster',
----> 7 'data': photo})
C:\Users\David\Anaconda\lib\site-packages\python_tumblpy-1.0.2-py2.7.egg\tumblpy\api.pyc in post(self, endpoint, blog_url, extra_endpoints, params)
170 def post(self, endpoint, blog_url=None, extra_endpoints=None, params=None):
171 return self.request(endpoint, method='POST', blog_url=blog_url,
--> 172 extra_endpoints=extra_endpoints, params=params)
173
174 def get_avatar_url(self, blog_url, size=64):
C:\Users\David\Anaconda\lib\site-packages\python_tumblpy-1.0.2-py2.7.egg\tumblpy\api.pyc in request(self, endpoint, method, blog_url, extra_endpoints, params)
124 if files:
125 kwargs['params'] = params
--> 126 response = func(url, **kwargs)
127 except requests.exceptions.RequestException:
128 raise TumblpyError('An unknown error occurred.')
C:\Users\David\Anaconda\lib\site-packages\requests-1.2.2-py2.7.egg\requests\sessions.pyc in post(self, url, data, **kwargs)
375 """
376
--> 377 return self.request('POST', url, data=data, **kwargs)
378
379 def put(self, url, data=None, **kwargs):
C:\Users\David\Anaconda\lib\site-packages\requests-1.2.2-py2.7.egg\requests\sessions.pyc in request(self, method, url, params, data, headers, cookies, files, auth, timeout, allow_redirects, proxies, hooks, stream, verify, cert)
322
323 # Prepare the Request.
--> 324 prep = req.prepare()
325
326 # Send the request.
C:\Users\David\Anaconda\lib\site-packages\requests-1.2.2-py2.7.egg\requests\models.pyc in prepare(self)
223 p.prepare_headers(self.headers)
224 p.prepare_cookies(self.cookies)
--> 225 p.prepare_body(self.data, self.files)
226 p.prepare_auth(self.auth, self.url)
227 # Note that prepare_auth must be last to enable authentication schemes
C:\Users\David\Anaconda\lib\site-packages\requests-1.2.2-py2.7.egg\requests\models.pyc in prepare_body(self, data, files)
383 # Multi-part file uploads.
384 if files:
--> 385 (body, content_type) = self._encode_files(files, data)
386 else:
387 if data:
C:\Users\David\Anaconda\lib\site-packages\requests-1.2.2-py2.7.egg\requests\models.pyc in _encode_files(files, data)
131 new_fields.append((k, new_v))
132
--> 133 body, content_type = encode_multipart_formdata(new_fields)
134
135 return body, content_type
C:\Users\David\Anaconda\lib\site-packages\requests-1.2.2-py2.7.egg\requests\packages\urllib3\filepost.pyc in encode_multipart_formdata(fields, boundary)
75 'filename="%s"\r\n' % (fieldname, filename))
76 body.write(b('Content-Type: %s\r\n\r\n' %
---> 77 (content_type,)))
78 else:
79 data = value
TypeError: 'unicode' does not have the buffer interface
Issue solved by updating requests, as suggested by Martijn Pieters.

Categories

Resources