如何使用带有 Python 的 Google Cloud Functions 将列表写入 Google Cloud Storage 中的文件

赛义德·巴尔吉

我正在尝试使用 Cloud Functions 将列表成员写入 Cloud Storage 存储桶中的文件。

我发现这个页面显示了如何将文件上传到我的存储桶,但我需要的是遍历列表中的成员并将它们写入 Cloud Storage 中的文件。

我需要能够使用从我的 Google Cloud SQL 数据库读取的 Cloud Functions 来完成此操作。我希望能够将 PostreSQL 数据库中某些表中的数据作为 Cloud Storage 中的文件存储。

谢谢。

赛义德·巴尔吉

我设法使用以下 python 代码完成了它:

import datetime
import logging
import os
import sqlalchemy
from google.cloud import storage
import pandas as pd

# Remember - storing secrets in plaintext is potentially unsafe. Consider using
# something like https://cloud.google.com/kms/ to help keep secrets secret.
db_user = "<DB_USER>"#os.environ.get("DB_USER")
db_pass = "<DB_PASS>"#os.environ.get("DB_PASS")
db_name = "<DB_NAME>"#os.environ.get("DB_NAME")
cloud_sql_connection_name = "<Cloud SQL Instance Connection Name>"#os.environ.get("CLOUD_SQL_CONNECTION_NAME")
logger = logging.getLogger()

# [START cloud_sql_postgres_sqlalchemy_create]
db = sqlalchemy.create_engine(
    # Equivalent URL:
    # postgres+pg8000://<db_user>:<db_pass>@/<db_name>?unix_sock=/cloudsql/<cloud_sql_instance_name>/.s.PGSQL.5432
    sqlalchemy.engine.url.URL(
        drivername='postgres+pg8000',
        username=db_user,
        password=db_pass,
        database=db_name,
        query={
            'unix_sock': '/cloudsql/{}/.s.PGSQL.5432'.format(
                cloud_sql_connection_name)
        }
    ),
    # ... Specify additional properties here.
    pool_size=5,
    max_overflow=2,
    pool_timeout=30,  # 30 seconds
    pool_recycle=1800,  # 30 minutes
)

def read_source_data(request):
    bucket_name = <YOUR_BUCKET_NAME>
    folder_name = "sample_files"
    file_name = "test.txt"

    with db.connect() as conn:
        sales_records = conn.execute(
            "SELECT * FROM sales;"
        ).fetchall()

    if len(sales_records) > 0:
        #for val in sales_records:
            #print(val)
        df = pd.DataFrame(sales_records)
        df.columns = sales_records[0].keys()
        create_file(bucket_name, "sample_files/test.txt", df)
        return "Done!"
    else:
        print("Nothing!")
        return "Nothing!"

def create_file(bucketname, path, records_read):
  storage_client = storage.Client()
  bucket = storage_client.get_bucket(bucketname)
  blob = storage.Blob(
        name=path,
        bucket=bucket,
    )

  content = records_read.to_csv(index=False)#'\n'.join(map(str, records_read))

  blob.upload_from_string(
        data=content,
        content_type='text/plain',
        client=storage_client,
    )

我从多个代码片段中将其拼接在一起,作为非 Python 开发人员,我很确定有更好的方法来完成这项工作。然后我使用

gcloud deployment-manager deployments  create

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

使用Python脚本中的Google Cloud Functions从Google Cloud Storage中读取CSV

如何使用Deployment Manager将文件写入Google Cloud Storage?

从Cloud Function(Python)写入Google Cloud Storage

从Google Cloud Function(Python)将新文件写入Google Cloud Storage存储桶

如何使用Google Cloud Dataflow将压缩文件写入Google Cloud Storage?

使用Cloud Functions将文件从Google Cloud Storage传输到Windows VM实例

使用Google Cloud Dataflow合并Google Cloud Storage中的文件

如何从Google Cloud Functions NodeJS连接到Google Cloud Storage

如何通过Google App Engine中的应用程序将文件写入Google Cloud Storage?

Google Cloud Functions中的Python

如何从 Google Cloud Functions 中删除文件

如何使用Google Cloud Function将文件从Cloud Storage存储桶中推送到实例中?

如何使用python遍历Google Cloud Storage子目录中的所有文件名?

如何使用Google Cloud Python API将目录复制到Google Cloud Storage?

使用Google App Engine(Python)将文件上传到Google Cloud Storage

无法使用Google Cloud Storage和Cloud Functions for Firebase下载文件

如何从python函数登录Google Cloud Storage?

使用DoFn使用Cloud Dataflow从PubSub写入Google Cloud Storage

如何使用Node.js获取Google Cloud Storage文件夹中的文件列表?

Google Storage // Cloud Function // Python 修改 Bucket 中的 CSV 文件

如何从Google Cloud Storage解密文件?

使用Flask将文件上传到Google Cloud Storage

使用 Codeigniter 将文件上传到 Google Cloud Storage

使用 For 循环将多个文件上传到 Google Cloud Storage

如何将 Google Data Prep 用于 Google Cloud Storage 中的多个文件?

使用Google Cloud Console在Google Cloud Storage中的文件夹之间移动文件

如何使用带有校验和控制的Java从Google Cloud Storage下载大文件

Google Cloud Storage中的Concat Avro文件

如何通过Cloud Functions将文件上传到Cloud Storage并使用Firestore控制对Cloud Storage的访问?