【问题标题】:Executing Google Cloud Shell commands from jupyter从 jupyter 执行 Google Cloud Shell 命令
【发布时间】:2019-03-01 12:41:33
【问题描述】:

我需要每天将文件从 FTP 上传到 Google Cloud Storage。我已经设法通过从 FTP 下载文件并上传到 Google Cloud Storage 来使用 Python,但它似乎太重了。所以,我很好奇是否可以通过在 Google Cloud Shell 中执行命令来实现它,或者是否有任何其他可能的解决方案可以以更优化的方式实现它。

from gcloud import storage
from oauth2client.service_account import ServiceAccountCredentials
import os

ftp = ftplib.FTP("ftp_url")
ftp.login('login', 'password')
ftp.cwd("/")


with open('file', 'wb') as f:
    ftp.retrbinary('RETR ' + 'file', f.write)

credentials = ServiceAccountCredentials.from_json_keyfile_dict(
    credentials_dict
)

client = storage.Client(credentials=credentials, project='project_id')

bucket = client.get_bucket('bucket')
blob = bucket.blob('file')
blob.upload_from_filename('file')

【问题讨论】:

  • 除了没有错误处理和使用from_json_keyfile_dict之外,你的代码都很好。您使从 FTP 服务器下载文件和上传 GCS 变得简单。我会为 FTP 文件传输模式添加一个有意的二进制设置。

标签: python python-2.7 google-cloud-platform ftp google-cloud-storage


【解决方案1】:

也许您可以使用"Cloud Storage FUSE" 将 Cloud Storage 存储桶作为文件系统直接挂载到您的 FTP 服务器中,以帮助解决此问题描述中报告的问题。

现在,回答问题的标题,您可以使用以下代码作为示例:

点安装:

!pip install google-cloud
!pip install google-api-python-client
!pip install oauth2client
!pip install google-cloud-bigquery

代码:

import subprocess
import logging
from google.cloud import storage

logger = logging.Logger('catch_all')

def execute_bash(parameters):
    try:
        return subprocess.check_output(parameters)
    except Exception as e: 
       logger.error(e) 
       logger.error('ERROR: Looking in jupyter console for more information')

def example_list_bucket_gcs():
    list_bucket = execute_bash(['gsutil', 'ls']).decode("utf-8").split('\n')
    for bucket in list_bucket:
        print(bucket)

def example_list_bucket_api(client_gcs):
    list_bucket = client_gcs.list_buckets()
    for bucket in list_bucket:
        print(bucket.name)

JSON_FILE_NAME = 'sa_bq.json'
client_gcs = storage.Client.from_service_account_json(JSON_FILE_NAME)
example_list_bucket_api(client_gcs)
example_list_bucket_gcs()

【讨论】:

    猜你喜欢
    • 2019-12-22
    • 2011-06-15
    • 2014-04-21
    • 2014-01-22
    • 2011-03-04
    • 2013-08-25
    • 1970-01-01
    相关资源
    最近更新 更多