Giter VIP home page Giter VIP logo

google-api-python-client's Introduction

Google API Client

PyPI version

This is the Google API Python client library for Google's discovery based APIs. To get started, please see the docs folder.

This library is considered complete and is in maintenance mode. This means that we will address critical bugs and security issues but will not add any new features.

This library is officially supported by Google. However, the maintainers of this repository recommend using Cloud Client Libraries for Python, where possible, for new code development. For more information, please visit Client Libraries Explained.

Version 2.0 Release

The 2.0 release of google-api-python-client includes a substantial reliability improvement, compared with 1.x, as discovery documents are now cached in the library rather than fetched dynamically. It is highly recommended to upgrade from v1.x to v2.x.

Only python 3.7 and newer is supported. If you are not able to upgrade python, then please continue to use version 1.x as we will continue supporting python 2.7+ in v1.

Discovery documents will no longer be retrieved dynamically when you call discovery.build(). The discovery documents will instead be retrieved from the client library directly. New versions of this library are released weekly. As a result of caching the discovery documents, the size of this package is at least 50 MB larger compared to the previous version.

Please see the Migration Guide for more information.

Documentation

See the docs folder for more detailed instructions and additional documentation.

Other Google API libraries

The maintainers of this repository recommend using Cloud Client Libraries for Python, where possible, for new code development due to the following reasons:

With Cloud Client Libraries for Python:

  • There is a separate client library for each API, so you can choose which client libraries to download. Whereas, google-api-python-client is a single client library for all APIs. As a result, the total package size for google-api-python-client exceeds 50MB.
  • There are stricter controls for breaking changes to the underlying APIs as each client library is focused on a specific API.
  • There are more features in these Cloud Client Libraries as each library is focused on a specific API, and in some cases, the libraries are owned by team who specialized in that API.
  • Developers will benefit from intellisense.

For more information, please visit Client Libraries Explained.

Although there are many benefits to moving to Cloud Client Libraries for Python, the maintainers want to emphasize that google-api-python-client will continue to be supported.

For Google Ads API, we recommend using Google Ads API Client Library for Python.

For Google Firebase Admin API, we recommend using Firebase Admin Python SDK.

Installation

Install this library in a virtualenv using pip. virtualenv is a tool to create isolated Python environments. The basic problem it addresses is one of dependencies and versions, and indirectly permissions.

With virtualenv, it's possible to install this library without needing system install permissions, and without clashing with the installed system dependencies.

Mac/Linux

pip3 install virtualenv
virtualenv <your-env>
source <your-env>/bin/activate
<your-env>/bin/pip install google-api-python-client

Windows

pip install virtualenv
virtualenv <your-env>
<your-env>\Scripts\activate
<your-env>\Scripts\pip.exe install google-api-python-client

Supported Python Versions

Python 3.7, 3.8, 3.9, 3.10, 3.11 and 3.12 are fully supported and tested. This library may work on later versions of 3, but we do not currently run tests against those versions.

Unsupported Python Versions

Python < 3.7

Third Party Libraries and Dependencies

The following libraries will be installed when you install the client library:

For development you will also need the following libraries:

Contributing

Please see our Contribution Guide. In particular, we love pull requests - but please make sure to sign the contributor license agreement.

google-api-python-client's People

Contributors

aliafshar avatar arithmetic1728 avatar busunkim96 avatar craigcitro avatar danoscarmike avatar dfrenkel avatar dhermes avatar eljobe avatar gcf-owl-bot[bot] avatar helen-fornazier avatar jcgregorio avatar josealcerreca avatar mcdonc avatar methane avatar mmattioli avatar msaniscalchi avatar nathanielmanistaatgoogle avatar ohmayr avatar parkayun avatar parthea avatar pferate avatar proppy avatar release-please[bot] avatar renovate-bot avatar saicheems avatar skelterjohn avatar theacodes avatar tommiller avatar yoshi-automation avatar yoshi-code-bot avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

google-api-python-client's Issues

How do I create Signed URLs for uploading files from browser directly?

I am aware that we can use use the p12 keys to create a der file and use it with SHA256, RSA and PKCS1_v1_5 to create a Singed URL. I am doing this at the moment. I was wondering is there any way to generate a signed url without a p12/der file [Something like oauth-only approach]?

OAuth Token does not validate with unicode state variable

Hi guys,

I had a problem to validate the oauth2 token with xsrfutil.validate_token.
Indeed, I switched to Django 1.7 which gives a unicode object when getting the state parameter of the oauth callback URL.

The initial state variable passed to Google is built as following:

flow.flow.params['state'] = xsrfutil.generate_token(google_app.secret,
                                                    request.user, 
                                                    action_id=GOOGLE_API_ACCESS_ACTION_ID)
