还有其他方法可以连接到 Airflow 中的 Google 表格吗?

ele*_*nto 3 python google-sheets airflow google-sheets-api

我正在尝试使用 Python Operator 连接到 Airflow 中的 Google Sheets,如下所示

import pandas as pd
import pygsheets
from google.oauth2 import service_account
from airflow.operators.python import PythonOperator

def estblsh_conn_to_gs():

    creds = service_account.Credentials.from_service_account_file(
        'service_account_json_file',
        scopes=('google_api_spreadsheets_auth_link', 'google_api_gdrive_auth_link'),
        subject='client_mail'
    )

    pg = pygsheets.authorize(custom_credentials=creds)
    return pg

def get_data_from_spreadsheet(spreadsheet_link, worksheet_title):

    pg = establish_conn_to_gs()
    doc = pg.open_by_url('spreadsheet_link')
    data = doc.worksheet_by_title('worksheet_name').get_all_values(include_tailing_empty_rows=False)
    return data

get_data_from_gs = PythonOperator(
    task_id = 'get_data_from_gs',
    python_callable = get_data_from_spreadsheet(link, title)
)
Run Code Online (Sandbox Code Playgroud)

这工作得很好,但也许还有其他选择可以做到同样的事情?我找到了 Google Sheets Operator,但当前的技术文档不好(

感谢帮助!

Ela*_*lad 5

Airflow 具有GSheetsHook通过 Google Cloud 连接与 Google Sheets 交互的功能(如果您没有定义连接,您可以按照此操作文档进行操作)

要从 Google Sheet 获取数据,只需使用钩子即可。您无需自己实现它 - 如果该功能不完全是您所需要的,那么您可以从钩子继承并增强它。

要获取值,您可以使用:

get_values- 从 Google Sheet 获取单个范围内的值 ( API )

batch_get_values- 从范围列表中的 Google Sheet 获取值(API

例子:

from airflow.providers.google.suite.hooks.sheets import GSheetsHook
from airflow.operators.python import PythonOperator

def get_data_from_spreadsheet():
    hook = GSheetsHook(
        gcp_conn_id="google_conn_id",
    )
    spreadsheet = hook.get_values(spreadsheet='name', range='my-range' )
   #spreadsheet is list of values from your spreadsheet.
   #add the rest of your code here.


get_data_from_gs = PythonOperator(
    task_id = 'get_data_from_gs',
    python_callable = get_data_from_spreadsheet(link, title)
)
Run Code Online (Sandbox Code Playgroud)