将 openerp 6.1 连接到 google 电子表格 api

connect openerp 6.1 to google spreadsheet api

我无法使用 openerp xml-rpc 验证 oauth2.0,现在我正在使用 cmd quickstart google 电子表格 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()

& 代码,我 运行 来自 openerp 6.1,其中,我接受电子表格的 url 作为输入,我从中删除电子表格 ID 和位置或块需要编辑例如A2,以及接受要写入该位置的值的值。

Openerp 6.1 代码:

    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()

我通过创建一个刷新密钥并使用它来授权解决了这个问题,因为刷新密钥永远不会过期但可以被撤销它最适合这种情况

我从 here and used it to generate credentials like here

生成了刷新令牌

最后我的 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()