...
return HttpResponseRedirect(flow.flow.step1_get_authorize_url())

Then I try to validate the token using xsrfutil.validate_token in my oauth return view as follows:

if not xsrfutil.validate_token(google_app.secret,
                               state,
                               request.user,
                               action_id=AUTHORIZE_GOOGLE_API_ACCESS_ACTION_ID):
            return HttpResponseBadRequest('Your Google API token could not be validated.')

with:

state = request.REQUEST['state']

However, I had to use

state = str(request.REQUEST['state'])

so the token validates.

This is due to the fact Django 1.7 returns a unicode object for the state variable above using request.REQUEST. I was previously using Django 1.6 which used to return a string.

I believe this is somehow related to the api's Python 3 migration enhancement, which is not available yet. It would be nice to update the api documentation and django samples to reflect this issue.

webmaster tools access via API with service account

Is access to webmaster tools supported via this API client using a Service Account?

I am receiving and Empty Set (ie - "{}") when running the following code:

webmasters_service.sites().list().execute()

Requests lock up when multiple are done in concurrent threads

When using the API in a concurrent threaded environment (Flask with threaded=True), requests lock up when multiple are made at the same time. I'm not sure why this happens, but when enabling full logging with httplib2, I see the connect and send, but no reply.

Does this client use a shared connection pool of any sort that could cause this?

comments extraction

How can I use this API to extract the comments from a particular app from google play store ?

Uploading a huge file overflow error

