當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。