当前位置: 首页>>代码示例>>Python>>正文


Python gspread.authorize方法代码示例

本文整理汇总了Python中gspread.authorize方法的典型用法代码示例。如果您正苦于以下问题:Python gspread.authorize方法的具体用法?Python gspread.authorize怎么用?Python gspread.authorize使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在gspread的用法示例。


在下文中一共展示了gspread.authorize方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: _init_gsheet_client

# 需要导入模块: import gspread [as 别名]
# 或者: from gspread import authorize [as 别名]
def _init_gsheet_client():
        with GoogleSheet._client_lock():
            def _():
                if config.GOOGLE_SERVICE_ACCOUNT is not None:
                    credentials = ServiceAccountCredentials.from_json_keyfile_dict(
                        json.loads(config.GOOGLE_SERVICE_ACCOUNT),
                        scopes=SCOPES)
                else:
                    credentials = ServiceAccountCredentials.from_json_keyfile_name(
                        "avrae-google.json",
                        scopes=SCOPES)
                return gspread.authorize(credentials)

            try:
                GoogleSheet.g_client = await asyncio.get_event_loop().run_in_executor(None, _)
            except:
                GoogleSheet._client_initializing = False
                raise
        GoogleSheet._token_expiry = datetime.datetime.now() + datetime.timedelta(
            seconds=ServiceAccountCredentials.MAX_TOKEN_LIFETIME_SECS)
        log.info("Logged in to google") 
开发者ID:avrae,项目名称:avrae,代码行数:23,代码来源:gsheet.py

示例2: handle

# 需要导入模块: import gspread [as 别名]
# 或者: from gspread import authorize [as 别名]
def handle(self, *args, **options):
        """Fetch Mess Menus."""

        # Use credentials to create a client to interact with the Google Drive API
        print("Authorizing - ", end="", flush=True)
        scope = ['https://spreadsheets.google.com/feeds',
                 'https://www.googleapis.com/auth/drive']

        creds = ServiceAccountCredentials.from_json_keyfile_name('google_client_secret.json', scope)
        client = gspread.authorize(creds)
        print("OK")

        # Iterate over all hostels
        for hostel in Hostel.objects.all():
            print("Updating " + hostel.name + " - ", end="", flush=True)
            if hostel.mess_gsheet:
                try:
                    fetch_hostel(client, hostel)
                    print("OK")
                except Exception:  # pylint: disable=W0703
                    print("FAIL")
            else:
                print("SKIP") 
开发者ID:wncc,项目名称:instiapp-api,代码行数:25,代码来源:mess_chore.py

示例3: setUp

# 需要导入模块: import gspread [as 别名]
# 或者: from gspread import authorize [as 别名]
def setUp(self):

        configPath = os.path.join(basePath, 'config', 'google-config.json')
        try:
            with open(configPath, 'rb') as f:
                s = json.loads(f.read())
        except:
            raise SkipTest("Could not access Google configuration file.")

        self.params = s['google']

        scope = ['https://spreadsheets.google.com/feeds']
        credentials = SignedJwtAssertionCredentials(self.params['client_email'], self.params['private_key'], scope)       
        gc = gspread.authorize(credentials)
        
        self.client = gc.open(self.params['google_sheet']).sheet1
        self.randText = ''.join([random.choice(string.letters) for i in range(10)])

        self.channel = googleSpread.GoogleSpread()
        self.channel.params['sending'] = self.params
        self.channel.params['receiving'] = self.params 
开发者ID:DakotaNelson,项目名称:sneaky-creeper,代码行数:23,代码来源:test_google.py

示例4: send

# 需要导入模块: import gspread [as 别名]
# 或者: from gspread import authorize [as 别名]
def send(self, data):
        CLIENT_EMAIL = self.param('sending', 'client_email')
        PRIVATE_KEY = self.param('sending', 'private_key')
        GOOGLE_SPREAD = self.param('sending', 'google_sheet')

        scope = ['https://spreadsheets.google.com/feeds']
        credentials = SignedJwtAssertionCredentials(CLIENT_EMAIL, PRIVATE_KEY, scope)
        gc = gspread.authorize(credentials)
        sheet = gc.open(GOOGLE_SPREAD).sheet1

        WRITE_COL = self.param('sending', 'column')
        row = 1
        while sheet.acell(WRITE_COL+str(row)).value:
            row += 1
        cell = WRITE_COL + str(row)

        sheet.update_acell(cell, data)
        return 
开发者ID:DakotaNelson,项目名称:sneaky-creeper,代码行数:20,代码来源:googleSpread.py

示例5: receive

# 需要导入模块: import gspread [as 别名]
# 或者: from gspread import authorize [as 别名]
def receive(self):
        CLIENT_EMAIL = self.param('receiving', 'client_email')
        PRIVATE_KEY = self.param('receiving', 'private_key')
        GOOGLE_SPREAD = self.param('receiving', 'google_sheet')

        scope = ['https://spreadsheets.google.com/feeds']
        credentials = SignedJwtAssertionCredentials(CLIENT_EMAIL, PRIVATE_KEY, scope)
        gc = gspread.authorize(credentials)
        sheet = gc.open(GOOGLE_SPREAD).sheet1

        READ_COL = self.param('receiving', 'column')

        cells = []
        row = 1

        while sheet.acell(READ_COL+str(row)).value:
            cells.append(sheet.acell(READ_COL+str(row)).value)
            row += 1

        return cells 
