I have a script that adds events to my calendar that worked fine until this morning. I haven't made any changes, but now it doesn't work.
This is my code:
from __future__ import print_function
import httplib2
import os
import sys
from apiclient import discovery
from oauth2client import client
from oauth2client import tools
from oauth2client.file import Storage
from subprocess import Popen
import datetime
# If modifying these scopes, delete your previously saved credentials
# at ~/.credentials/calendar-python-quickstart.json
SCOPES = 'https://www.googleapis.com/auth/calendar.readonly'
CLIENT_SECRET_FILE = 'client_secret.json'
APPLICATION_NAME = 'Google Calendar API Python Quickstart'
def get_credentials():
"""Gets valid user credentials from storage.
If nothing has been stored, or if the stored credentials are invalid,
the OAuth2 flow is completed to obtain the new credentials.
Returns:
Credentials, the obtained credential.
"""
home_dir = os.path.expanduser('~')
credential_dir = os.path.join(home_dir, '.credentials')
if not os.path.exists(credential_dir):
os.makedirs(credential_dir)
credential_path = os.path.join(credential_dir,
'calendar-python-quickstart.json')
store = Storage(credential_path)
credentials = store.get()
if not credentials or credentials.invalid:
flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
flow.user_agent = APPLICATION_NAME
credentials = tools.run(flow, store)
print('Storing credentials to ' + credential_path)
return credentials
def main():
"""Shows basic usage of the Google Calendar API.
Creates a Google Calendar API service object and outputs a list of the next
10 events on the user's calendar.
"""
try:
if(len(sys.argv) < 2):
print('No name was provided.')
input()
exit()
credentials = get_credentials()
http = credentials.authorize(httplib2.Http())
service = discovery.build('calendar', 'v3', http=http)
event = {
'summary': 'Teststop ' + " ".join(sys.argv[1:]),
'start': {
'date': str(datetime.date.today() + datetime.timedelta(days=14)),
'timeZone': 'Europe/Stockholm',
},
'end': {
'date': str(datetime.date.today() + datetime.timedelta(days=14)),
'timeZone': 'Europe/Stockholm',
},
}
event = service.events().insert(calendarId='CENSORED#group.calendar.google.com', body=event).execute()
print ('Event created: %s' % (event.get('htmlLink')))
p = Popen([r'C:\Program Files (x86)\Google\Chrome\Application\chrome.exe', r'https://calendar.google.com/calendar/render#main_7%7Cmonth' ], stdin=None, stdout=None, stderr=None)
exit()
except Exception as e:
traceback.print_exc()
print(str(e))
input()
if __name__ == '__main__':
main()
This is the output I'm getting:
C:\Users\jhh\executor\scripts\google calendar>py addEvent.py test
Traceback (most recent call last):
File "addEvent.py", line 63, in main
service = discovery.build('calendar', 'v3', http=http)
File "C:\Python\lib\site-packages\oauth2client\_helpers.py", line 133, in posi
tional_wrapper
return wrapped(*args, **kwargs)
File "C:\Python\lib\site-packages\googleapiclient\discovery.py", line 229, in
build
requested_url, discovery_http, cache_discovery, cache)
File "C:\Python\lib\site-packages\googleapiclient\discovery.py", line 276, in
_retrieve_discovery_doc
resp, content = http.request(actual_url)
File "C:\Python\lib\site-packages\oauth2client\transport.py", line 175, in new
_request
redirections, connection_type)
File "C:\Python\lib\site-packages\oauth2client\transport.py", line 282, in req
uest
connection_type=connection_type)
File "C:\Python\lib\site-packages\httplib2\__init__.py", line 1322, in request
(response, content) = self._request(conn, authority, uri, request_uri, metho
d, body, headers, redirections, cachekey)
File "C:\Python\lib\site-packages\httplib2\__init__.py", line 1072, in _reques
t
(response, content) = self._conn_request(conn, request_uri, method, body, he
aders)
File "C:\Python\lib\site-packages\httplib2\__init__.py", line 995, in _conn_re
quest
conn.connect()
File "C:\Python\lib\http\client.py", line 1400, in connect
server_hostname=server_hostname)
File "C:\Python\lib\ssl.py", line 407, in wrap_socket
_context=self, _session=session)
File "C:\Python\lib\ssl.py", line 814, in __init__
self.do_handshake()
File "C:\Python\lib\ssl.py", line 1068, in do_handshake
self._sslobj.do_handshake()
File "C:\Python\lib\ssl.py", line 689, in do_handshake
self._sslobj.do_handshake()
ConnectionResetError: [WinError 10054] An existing connection was forcibly closed by the remote host.
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "addEvent.py", line 88, in <module>
main()
File "addEvent.py", line 83, in main
traceback.print_exc()
NameError: name 'traceback' is not defined
I have no idea how to solve this. Any ideas?
Related
I would like to extract the reporting data of our mobile apps from Google Play Console.
According to this documentation, we have to use SignedJwtAssertionCredentials to authenticate. After some errors and research it seems that the code snippet in the doc is kind of outdated (since SignedJWTAssertionCredentials is not available anymore). Instead we tried the following to automatically download the reports:
from oauth2client.service_account import ServiceAccountCredentials
from apiclient.discovery import build
scopes = ['https://www.googleapis.com/auth/analytics.readonly']
key_file_location = 'files/access_token/mykeyfile.json'
credentials = ServiceAccountCredentials.from_json_keyfile_name(key_file_location, scopes)
cloud_storage_bucket = 'pubsite_prod_rev_123456789'
report_to_download = 'installs/installs_com.someapp.etc.etc_2021*'
storage = build('storage', 'v1', credentials=credentials)
print( storage.objects().get(bucket = cloud_storage_bucket,object = report_to_download).execute())
Now the problem is, that we receive the following error message:
Traceback (most recent call last):
File "C:\Users\dev\dev\z_10_ext_google_play_store.py", line 30, in <module>
print( storage.objects().get(bucket = cloud_storage_bucket,object = report_to_download).execute())
File "D:\Software\Python\lib\site-packages\googleapiclient\_helpers.py", line 130, in positional_wrapper
return wrapped(*args, **kwargs)
File "D:\Software\Python\lib\site-packages\googleapiclient\http.py", line 938, in execute
raise HttpError(resp, content, uri=self.uri)
googleapiclient.errors.HttpError: <HttpError 403 when requesting https://storage.googleapis.com/storage/v1/b/pubsite_prod_rev_123456789/o/installs%2Finstalls_com.someapp.etc.etc_2021%2A?alt=json returned "Insufficient Permission". Details: "[{'message': 'Insufficient Permission', 'domain': 'global', 'reason': 'insufficientPermissions'}]">
Does anyone have an idea? Our service account even has admin rights in play console (which normally would be to much..)
UPDATE
As DaImTo pointed out, I was missing some scopes which lead me to a different line of scope definition:
scopes = ['https://www.googleapis.com/auth/analytics.readonly', 'https://www.googleapis.com/auth/devstorage.read_only'
,'https://www.googleapis.com/auth/cloud-platform.read_only']
But I still receive some errors, now because of the missing access token which is weird because the .json file contains everything necessary:
Traceback (most recent call last):
File "C:\Users\andre\Desktop\DAWSE\z_10_ext_google_play_store.py", line 33, in <module>
print( storage.objects().get(bucket = cloud_storage_bucket,object = report_to_download).execute())
File "D:\Sonstige Programme\Python\lib\site-packages\googleapiclient\_helpers.py", line 130, in positional_wrapper
return wrapped(*args, **kwargs)
File "D:\Sonstige Programme\Python\lib\site-packages\googleapiclient\http.py", line 923, in execute
resp, content = _retry_request(
File "D:\Sonstige Programme\Python\lib\site-packages\googleapiclient\http.py", line 191, in _retry_request
resp, content = http.request(uri, method, *args, **kwargs)
File "D:\Sonstige Programme\Python\lib\site-packages\oauth2client\transport.py", line 159, in new_request
credentials._refresh(orig_request_method)
File "D:\Sonstige Programme\Python\lib\site-packages\oauth2client\client.py", line 749, in _refresh
self._do_refresh_request(http)
File "D:\Sonstige Programme\Python\lib\site-packages\oauth2client\client.py", line 785, in _do_refresh_request
self.access_token = d['access_token']
KeyError: 'access_token'
You appear to be using the objects.get method
The authenticated user must have sufficient permission to use this method. To start with i would ensure your service account has access.
After that i would check your scopes you are currently only loading the scope for google analytics api.
scopes = ['https://www.googleapis.com/auth/analytics.readonly']
This scope will not grant you access to the google cloud storage objects get method. For that you need to use one of the google cloud storage scopes
I have set up a discord bot a week ago that uses google drive api. The bot worked for a week in a web hosting server, and today I checked and it's been giving me this error every time i started up the bot.
client_secret.json-drive-v3-(['https://www.googleapis.com/auth/drive'],)
['https://www.googleapis.com/auth/drive']
Traceback (most recent call last):
File "C:\Users\Unknown1\Documents\discordbot\bot.py", line 5, in <module>
from googledrive import find_recent
File "C:\Users\Unknown1\Documents\discordbot\googledrive.py", line 10, in <module>
service = Create_Service(CLIENT_SECRET_FILE, API_NAME, API_VERSION, SCOPES)
File "C:\Users\Unknown1\Documents\discordbot\Google.py", line 28, in Create_Service
cred.refresh(Request())
File "C:\Users\Unknown1\AppData\Local\Programs\Python\Python39\lib\site-packages\google\oauth2\credentials.py", line 200, in refresh
access_token, refresh_token, expiry, grant_response = _client.refresh_grant(
File "C:\Users\Unknown1\AppData\Local\Programs\Python\Python39\lib\site-packages\google\oauth2\_client.py", line 248, in refresh_grant
response_data = _token_endpoint_request(request, token_uri, body)
File "C:\Users\Unknown1\AppData\Local\Programs\Python\Python39\lib\site-packages\google\oauth2\_client.py", line 124, in _token_endpoint_request
_handle_error_response(response_body)
File "C:\Users\Unknown1\AppData\Local\Programs\Python\Python39\lib\site-packages\google\oauth2\_client.py", line 60, in _handle_error_response
raise exceptions.RefreshError(error_details, response_body)
google.auth.exceptions.RefreshError: ('invalid_grant: Token has been expired or revoked.', '{\n "error": "invalid_grant",\n "error_description": "Token has been expired or revoked."\n}')
PS C:\Users\Unknown1\Documents\discordbot>
I checked the client_secret_file.json and redownloaded it from google cloud api credentials and its still the same thing. I'm not sure where to go about from here to fix this issue.
import pandas as pd
import datetime
CLIENT_SECRET_FILE = 'client_secret.json'
API_NAME = 'drive'
API_VERSION = 'v3'
SCOPES = ['https://www.googleapis.com/auth/drive']
service = Create_Service(CLIENT_SECRET_FILE, API_NAME, API_VERSION, SCOPES)
#in the google drive web link, there will be a folder id.
folder_id = '1ANm4frKaL_JeMEewRMDBLWiiY3Srh-B-'
query = f"parents = '{folder_id}'"
response = service.files().list(q=query).execute()
files = response.get('files')
nextPageToken = response.get('nextPageToken')
while nextPageToken:
response = service.files().list(q=query,pageToken=nextPageToken).execute()
files.extend(response.get('files'))
nextpageToken = response.get('nextPageToken')
df = pd.DataFrame(files)
I have set up a new project , OAuth 2.0 Client ID Credentials, following this youtube video:https://www.youtube.com/watch?v=FAM_4J7ywcE&ab_channel=nouthemes
and deleted the old one in hopes of replacing the client secret file with the new one. Now I am getting a new error :
client_secret.json-drive-v3-(['https://www.googleapis.com/auth/drive'],)
['https://www.googleapis.com/auth/drive']
Traceback (most recent call last):
File "C:\Users\Unknown1\Documents\discordbot\bot.py", line 5, in <module>
from googledrive import find_recent
File "C:\Users\Unknown1\Documents\discordbot\googledrive.py", line 10, in <module>
service = Create_Service(CLIENT_SECRET_FILE, API_NAME, API_VERSION, SCOPES)
File "C:\Users\Unknown1\Documents\discordbot\Google.py", line 28, in Create_Service
cred.refresh(Request())
File "C:\Users\Unknown1\AppData\Local\Programs\Python\Python39\lib\site-packages\google\oauth2\credentials.py", line 200, in refresh
access_token, refresh_token, expiry, grant_response = _client.refresh_grant(
File "C:\Users\Unknown1\AppData\Local\Programs\Python\Python39\lib\site-packages\google\oauth2\_client.py", line 248, in refresh_grant
response_data = _token_endpoint_request(request, token_uri, body)
File "C:\Users\Unknown1\AppData\Local\Programs\Python\Python39\lib\site-packages\google\oauth2\_client.py", line 124, in _token_endpoint_request
_handle_error_response(response_body)
File "C:\Users\Unknown1\AppData\Local\Programs\Python\Python39\lib\site-packages\google\oauth2\_client.py", line 60, in _handle_error_response
raise exceptions.RefreshError(error_details, response_body)
google.auth.exceptions.RefreshError: ('deleted_client: The OAuth client was deleted.', '{\n "error": "deleted_client",\n "error_description": "The OAuth client was deleted."\n}')
I'm stuck.
I am trying to connect to Google Cloud Storage from a standalone python script using a service account. I am running this script from my local system. I have also activated the service account using gcloud auth and added "GOOGLE_APPLICATION_CREDENTIALS" to point to the client_secrets.json file.
The authentication does not work and fails with the following log:
Uploading object..
Traceback (most recent call last):
File "quickstart.py", line 122, in
main(args.bucket, args.filename, args.reader, args.owner)
File "quickstart.py", line 16, in main
resp = upload_object(bucket, filename, readers, owners)
File "quickstart.py", line 43, in upload_object
service = create_service()
File "quickstart.py", line 39, in create_service
return discovery.build('storage', 'v1', http=http_auth)
File "build/bdist.macosx-10.12-intel/egg/oauth2client/util.py", line 137, in positional_wrapper
File "build/bdist.macosx-10.12-intel/egg/googleapiclient/discovery.py", line 214, in build
File "build/bdist.macosx-10.12-intel/egg/googleapiclient/discovery.py", line 261, in _retrieve_discovery_doc
File "build/bdist.macosx-10.12-intel/egg/oauth2client/transport.py", line 153, in new_request
File "build/bdist.macosx-10.12-intel/egg/oauth2client/client.py", line 765, in _refresh
File "build/bdist.macosx-10.12-intel/egg/oauth2client/client.py", line 797, in _do_refresh_request
File "/Library/Python/2.7/site-packages/httplib2-0.9.2-py2.7.egg/httplib2/__init__.py", line 1609, in request
(response, content) = self._request(conn, authority, uri, request_uri, method, body, headers, redirections, cachekey)
File "/Library/Python/2.7/site-packages/httplib2-0.9.2-py2.7.egg/httplib2/__init__.py", line 1351, in _request
(response, content) = self._conn_request(conn, request_uri, method, body, headers)
File "/Library/Python/2.7/site-packages/httplib2-0.9.2-py2.7.egg/httplib2/__init__.py", line 1272, in _conn_request
conn.connect()
File "/Library/Python/2.7/site-packages/httplib2-0.9.2-py2.7.egg/httplib2/__init__.py", line 1036, in connect
self.disable_ssl_certificate_validation, self.ca_certs)
File "/Library/Python/2.7/site-packages/httplib2-0.9.2-py2.7.egg/httplib2/__init__.py", line 80, in _ssl_wrap_socket
cert_reqs=cert_reqs, ca_certs=ca_certs)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ssl.py", line 911, in wrap_socket
ciphers=ciphers)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ssl.py", line 520, in __init__
self._context.load_verify_locations(ca_certs)
IOError: [Errno 13] Permission denied
Here is the code snipped I am trying to run to authenticate:
import oauth2client
from oauth2client.service_account import ServiceAccountCredentials
from httplib2 import Http
from googleapiclient import discovery
import argparse
import filecmp
import json
import tempfile
import logging
logging.basicConfig(filename='debug.log',level=logging.DEBUG)
def main(bucket, filename, readers=[], owners=[]):
print('Uploading object..')
resp = upload_object(bucket, filename, readers, owners)
print(json.dumps(resp, indent=2))
def create_service():
scopes = ['https://www.googleapis.com/auth/devstorage.read_write']
credentials = ServiceAccountCredentials.from_json_keyfile_name('client_secrets.json', scopes)
http_auth = credentials.authorize(Http())
return discovery.build('storage', 'v1', http=http_auth)
def upload_object(bucket, filename, readers, owners):
service = create_service()
# This is the request body as specified:
# http://g.co/cloud/storage/docs/json_api/v1/objects/insert#request
body = {
'name': filename,
}
# If specified, create the access control objects and add them to the
# request body
if readers or owners:
body['acl'] = []
for r in readers:
body['acl'].append({
'entity': 'user-%s' % r,
'role': 'READER',
'email': r
})
for o in owners:
body['acl'].append({
'entity': 'user-%s' % o,
'role': 'OWNER',
'email': o
})
# Now insert them into the specified bucket as a media insertion.
# http://g.co/dv/resources/api-libraries/documentation/storage/v1/python/latest/storage_v1.objects.html#insert
with open(filename, 'rb') as f:
req = service.objects().insert(
bucket=bucket, body=body,
# You can also just set media_body=filename, but for the sake of
# demonstration, pass in the more generic file handle, which could
# very well be a StringIO or similar.
media_body=http.MediaIoBaseUpload(f, 'application/octet-stream'))
resp = req.execute()
return resp
I tried looking at multiple examples from google developers forum as well as other blogs. All show the same code. Not sure what is going wrong here.
From the error it looks like a simple permissions problem. Did you run the program with root priviges? If not then run the file from the command line with sudo at the beginning.
Note: IDLE doesn't run it with root.
The last line of the traceback indicates that your Python script cannot access a resource on disk with the correct permissions.
IOError: [Errno 13] Permission denied
A simple fix is to run this script with sudo.
When running the sample script provided I get an IOError, is there something in the sample code i should change to work for my needs? I added the nesscessary items to the client_secrets.json. The sample code works up to when it opens the Youtube Authorization page
Terminal Output:
Your browser has been opened to visit:
https://accounts.google.com/o/oauth2/auth?scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fyoutube.readonly&redirect_uri=http%3A%2F%2Flocalhost%3A8080%2F&response_type=code&client_id=186270759317-a10stlli8gucv9bt8gt9f8vvbo1hsfv2.apps.googleusercontent.com&access_type=offline
If your browser is on a different machine then exit and re-run this
application with the command-line parameter
--noauth_local_webserver
Traceback (most recent call last):
File "youtube_broadcast.py", line 90, in <module>
youtube = get_authenticated_service(args)
File "youtube_broadcast.py", line 61, in get_authenticated_service
credentials = run_flow(flow, storage, args)
File "/Library/Python/2.7/site-packages/oauth2client-1.4.12-py2.7.egg/oauth2client/util.py", line 137, in positional_wrapper
File "/Library/Python/2.7/site-packages/oauth2client-1.4.12-py2.7.egg/oauth2client/tools.py", line 225, in run_flow
File "/Library/Python/2.7/site-packages/oauth2client-1.4.12-py2.7.egg/oauth2client/util.py", line 137, in positional_wrapper
File "/Library/Python/2.7/site-packages/oauth2client-1.4.12-py2.7.egg/oauth2client/client.py", line 1993, in step2_exchange
File "/Library/Python/2.7/site-packages/httplib2-0.9.1-py2.7.egg/httplib2/__init__.py", line 1608, in request
(response, content) = self._request(conn, authority, uri, request_uri, method, body, headers, redirections, cachekey)
File "/Library/Python/2.7/site-packages/httplib2-0.9.1-py2.7.egg/httplib2/__init__.py", line 1350, in _request
(response, content) = self._conn_request(conn, request_uri, method, body, headers)
File "/Library/Python/2.7/site-packages/httplib2-0.9.1-py2.7.egg/httplib2/__init__.py", line 1272, in _conn_request
conn.connect()
File "/Library/Python/2.7/site-packages/httplib2-0.9.1-py2.7.egg/httplib2/__init__.py", line 1036, in connect
self.disable_ssl_certificate_validation, self.ca_certs)
File "/Library/Python/2.7/site-packages/httplib2-0.9.1-py2.7.egg/httplib2/__init__.py", line 80, in _ssl_wrap_socket
cert_reqs=cert_reqs, ca_certs=ca_certs)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ssl.py", line 911, in wrap_socket
ciphers=ciphers)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ssl.py", line 520, in __init__
self._context.load_verify_locations(ca_certs)
IOError: [Errno 13] Permission denied
Python Script:
#!/usr/bin/python
import httplib2
import os
import sys
from apiclient.discovery import build
from apiclient.errors import HttpError
from oauth2client.client import flow_from_clientsecrets
from oauth2client.file import Storage
from oauth2client.tools import argparser, run_flow
# The CLIENT_SECRETS_FILE variable specifies the name of a file that contains
# the OAuth 2.0 information for this application, including its client_id and
# client_secret. You can acquire an OAuth 2.0 client ID and client secret from
# the Google Developers Console at
# https://console.developers.google.com/.
# Please ensure that you have enabled the YouTube Data API for your project.
# For more information about using OAuth2 to access the YouTube Data API, see:
# https://developers.google.com/youtube/v3/guides/authentication
# For more information about the client_secrets.json file format, see:
# https://developers.google.com/api-client-library/python/guide/aaa_client_secrets
CLIENT_SECRETS_FILE = "client_secrets.json"
# This OAuth 2.0 access scope allows for read-only access to the authenticated
# user's account, but not other types of account access.
YOUTUBE_READONLY_SCOPE = "https://www.googleapis.com/auth/youtube.readonly"
YOUTUBE_API_SERVICE_NAME = "youtube"
YOUTUBE_API_VERSION = "v3"
# This variable defines a message to display if the CLIENT_SECRETS_FILE is
# missing.
MISSING_CLIENT_SECRETS_MESSAGE = """
WARNING: Please configure OAuth 2.0
To make this sample run you will need to populate the client_secrets.json file
found at:
%s
with information from the Developers Console
https://console.developers.google.com/
For more information about the client_secrets.json file format, please visit:
https://developers.google.com/api-client-library/python/guide/aaa_client_secrets
""" % os.path.abspath(os.path.join(os.path.dirname(__file__),
CLIENT_SECRETS_FILE))
VALID_BROADCAST_STATUSES = ("all", "active", "completed", "upcoming",)
def get_authenticated_service(args):
flow = flow_from_clientsecrets(CLIENT_SECRETS_FILE,
scope=YOUTUBE_READONLY_SCOPE,
message=MISSING_CLIENT_SECRETS_MESSAGE)
storage = Storage("%s-oauth2.json" % sys.argv[0])
credentials = storage.get()
if credentials is None or credentials.invalid:
credentials = run_flow(flow, storage, args)
return build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION,
http=credentials.authorize(httplib2.Http()))
# Retrieve a list of broadcasts with the specified status.
def list_broadcasts(youtube, broadcast_status):
print "Broadcasts with status '%s':" % broadcast_status
list_broadcasts_request = youtube.liveBroadcasts().list(
broadcastStatus=broadcast_status,
part="id,snippet",
maxResults=50
)
while list_broadcasts_request:
list_broadcasts_response = list_broadcasts_request.execute()
for broadcast in list_broadcasts_response.get("items", []):
print "%s (%s)" % (broadcast["snippet"]["title"], broadcast["id"])
list_broadcasts_request = youtube.liveBroadcasts().list_next(
list_broadcasts_request, list_broadcasts_response)
if __name__ == "__main__":
argparser.add_argument("--broadcast-status", help="Broadcast status",
choices=VALID_BROADCAST_STATUSES, default=VALID_BROADCAST_STATUSES[0])
args = argparser.parse_args()
youtube = get_authenticated_service(args)
try:
list_broadcasts(youtube, args.broadcast_status)
except HttpError, e:
print "An HTTP error %d occurred:\n%s" % (e.resp.status, e.content)
I am using google-api-python-client to site-wide delegate auth for a calendar building program I am writing.
import pytz
from datetime import datetime, timedelta
import httplib2
import json
from apiclient.discovery import build
from oauth2client.client import SignedJwtAssertionCredentials
with open('privatekey.pem', 'rb') as f:
key = f.read()
with open('config.json') as f:
config = json.load(f)
service_account_name = config['account_email']
calendarId = config['calendarId']
credentials = SignedJwtAssertionCredentials(
service_account_name, key,
scope=['https://www.googleapis.com/auth/calendar',
'https://www.googleapis.com/auth/calendar.readonly'])
http = httplib2.Http()
http = credentials.authorize(http)
service = build(serviceName='calendar', version='v3', http=http)
I do not have any issue running this on my production server, however on my dev (personal laptop) it is throwing a I do not have any issue running this on my production server, however on my dev (personal laptop) is throwing an error on urlencode. From my understanding urllib.parse.urlencode is the python 3 path? Why is my dev calling this ?
File "cal.py", line 27, in <module>
service = build(serviceName='calendar', version='v3', http=http)
return wrapped(*args, **kwargs)
File "/Library/Python/2.7/site-packages/googleapiclient/discovery.py", line 196, in build
resp, content = http.request(requested_url)
File "/Library/Python/2.7/site-packages/oauth2client/util.py", line 137, in positional_wrapper
return wrapped(*args, **kwargs)
File "/Library/Python/2.7/site-packages/oauth2client/client.py", line 534, in new_request
self._refresh(request_orig)
File "/Library/Python/2.7/site-packages/oauth2client/client.py", line 748, in _refresh
self._do_refresh_request(http_request)
File "/Library/Python/2.7/site-packages/oauth2client/client.py", line 772, in _do_refresh_request
body = self._generate_refresh_request_body()
File "/Library/Python/2.7/site-packages/oauth2client/client.py", line 1381, in _generate_refresh_request_body
body = urllib.parse.urlencode({
AttributeError: 'Module_six_moves_urllib_parse' object has no attribute 'urlencode'
Thanks for you help!