I am unable to authenticate oauth2.0 using openerp xml-rpc, right now i am using the cmd quickstart google spreadsheet api code to read and write from openerp once i have acquired the token using another script,
SCOPES = 'https://www.googleapis.com/auth/spreadsheets'
CLIENT_SECRET_FILE = '/opt/openerp/client_secret.json'
APPLICATION_NAME = 'Google Sheets 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,
'sheets.googleapis.com-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
if flags:
credentials = tools.run_flow(flow, store, flags)
# print (flags)
print('Storing credentials to ' + credential_path)
return credentials
print get_credentials()
& the code, I run from within openerp 6.1, where, I accept the url for the spreadsheet as an input from which, I strip the spreadsheet id and the location or block which needs to be edited eg A2, and a value that accepts the value to be written in that location.
def get_credentials(self,cr,uid,ids,context=None):
"""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,
'sheets.googleapis.com-python-quickstart.json')
store =Storage(credential_path)
credentials = store.get()
if not credentials or credentials.invalid:
subprocess.call(['python /opt/openerp/test.py'])
self.get_credentials(cr,uid,ids,context=context)
# flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
# flow.user_agent = APPLICATION_NAME
# if flags:
# credentials = tools.run_flow(flow, store, flags)
# else: # Needed only for compatibility with Python 2.6
# credentials = tools.run(flow, store)
# # print('Storing credentials to ' + credential_path)
return credentials
def update_sheet(self,cr,uid,ids,context=None):
"""Shows basic usage of the Sheets API.
Creates a Sheets API service object and prints the names and majors of
students in a sample spreadsheet:
https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit
"""
sheet_brw=self.browse(cr,uid,ids[0])
get_url=sheet_brw.get_url
rangeName=sheet_brw.update_location
start=get_url.find('spreadsheets/d/') +15
end=get_url.find('/edit',start)
spreadsheetId=get_url[start:end]
sheet_val=sheet_brw.value
credentials = self.get_credentials(cr,uid,ids,context)
http = credentials.authorize(httplib2.Http())
discoveryUrl = ('https://sheets.googleapis.com/$discovery/rest?'
'version=v4')
service = discovery.build('sheets', 'v4', http=http,
discoveryServiceUrl=discoveryUrl)
# spreadsheetId = '1sFhMx8VTkC_cgFfUDxdCByXkbUl7LpWSQbb_S2aIEtE'
# rangeName = 'A2:B'
result = service.spreadsheets().values().get(
spreadsheetId=spreadsheetId, range=rangeName).execute()
values = result.get('values', [])
print values
if not values:
print('No data found.')
else:
print('Medical College, Distance:')
for row in values:
# Print columns A and E, which correspond to indices 0 and 4.
row0=row[0] if len(row) else ''
row1=row[1] if len(row) > 1 else ''
print('%s, %s' % (row0, row1))
values = [
[ str(sheet_val)
],
# Additional rows ...
]
body = {
# 'valueInputOption': 'RAW',
'values': values
}
result = service.spreadsheets().values().update(
spreadsheetId=spreadsheetId, range=rangeName,valueInputOption='RAW',body=body).execute()
get_spreadsheet()
I solved it by creating a refresh key and using the same to authorize since the refresh key never expires but can be revoked it works best for this scenario
I generated the refresh token from here and used it to generate credentials like here
Finally my code for openerp is as :
from oauth2client import client, GOOGLE_TOKEN_URI, GOOGLE_REVOKE_URI
CLIENT_ID = "<client identifier>"
CLIENT_SECRET = "<client secret>"
REFRESH_TOKEN = "<refresh_token>"
def get_credentials(self,cr,uid,ids,context=None):
credentials = client.OAuth2Credentials(
None, CLIENT_ID, CLIENT_SECRET, REFRESH_TOKEN, None, GOOGLE_TOKEN_URI,
None, revoke_uri=GOOGLE_REVOKE_URI)
credentials.refresh(httplib2.Http())
return credentials
def update_sheet(self,cr,uid,ids,context=None):
"""Shows basic usage of the Sheets API.
Creates a Sheets API service object and prints the names and majors of
students in a sample spreadsheet:
https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit
"""
sheet_brw=self.browse(cr,uid,ids[0])
get_url=sheet_brw.get_url
rangeName=sheet_brw.update_location
start=get_url.find('spreadsheets/d/') +15
end=get_url.find('/edit',start)
spreadsheetId=get_url[start:end]
sheet_val=sheet_brw.value
credentials = self.get_credentials(cr,uid,ids,context)
http = credentials.authorize(httplib2.Http())
discoveryUrl = ('https://sheets.googleapis.com/$discovery/rest?'
'version=v4')
service = discovery.build('sheets', 'v4', http=http,
discoveryServiceUrl=discoveryUrl)
# rangeName = 'A2:B'
result = service.spreadsheets().values().get(
spreadsheetId=spreadsheetId, range=rangeName).execute()
values = result.get('values', [])
print values
if not values:
print('No data found.')
else:
print('Medical College, Distance:')
for row in values:
# Print columns A and E, which correspond to indices 0 and 4.
row0=row[0] if len(row) else ''
row1=row[1] if len(row) > 1 else ''
print('%s, %s' % (row0, row1))
values = [
[ str(sheet_val)
],
# Additional rows ...
]
body = {
# 'valueInputOption': 'RAW',
'values': values
}
result = service.spreadsheets().values().update(
spreadsheetId=spreadsheetId, range=rangeName,valueInputOption='RAW',body=body).execute()
get_spreadsheet()