开发者ID:DakotaNelson,项目名称:sneaky-creeper,代码行数:22,代码来源:googleSpread.py

示例6: upload_test_results

# 需要导入模块: import gspread [as 别名]
# 或者: from gspread import authorize [as 别名]
def upload_test_results(results, name, sheet, credentials):
    """Upload the test results to the the google sheet"""

    if not sheet:
        return
    if not results:
        print('ERROR: No results specified')
        return

    credentials = ServiceAccountCredentials.from_json_keyfile_name(credentials, SCOPES)
    gcloud = gspread.authorize(credentials)

    spreadsheet = gcloud.open_by_url(sheet)

    try:
        worksheet = spreadsheet.worksheet(results["suite"])
    except gspread.exceptions.WorksheetNotFound:
        print(" * ERROR: Worksheet {} not found".format(results["suite"]))
        return

    filename = "{}_{}_{}.json".format(name, results.get('suite'), results.get('timestamp'))

    gsheets_import(results, worksheet, filename) 
开发者ID:AMWA-TV,项目名称:nmos-testing,代码行数:25,代码来源:runTestSuites.py

示例7: get_spreadsheet

# 需要导入模块: import gspread [as 别名]
# 或者: from gspread import authorize [as 别名]
def get_spreadsheet(credentials, doc_id, tab_id):
    """
    Inputs params:
    * credentials
    * doc_id
    * tab_id
    Returns a gspread's worksheet object.
    """
    credentials = get_credentials(credentials)
    scope = [
        'https://www.googleapis.com/auth/spreadsheets'
    ]
    gspread_client = gspread.authorize(ServiceAccountCredentials.from_json_keyfile_dict(credentials, scope))

    try:
        return gspread_client.open_by_key(doc_id).worksheet(tab_id)
    except gspread.exceptions.SpreadsheetNotFound as e:
        raise Exception("Trying to open non-existent or inaccessible spreadsheet document.")
    except gspread.exceptions.WorksheetNotFound as e:
        raise Exception("Trying to open non-existent sheet. Verify that the sheet name exists (%s)." % tab_id)
    except gspread.exceptions.APIError as e:
        if hasattr(e, 'response'):
            error_json = e.response.json()
            print(error_json)
            error_status = error_json.get("error", {}).get("status")
            email = credentials.get("client_email", "(email missing)")
            if error_status == 'PERMISSION_DENIED':
                error_message = error_json.get("error", {}).get("message", "")
                raise Exception("Access was denied with the following error: %s. Have you enabled the Sheets API? Have you shared the spreadsheet with %s?" % (error_message, email))
            if error_status == 'NOT_FOUND':
                raise Exception("Trying to open non-existent spreadsheet document. Verify the document id exists (%s)." % doc_id)
        raise Exception("The Google API returned an error: %s" % e) 
开发者ID:dataiku,项目名称:dataiku-contrib,代码行数:34,代码来源:googlesheets.py

示例8: _open_doc

# 需要导入模块: import gspread [as 别名]
# 或者: from gspread import authorize [as 别名]
def _open_doc(url):
    scope = ['https://spreadsheets.google.com/feeds']
    credentials = ServiceAccountCredentials.from_json_keyfile_name(
        settings.GOOGLE_SERVICE_ACCOUNT_KEYFILE_PATH, scope)
    gc = gspread.authorize(credentials)
    try:
        return gc.open_by_url(url)
    except gspread.SpreadsheetNotFound:
        raise SpreadsheetNotFound 
开发者ID:cyanfish,项目名称:heltour,代码行数:11,代码来源:spreadsheet.py

示例9: get_repo_request_rows

# 需要导入模块: import gspread [as 别名]
# 或者: from gspread import authorize [as 别名]
def get_repo_request_rows():
    from oauth2client.service_account import ServiceAccountCredentials

    # this file inspired by https://www.twilio.com/blog/2017/02/an-easy-way-to-read-and-write-to-a-google-spreadsheet-in-python.html

    # use creds to create a client to interact with the Google Drive API
    scopes = ['https://spreadsheets.google.com/feeds']
    json_creds = os.getenv("GOOGLE_SHEETS_CREDS_JSON")

    creds_dict = json.loads(json_creds)

    # hack to get around ugly new line escaping issues
    # this works for me, but later found links to what might be cleaner solutions:
    # use ast.literal_eval?  https://github.com/googleapis/google-api-go-client/issues/185#issuecomment-422732250
    # or maybe dumping like this might fix it? https://coreyward.svbtle.com/how-to-send-a-multiline-file-to-heroku-config

    creds_dict["private_key"] = creds_dict["private_key"].replace("\\\\n", "\n")

    # now continue
    creds = ServiceAccountCredentials.from_json_keyfile_dict(creds_dict, scopes)
    client = gspread.authorize(creds)

    # Find a workbook by url
    spreadsheet = client.open_by_url("https://docs.google.com/spreadsheets/d/1RcQuetbKVYRRf0GhGZQi38okY8gT1cPUs6l3RM94yQo/edit#gid=704459328")
    sheet = spreadsheet.sheet1

    # Extract and print all of the values
    rows = sheet.get_all_values()
    print(rows[0:1])
    return rows 