I get an overflowerror when uploading a very large file.
full stack (i'm using raspberry pi which is 32 bit OS and the file is over 4 gig and python 2.7):

Traceback (most recent call last):
  File "./drive_upload.py", line 33, in <module>
    backupFile.Upload()
  File "/usr/local/lib/python2.7/dist-packages/pydrive/files.py", line 225, in Upload
    self._FilesInsert(param=param)
  File "/usr/local/lib/python2.7/dist-packages/pydrive/auth.py", line 54, in _decorated
    return decoratee(self, *args, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/pydrive/files.py", line 241, in _FilesInsert
    metadata = self.auth.service.files().insert(**param).execute()
  File "/usr/local/lib/python2.7/dist-packages/googleapiclient/discovery.py", line 750, in method
    payload = media_upload.getbytes(0, media_upload.size())
  File "/usr/local/lib/python2.7/dist-packages/googleapiclient/http.py", line 357, in getbytes
    return self._fd.read(length)
OverflowError: Python int too large to convert to C long

Bug in http.MediaIoBaseDownload

Problem is here. If content-range is not found in response. This will leads to infinite loop because self._total_size will always be None and self._progress == self._total_size will always results in False hence self._done will never be True. Shouldn't it raise an exception if content-range header is not found?

cannot import name urllib

I updated my system from trusty to utopic and started getting this error not sure which version of what changed. I don't have time to dig in to it right now, but I wanted to make sure people are aware of it.

I went ahead and did what I needed by working with a trusty image.

[steve]sheila@yagi: ar14 ยป ./youtube.py                ~/dev/pyvideo/conferences/ar14  
Traceback (most recent call last):
  File "./youtube.py", line 10, in <module>
    from apiclient.discovery import build
  File "/home/sheila/dev/pyvideo/google-api-python-client/apiclient/__init__.py", line 16, in <module>
    from googleapiclient import channel
  File "/home/sheila/dev/pyvideo/google-api-python-client/googleapiclient/channel.py", line 62, in <module>
    from googleapiclient import errors
  File "/home/sheila/dev/pyvideo/google-api-python-client/googleapiclient/errors.py", line 27, in <module>
    from oauth2client import util
  File "/home/sheila/.virtualenvs/steve/local/lib/python2.7/site-packages/oauth2client/util.py", line 38, in <module>
    from six.moves import urllib
ImportError: cannot import name urllib

large file download fails with OverflowError

On my 32-bit linux machine, files over 2GB fail to download. Memory usage gets very high while running the test script below, suggesting the entire download is being cached in memory. I think the download should be streamed to disk instead.

To use the script, upload a large file called bigvid.avi to google drive and put client_secrets.json in the working directory.

This script uses PyDrive so I originally raised this issue at googlearchive/PyDrive#30 but aliafshar commented that the bug lies in google-api-python-client.

$ ./test.py 
bigvid.avi
Traceback (most recent call last):
  File "./test.py", line 16, in <module>
    f.GetContentFile('/tmp/bigvid-from-pydrive.avi')
  File "/usr/local/lib/python2.7/dist-packages/pydrive/files.py", line 167, in GetContentFile
    self.FetchContent(mimetype)
  File "/usr/local/lib/python2.7/dist-packages/pydrive/files.py", line 36, in _decorated
    return decoratee(self, *args, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/pydrive/files.py", line 198, in FetchContent
    self.content = io.BytesIO(self._DownloadFromUrl(download_url))
  File "/usr/local/lib/python2.7/dist-packages/pydrive/auth.py", line 54, in _decorated
    return decoratee(self, *args, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/pydrive/files.py", line 313, in _DownloadFromUrl
    resp, content = self.auth.service._http.request(url)
  File "/usr/local/lib/python2.7/dist-packages/oauth2client/util.py", line 135, in positional_wrapper
    return wrapped(*args, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/oauth2client/client.py", line 547, in new_request
    redirections, connection_type)
  File "/usr/local/lib/python2.7/dist-packages/httplib2/__init__.py", line 1593, in request
    (response, content) = self._request(conn, authority, uri, request_uri, method, body, headers, redirections, cachekey)
  File "/usr/local/lib/python2.7/dist-packages/httplib2/__init__.py", line 1335, in _request
    (response, content) = self._conn_request(conn, request_uri, method, body, headers)
  File "/usr/local/lib/python2.7/dist-packages/httplib2/__init__.py", line 1318, in _conn_request
    content = response.read()
  File "/usr/lib/python2.7/httplib.py", line 541, in read
    return self._read_chunked(amt)
  File "/usr/lib/python2.7/httplib.py", line 624, in _read_chunked
    return ''.join(value)
OverflowError: join() result is too long for a Python string
$ cat test.py
#!/usr/bin/env python

from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive

gauth=GoogleAuth()
if not gauth.LoadCredentialsFile("auth.txt") :
    gauth.CommandLineAuth()
    gauth.SaveCredentialsFile("auth.txt")

drive=GoogleDrive(gauth)

filelist=drive.ListFile({'q': "title='bigvid.avi'"}).GetList()
for f in filelist:
    print f['title'];
    f.GetContentFile('/tmp/bigvid-from-pydrive.avi')

$ ls -l /tmp/big*
ls: cannot access /tmp/big*: No such file or directory

Switch from "uritemplate" to "uritemplate.py"

There are at least 2 URI template packages on the PyPI: uritemplate and uritemplate.py. Both of these packages use uritemplate as the package name to be imported, which causes a conflict when both are installed (see python-hyper/uritemplate#14).

I propose that this project depend on uritemplate.py because:

  • uritemplate.py is API-compatible with uritemplate, but the reverse is not true. I have confirmed that this library works with uritemplate.py.
  • Other projects depend on uritemplate.py. For example, we are currently working on a project that depends on both github3.py (GitHub API client) and google-api-python-client. Installing both results in an immediate ImportError due to the uritemplate conflict.

This is a simple, low-risk change that would aid compatibility with other projects.

Thoughts?

Deprecate https://code.google.com/p/google-api-python-client/ MOAR

  1. When Googling for google-api-python-client the old project comes up before this one.
  2. The massive amount of text on the front page makes the project still look active. Suggest nuking all text including and after

    All following text is deprecated and left in only for historical purposes.

  3. Remove the massive number of project members, downloads and Wiki.

If I am off-base, feel free to close this issue.

Humble Suggestion

First of all, thank you for this library.
I however have an idea on how to make it much better though. If it had documentation like, for example, GAE (a comprehensive tutorial), that would make it much more usable, maybe even increase Google revenue by 0.0001%

BadStatusLine: '' exception during requests to Google Analytics API

When making requests to the Google Analytics API, we see frequent BadStatusLine: '' exceptions. Here's a full traceback:

 ...
    data = service.data().ga().get(*args, **kwargs).execute(num_retries=3)
  File "/Users/jessepollak/.virtualenvs/clef/lib/python2.7/site-packages/oauth2client/util.py", line 129, in positional_wrapper
    return wrapped(*args, **kwargs)
  File "/Users/jessepollak/.virtualenvs/clef/lib/python2.7/site-packages/googleapiclient/http.py", line 716, in execute
    body=self.body, headers=self.headers)
  File "/Users/jessepollak/.virtualenvs/clef/lib/python2.7/site-packages/oauth2client/util.py", line 129, in positional_wrapper
    return wrapped(*args, **kwargs)
  File "/Users/jessepollak/.virtualenvs/clef/lib/python2.7/site-packages/oauth2client/client.py", line 533, in new_request
    redirections, connection_type)
  File "/Users/jessepollak/.virtualenvs/clef/lib/python2.7/site-packages/httplib2/__init__.py", line 1570, in request
    (response, content) = self._request(conn, authority, uri, request_uri, method, body, headers, redirections, cachekey)
  File "/Users/jessepollak/.virtualenvs/clef/lib/python2.7/site-packages/httplib2/__init__.py", line 1317, in _request
    (response, content) = self._conn_request(conn, request_uri, method, body, headers)
  File "/Users/jessepollak/.virtualenvs/clef/lib/python2.7/site-packages/httplib2/__init__.py", line 1286, in _conn_request
    response = conn.getresponse()
  File "/usr/local/Cellar/python/2.7.6_1/Frameworks/Python.framework/Versions/2.7/lib/python2.7/httplib.py", line 1045, in getresponse
    response.begin()
  File "/usr/local/Cellar/python/2.7.6_1/Frameworks/Python.framework/Versions/2.7/lib/python2.7/httplib.py", line 409, in begin
    version, status, reason = self._read_status()
  File "/usr/local/Cellar/python/2.7.6_1/Frameworks/Python.framework/Versions/2.7/lib/python2.7/httplib.py", line 373, in _read_status
    raise BadStatusLine(line)
BadStatusLine: ''

Is asynchronous requests possible?

Is it possible to send asynchronous requests using this client library? I have few modules in app engine and I can run URL Fetch asynchronously to pull data from these modules concurrently, but there is an endpoint project and I'm not sure how to use this client library to run it asynchronously. Do I have to use some other mechanism or roll my own?

include python-gflags as dependency

Not sure if this should go here or under oauth2client: When doing pip install google-api-python-client, it installs a couple of dependencies but not python-gflags. The error message when running some google analytics api query is: No module named gflags.

Need up-to-date instructions for google-api-python-client on AppEngine.

Couple things I noticed in getting google-api-python-client to work on my AppEngine app,

  1. https://developers.google.com/api-client-library/python/start/installation#appengine references a version of google-api-python-client that is old and uses the googlecode version of the code.
  2. There are no updated instruction related to appengine on the github site.
  3. The appengine demo in this repo doesn't immediately work.
  4. It would be nice to have info about a process similar to http://blog.jonparrott.com/managing-vendored-packages-on-app-engine/ or a link to that post. But a duplication might be worthwhile.

Question: gmail scope with step1_get_device_and_user_codes

Hi,

It looks like we cannot use OAuth2WebServerFlow.step1_get_device_and_user_codes() with gmail service
It always return :
"OAuth2DeviceCodeError: Invalid response 400. Error: invalid_scope"
although I set different scope such as
'https://www.googleapis.com/auth/gmail.modify'
'https://www.googleapis.com/auth/gmail.compose'
'https://www.googleapis.com/auth/gmail.readonly'
'https://mail.google.com/'

oauth2_for_devices.py sample (https://github.com/google/oauth2client/blob/master/samples/oauth2_for_devices.py) works fine for 'youtube' or 'calendar' service, but not for gmail.
Did I miss something?

Thanks in advance for your feedback,
fcaza

Proxy doesn't work

When I try to execute this:
`
credentials = client.SignedJwtAssertionCredentials(
SERVICE_ACCOUNT_EMAIL,
key,
scope='https://www.googleapis.com/auth/androidpublisher')
httplib2.debuglevel=4
myproxy = httplib2.ProxyInfo(proxy_type = httplib2.socks.PROXY_TYPE_HTTP, proxy_host='http://proxy.my.comp', proxy_port=8080)
myhttp = httplib2.Http(proxy_info=myproxy)
authorization = credentials.authorize(myhttp)

service = build('androidpublisher', 'v2', http=authorization)
`
I get this error:
httplib2.ServerNotFoundError: Unable to find the server at accounts.google.com

I also tried to set the proxy as env-variables. For basic stuff like installing via pip it works fine, but it doesn't work with the client. But I assume it should use the environment variables if nothing is set as proxy_info in the code.
Any suggestions on this?

Thanks!

BigQuery Client Api Library - Load operations raises Not Found Error when the table already exists in the dataset

For security reasons I can't publish specific additional informations, but I will try to detail as much as I can.

I have these tables on 'Sandbox' dataset:

  • Sandbox.test4
  • Sandbox.test5
a = bqLoader.loadAssync("/home/wesley/k/codes_return20150320.csv", "Sandbox", "test3", "/home/wesley/Desktop/loadFileTestSchema.json", )
print a
b = bqLoader.loadAssync("/home/wesley/k/codes_return20150321.csv", "Sandbox", "test4", "/home/wesley/Desktop/loadFileTestSchema.json", )
print b
c = bqLoader.loadAssync("/home/wesley/k/codes_return20150322.csv", "Sandbox", "test5", "/home/wesley/Desktop/loadFileTestSchema.json", )
print c

the above code's output:

<googleapiclient.http.MediaFileUpload object at 0x7f9580e94850>
job_xxxxxxxxC2WY6SlEFTrtaxxxxx

Traceback (most recent call last):
  File "/home/wesley/github/BI/helpers/BigQuery/BigQueryLoad.py", line 130, in <module>
    b = bqLoader.loadAssync("/home/wesley/k/codes_return20150321.csv", "Sandbox", "test4", "/home/wesley/Desktop/loadFileTestSchema.json", )
  File "/home/wesley/github/BI/helpers/BigQuery/BigQueryLoad.py", line 122, in loadAssync
    jobId = self._jobsInsert(jobData, upload)["jobReference"]["jobId"]
  File "/home/wesley/github/BI/helpers/BigQuery/BaseClass.py", line 107, in _jobsInsert
    raise e
googleapiclient.errors.HttpError: <HttpError 404 when requesting https://www.googleapis.com/upload/bigquery/v2/projects/PROJECT_ID/jobs?uploadType=multipart&alt=json returned "Not Found: Job PROJECT_ID:JOB_ID">

Please get rid of the stale googleapiclient 1.2 from Pypi

https://pypi.python.org/pypi?%3Aaction=search&term=google+api+client&submit=search
image

From what I can tell, that 1.2 library is an old version of this library somehow submitted under a different name. The main problem is that they are both endorsed by Google in the details and confused the hell out of me originally.

Please just take the other library out of Pypi completely, everyone should be relying on the google-api-python-client library instead.

Hardcoded /usr/bin/python2.4

Two files have hardcoded references to /usr/bin/python2.4.
googleapiclient/errors.py and model.py
They can probably do without an interpreter line, but if one stays, it shouldn't have a python version number inside.

Can't upload into beta track with higher versionCode than alpha

When Uploading a new APK into beta track via the Publisher API, I get a 403 error, if there still is an APK in the alpa track, that has a lower android:versionCode.

In my example I have an APK with version Code 49 in alpha. I modified my project, built a new APK and want to publish it as beta. Therefor I updated the versionCode to 50.

I can upload the APK 50 into the API edit, but as soon as I try and commit the changed, I receive the following error:

<HttpError 403 when requesting https://www.googleapis.com/androidpublisher/v2/applications/[__bundleIdentifier__]/edits/474013840124732894710324789:commit?alt=json returned "Version 49 of this app can not be downloaded by any devices as they will all receive APKs with higher version codes.">

If I publish the APK 49 to beta first, then I can overwrite it with the 50 successfully.

I wonder, if the observed behavior is by design? If so, I would argue, that it might not be close to practice:

  1. I wouldn't expect any APK to move from alpha to beta without any changes and thus an update in the versionCode
  2. I would expect, that after leaving alpha base, some beta versions might follow, while not working on the alpha currently.
  3. In the developer console, within the list of testers, it is mentioned, that an alpha tester will receive a beta APK, if no alpha APK is available. So updating the version code and changing the track to the beta seemed like a reasonable step.

SSL3_GET_RECORD:wrong version number exception during requests to Google Analytics API

When using the client to make requests to the Google Analytics, API, we see the following exception occasionally. It can usually be solved by making retrying the request.

...
    data = service.data().ga().get(*args, **kwargs).execute(num_retries=3)
  File "/Users/jessepollak/.virtualenvs/clef/lib/python2.7/site-packages/oauth2client/util.py", line 129, in positional_wrapper
    return wrapped(*args, **kwargs)
  File "/Users/jessepollak/.virtualenvs/clef/lib/python2.7/site-packages/googleapiclient/http.py", line 716, in execute
    body=self.body, headers=self.headers)
  File "/Users/jessepollak/.virtualenvs/clef/lib/python2.7/site-packages/oauth2client/util.py", line 129, in positional_wrapper
    return wrapped(*args, **kwargs)
  File "/Users/jessepollak/.virtualenvs/clef/lib/python2.7/site-packages/oauth2client/client.py", line 533, in new_request
    redirections, connection_type)
  File "/Users/jessepollak/.virtualenvs/clef/lib/python2.7/site-packages/httplib2/__init__.py", line 1570, in request
    (response, content) = self._request(conn, authority, uri, request_uri, method, body, headers, redirections, cachekey)
  File "/Users/jessepollak/.virtualenvs/clef/lib/python2.7/site-packages/httplib2/__init__.py", line 1317, in _request
    (response, content) = self._conn_request(conn, request_uri, method, body, headers)
  File "/Users/jessepollak/.virtualenvs/clef/lib/python2.7/site-packages/httplib2/__init__.py", line 1286, in _conn_request
    response = conn.getresponse()
  File "/usr/local/Cellar/python/2.7.6_1/Frameworks/Python.framework/Versions/2.7/lib/python2.7/httplib.py", line 1045, in getresponse
    response.begin()
  File "/usr/local/Cellar/python/2.7.6_1/Frameworks/Python.framework/Versions/2.7/lib/python2.7/httplib.py", line 409, in begin
    version, status, reason = self._read_status()
  File "/usr/local/Cellar/python/2.7.6_1/Frameworks/Python.framework/Versions/2.7/lib/python2.7/httplib.py", line 365, in _read_status
    line = self.fp.readline(_MAXLINE + 1)
  File "/usr/local/Cellar/python/2.7.6_1/Frameworks/Python.framework/Versions/2.7/lib/python2.7/socket.py", line 476, in readline
    data = self._sock.recv(self._rbufsize)
  File "/usr/local/Cellar/python/2.7.6_1/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ssl.py", line 241, in recv
    return self.read(buflen)
  File "/usr/local/Cellar/python/2.7.6_1/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ssl.py", line 160, in read
    return self._sslobj.read(len)
SSLError: [Errno 1] _ssl.c:1426: error:1408F10B:SSL routines:SSL3_GET_RECORD:wrong version number

Python3 - tools.ClientRedirectHandler.do_GET needs to write bytes, not strings

When Authentication Flow completes, an attempt to alert the user in the browser is made. Using google-api-python-client-py3, an exception is thrown:

Traceback (most recent call last):
File "C:\Python33\Lib\socketserver.py", line 306, in _handle_request_noblock
self.process_request(request, client_address)
File "C:\Python33\Lib\socketserver.py", line 332, in process_request
self.finish_request(request, client_address)
File "C:\Python33\Lib\socketserver.py", line 345, in finish_request
self.RequestHandlerClass(request, client_address, self)
File "C:\Python33\Lib\socketserver.py", line 666, in init
self.handle()
File "C:\Python33\Lib\http\server.py", line 400, in handle
self.handle_one_request()
File "C:\Python33\Lib\http\server.py", line 388, in handle_one_request
method()
File "C:\python_projects\pdns\lib\site-packages\oauth2client\tools.py", line 100, in do_GET
s.wfile.write("<title>Authentication Status</title>")
File "C:\Python33\Lib\socket.py", line 317, in write
return self._sock.send(b)
TypeError: 'str' does not support the buffer interface

Fixed by changing the following lines in tools.ClientRedirectHandler.do_GET():
s.wfile.write(bytes("<html><head><title>Authentication Status</title></head>", "UTF-8")) s.wfile.write(bytes("<body><p>The authentication flow has completed.</p>", "UTF-8")) s.wfile.write(bytes("</body></html>", "UTF-8"))

Update "Sending e-mail" docs to work with Python 3

The documentation for sending e-mails doesn't seem to work when using Python 3. Also, I can't seem to get e-mail sending working with Python 3 when sending binary (PDF) attachments. The code I'm using worked with Python 2. Details are below.

The Gmail REST API documentation for sending e-mail says to do the following:

raw = base64.urlsafe_b64encode(mime.as_string())
body = {'raw': raw}
messages = service.users().messages()
message = messages.send(userId='me', body=body).execute()

However, this code results in the following error:

File "/Users/chris/dev/.virtualenvs/my_package/lib/python3.4/base64.py", line 121, in urlsafe_b64encode
  return b64encode(s).translate(_urlsafe_encode_translation)
File "/Users/chris/dev/.virtualenvs/my_package/lib/python3.4/base64.py", line 62, in b64encode
  encoded = binascii.b2a_base64(s)[:-1]
TypeError: 'str' does not support the buffer interface

Changing as_string() in the above to as_bytes():

raw = base64.urlsafe_b64encode(mime.as_bytes())
body = {'raw': raw}
messages = service.users().messages()
message = messages.send(userId='me', body=body).execute()

results in the following error:

File "/Users/chris/dev/.virtualenvs/my_package/lib/python3.4/site-packages/googleapiclient/discovery.py", line 691, in method
  actual_path_params, actual_query_params, body_value)
File "/Users/chris/dev/.virtualenvs/my_package/lib/python3.4/site-packages/googleapiclient/model.py", line 149, in request
  body_value = self.serialize(body_value)
File "/Users/chris/dev/.virtualenvs/my_package/lib/python3.4/site-packages/googleapiclient/model.py", line 258, in serialize
  return json.dumps(body_value)
File "/opt/local/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/json/__init__.py", line 230, in dumps
  return _default_encoder.encode(obj)
File "/opt/local/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/json/encoder.py", line 192, in encode
  chunks = self.iterencode(o, _one_shot=True)
File "/opt/local/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/json/encoder.py", line 250, in iterencode
  return _iterencode(o, 0)
File "/opt/local/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/json/encoder.py", line 173, in default
  raise TypeError(repr(o) + " is not JSON serializable")
TypeError: b'Q29ud...TY9PS0tCg==' is not JSON serializable

If I add raw = raw.decode() to ensure that raw is a string in Python 3 as opposed to bytes, then the e-mail does get sent. However, the PDF attachment now seems to be corrupted:

raw = base64.urlsafe_b64encode(mime.as_bytes())
raw = raw.decode()
body = {'raw': raw}
messages = service.users().messages()
message = messages.send(userId='me', body=body).execute()

HEAD requests returns 503

This fails with status 503:

response, content = service._http.request(download_url, method='HEAD')

While this works:

response, content = service._http.request(download_url)

Is it not possible to perform HEAD request for files whose downloadUrl is available in meta?

Please release new version

The one in pypi tries to import oauth2client.anyjson

from oauth2client.anyjson import simplejson

but the newest version of oauth2client doesn't have anyjson anymore.

The current master branch has this fixed.

Documentation release process is broken

Now that Python 3 support is (nearly) done, might I suggest that the next step would be updating the documentation regarding this project?

I've been struggling to get even a simple application up and running using this API, simply due to the lack of up-to-date, available documentation.

The documentation available at developers.google.com is not at all updated, and still advertises the use of apiclient instead of googleapiclient.

Furthermore, only cryptic, automatically-generated documentation is available at google.github.io.

I think it would be absolutely fantastic, if the documentation was improve, allowing developers to get into using this library more easily. I would love to help in any way I can, but sadly, I'm having a hard time gettings my bearings.

Help with SSLError: [Errno 185090050]

Need help resolving error below. My key and cx work in another Goole sample at the very bottom, but not with google-api-python-client.

Thanks in advance.

Python 2.7.6 Mac OSX 10.10.2
Enabled Content API for Shopping.

Source:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2014 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#           http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Simple command-line example for Custom Search.
Command-line application that does a search.
"""

__author__ = '[email protected] (Joe Gregorio)'

import pprint

from discovery import build

def main():
    # Build a service object for interacting with the API. Visit
    # the Google APIs Console <http://code.google.com/apis/console>
    # to get an API key for your own application.
    service = build("customsearch", "v1",
        developerKey="<my Dev key>")
    res = service.cse().list(
            q='lectures',
            cx='<my cx>',
        ).execute()

    pprint.pprint(res)

if __name__ == '__main__':
    main()

========== Last 2 lines of Traceback ==========================

File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ssl.py", line 141, in init
ciphers)
ssl.SSLError: [Errno 185090050] _ssl.c:343: error:0B084002:x509 certificate routines:X509_load_cert_crl_file:system lib

================== Another demo program that does work =====================

import urllib2
import simplejson
url = ('https://ajax.googleapis.com/ajax/services/search/images?' +
       'v=1.0&q="ANd9GcThbeJBfVq0WNfRTiPCO4fbjFDvlatP9aMA7r6NzGMTXIv0qMCA8z8i-8yZ"&exactTerms="plus"&fileType="image"&relatedSite="amazon.com"&&userip=<my developer key>')

request = urllib2.Request(url, None, {'Referer': "https://www.google.com/cse/publicurl?cx=<my cx>"})
response = urllib2.urlopen(request)

# Process the JSON string.
results = simplejson.load(response)
print results

Batch execution problem in Python3?

def getThreads(email, userId):

    threadList = []

    def threadCallback(request_id, response, exception):
        if exception is not None:
            raise APIError("Error occurred during thread callback")
        threadList.append(response)

    batch = BatchHttpRequest()

    try:
        credential = EmailAddress.objects.get(email=email, user=userId).credential
        gmail_client = getGmailClient(credential)
        threads = gmail_client.users().threads().list(userId='me', maxResults=10, q="", labelIds=['INBOX']).execute()
    except ObjectDoesNotExist:
        logger.error(Template("Error retrieving credential for email: $email, user: $user").safe_substitute(email=email, user=userId))
        raise ObjectDoesNotExist
    except errors.HttpError as e:
        # Returned for invalid requests, e.g. maxResults=0
        logger.error(Template("Gmail API: An error occurred: $e").safe_substitute(e=e))
        raise APIError("Gmail API: HttpError")

    if 'threads' in threads:
        for thread in threads['threads']:
            # TODO: Cache threads on 'id' field
            batch.add(gmail_client.users().threads().get(userId='me', id=thread['id'], format='metadata', metadataHeaders=['subject','date','to','from']), callback=threadCallback)
        batch.execute()

    return threadList

This code runs fine in Python2.7, but in Python3.3 the batch.execute() line throws an error:

Error: Can't convert 'bytes' object to str implicitly
Location: python3.3/site-packages/googleapiclient/http.py in _execute, line 1260

This is using google-api-python-client==1.4.0.

Any ideas what's going on? Again the first non-batch call is working fine, it's only the batch call that's throwing an error.

UnicodeDecodeError in discovery.createNextMethod()

The request.uri string might be converted to unicode (because of concatenation).

There is a failsafe in models.BaseModel._build_query() but not in discovery.createNextMethod(), so when calling search.list with q="pasiรณn", the call to search.list_next raises a UnicodeDecodeError.

Suggested fix:
in googleapiclient/discovery.py:842

pageToken = previous_response['nextPageToken']
try:
    uri = request.uri.encode('utf-8')
except UnicodeDecodeError:
    uri = request.uri
parsed = list(urlparse.urlparse(uri))
q = parse_qsl(parsed[4])

SSLError: EOF occurred in violation of protocol

I am using google-api-python-client_v1.2 on python 2.7.3. Often I see the following error while trying to build a drive service object. This is the stack trace:

drive_service = build('drive', 'v2', http=http)
File "/local/lib/python2.7/site-packages/google_api_python_client-1.2-py2.7.egg/oauth2client/util.py", line 132, in positional_wrapper
return wrapped(_args, *_kwargs)
File "/local/lib/python2.7/site-packages/google_api_python_client-1.2-py2.7.egg/apiclient/discovery.py", line 192, in build
resp, content = http.request(requested_url)
File "/local/lib/python2.7/site-packages/google_api_python_client-1.2-py2.7.egg/oauth2client/util.py", line 132, in positional_wrapper
return wrapped(_args, *_kwargs)
File "/local/lib/python2.7/site-packages/google_api_python_client-1.2-py2.7.egg/oauth2client/client.py", line 475, in new_request
self._refresh(request_orig)
File "/local/lib/python2.7/site-packages/google_api_python_client-1.2-py2.7.egg/oauth2client/client.py", line 653, in _refresh
self._do_refresh_request(http_request)
File "/local/lib/python2.7/site-packages/google_api_python_client-1.2-py2.7.egg/oauth2client/client.py", line 682, in _do_refresh_request
self.token_uri, method='POST', body=body, headers=headers)
File "/local/lib/python2.7/site-packages/httplib2/init.py", line 1593, in request
(response, content) = self._request(conn, authority, uri, request_uri, method, body, headers, redirections, cachekey)
File "/local/lib/python2.7/site-packages/httplib2/init.py", line 1335, in _request
(response, content) = self._conn_request(conn, request_uri, method, body, headers)
File "/local/lib/python2.7/site-packages/httplib2/init.py", line 1257, in _conn_request
self.disable_ssl_certificate_validation, self.ca_certs)
File "/local/lib/python2.7/site-packages/httplib2/init.py", line 80, in _ssl_wrap_socket
cert_reqs=cert_reqs, ca_certs=ca_certs)
File "/usr/lib/python2.7/ssl.py", line 381, in wrap_socket
ciphers=ciphers)
File "/usr/lib/python2.7/ssl.py", line 143, in init
self._sslobj.do_handshake()
SSLError: [Errno 8] _ssl.c:504: EOF occurred in violation of protocol

Typo in README

Should be pip install --upgrade google-api-python-client

sendNotificationEmails is broken?

I am trying to change the ownership of some files from my service account to myself and it changes the ownership but I cannot for the life of me turn off the email notification.

perm = {'value': '[email protected]', 'type': 'user', 'role': 'owner'}
        service.permissions().insert(fileId=file_id, body=perm, sendNotificationEmails=False).execute()

Is this feature broken?

Error in converting googleapiclient.errors.HttpError to string

try:
    results = ga.core.query.get()
except googleapiclient.errors.HttpError as err:
    print(err)  # TypeError: the JSON object must be str, not 'bytes'

    print(json.loads(err.content.decode('utf-8'))['error']['message'])  # works

Environment:

  • Python 3.4.3
  • google-api-python-client==1.4.0
  • httplib2==0.9.1
  • oauth2client==1.4.7
  • six==1.9.0
  • uritemplate==0.6

enhacement: attach listener to long running tasks

I guess this is more relevant for drive apis as those can take a long time for large files.
It would be nice to provide some sort of callback/listener to get progress report every once and a while so we will know that things are still working properly and estimate how long we got until done.

Copy doesn't interpret bucket name correctly

Looking at the URL being requested, it's clear that the bucket being requested is foo-test. However, for some reason, the server thinks I'm passing bucket name foo-test/original. It's wrong.

  File "/Users/bistenes/Code/MyOrg/product/env/lib/python2.7/site-packages/googleapiclient/http.py", line 723, in execute
    raise HttpError(resp, content, uri=self.uri)
HttpError: <HttpError 400 when requesting https://www.googleapis.com/storage/v1/b/foo-test/o/original%2Fcopy.json/copyTo/b/foo-test/o/copy%2Fcopy.json?alt=json returned "Invalid bucket name: 'foo-test/original'.">

"apiclient" module not found

After installing this library with pip install google-api-python-client, it can't be found, though it is described like this in the docs and samples:

>>> from apiclient.discovery import build
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named apiclient.discovery

Fun fact: This worked fine a couple of days ago.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.