[英]connect openerp 6.1 to google spreadsheet api
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, 我无法使用openerp xml-rpc对oauth2.0进行身份验证,现在我一旦使用其他脚本获取了令牌,就使用cmd quickstart谷歌电子表格api代码从openerp进行读写,
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. &代码,我在openerp 6.1中运行,在其中,我接受电子表格的网址作为输入,从中删除电子表格的ID和需要编辑的位置或块(例如A2)以及一个接受要写入该位置的值。
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 : 最后,我的openerp代码如下:
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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.