开发者ID:ourresearch,项目名称:oadoi,代码行数:32,代码来源:put_repo_requests_in_db.py

示例10: __init__

# 需要导入模块: import gspread [as 别名]
# 或者: from gspread import authorize [as 别名]
def __init__(self, spreadsheet_name):
        self.item_col = 1
        self.price_col = 2
        self.frequency_col = 3
        self.url_col = 4
        self.product_name_col = 5
        
        scope = ['https://spreadsheets.google.com/feeds',
                 'https://www.googleapis.com/auth/drive']

        creds = ServiceAccountCredentials.from_json_keyfile_name('client_secret.json',
                                                                 scope)
        client = gspread.authorize(creds)

        self.sheet = client.open(spreadsheet_name).sheet1 
开发者ID:vprusso,项目名称:youtube_tutorials,代码行数:17,代码来源:price_updater.py

示例11: get_credentials

# 需要导入模块: import gspread [as 别名]
# 或者: from gspread import authorize [as 别名]
def get_credentials(cred_file):
    scope = ['https://spreadsheets.google.com/feeds']
    credentials = ServiceAccountCredentials.from_json_keyfile_name(cred_file, scope)
    return gspread.authorize(credentials) 
开发者ID:redhat-cop,项目名称:infra-ansible,代码行数:6,代码来源:gsheets.py

示例12: test_toggl2gsuite

# 需要导入模块: import gspread [as 别名]
# 或者: from gspread import authorize [as 别名]
def test_toggl2gsuite(self):
        # have to do this year by year
        data = {
            'workspace_id': os.environ['WORKSPACE_ID'],
        }
        y = self.toggl.getDetailedReport(data)


        credentials = ServiceAccountCredentials.from_json_keyfile_name(
            os.environ['KEYFILE'],
            ['https://spreadsheets.google.com/feeds'])

        client = gspread.authorize(credentials)
        sheet = client.open_by_url(os.environ['SHEET_URL'])
        worksheet = sheet.get_worksheet(0)

        wrote_header = False
        columns_to_write = ['user', 'updated', 'start', 'end', 'client', 'project', 'description', 'is_billable',
                            'billable']
        cell_row = 0
        for row_idx, rec in enumerate(y['data']):
            if wrote_header == False:
                for col_idx, header in enumerate(columns_to_write):
                    worksheet.update_acell(Toggl2GSuiteTest.excel_style(row_idx + 1, col_idx + 1), header)
                wrote_header = True
            for col_idx, header in enumerate(columns_to_write):
                worksheet.update_acell(Toggl2GSuiteTest.excel_style(row_idx + 2, col_idx + 1), rec[header]) 
开发者ID:matthewdowney,项目名称:TogglPy,代码行数:29,代码来源:toggl2gsuite.py

示例13: setUpClass

# 需要导入模块: import gspread [as 别名]
# 或者: from gspread import authorize [as 别名]
def setUpClass(cls):
        try:
            cls.config = read_config(CONFIG_FILENAME)
            credentials = read_credentials(CREDS_FILENAME)
            cls.gc = gspread.authorize(credentials)
        except IOError as e:
            msg = "Can't find %s for reading test configuration. "
            raise Exception(msg % e.filename) 
开发者ID:robin900,项目名称:gspread-dataframe,代码行数:10,代码来源:gspread_dataframe_integration.py

示例14: write_to_google_sheet

# 需要导入模块: import gspread [as 别名]
# 或者: from gspread import authorize [as 别名]
def write_to_google_sheet(row):
    # use creds to create a client to interact with the Google Drive API
    scope = ['https://spreadsheets.google.com/feeds',
             'https://www.googleapis.com/auth/drive']
    credentials = ServiceAccountCredentials.from_json_keyfile_name('./client_secret.json', scope)
    client = gspread.authorize(credentials)

    sheet = client.open("2017-2018-PL-tips").sheet1
    sheet.append_row(row) 
开发者ID:BradleyGrantham,项目名称:pl-predictions-using-fifa,代码行数:11,代码来源:bot.py

示例15: get_sheet

# 需要导入模块: import gspread [as 别名]
# 或者: from gspread import authorize [as 别名]
def get_sheet(self, ctx) -> gspread.Worksheet:
        """Return values from spreadsheet."""
        server = ctx.message.server

        credentials = ServiceAccountCredentials.from_json_keyfile_name(
            SERVICE_KEY_JSON, scopes=SCOPES)
        spreadsheetId = self.settings[server.id]["SHEET_ID"]
        gc = gspread.authorize(credentials)
        sh = gc.open_by_key(spreadsheetId)
        worksheet = sh.get_worksheet(0)

        return worksheet 
开发者ID:smlbiobot,项目名称:SML-Cogs,代码行数:14,代码来源:banned.py


注:本文中的gspread.authorize方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。