我目前正在使用一个生成 CSV 文件作为其输出的 API,检索它们的唯一方法是运行
request.get
,例如:
raw_report_data = requests.get(report_url).content.decode('utf-8')
然后我们将这些文件上传到 GCP 云存储,根据 GCP 文档,我们有多种执行此操作的方法。
我希望避免在本地下载整个报告,然后将其上传到我们的 GCP 存储桶。我知道
requests.get
允许 stream=True
参数,它会逐渐下载内容,但我无法使其与云存储的“流上传”一起使用。
这是我想要做的事情的代码片段。我使用虚拟 CSV 来 简化API部分,这样我们就可以专注于问题
import requests
from google.cloud import storage
url = "https://people.sc.fsu.edu/~jburkardt/data/csv/addresses.csv"
# GCP info
client = storage.Client(project="my-project")
bucket = client.get_bucket('my-bucket')
target_blob = bucket.blob("test/report_01.csv")
with requests.get(url, stream=True) as f:
target_blob.upload_from_file(f)
对于此代码,我收到以下错误..
属性错误:“响应”对象没有属性“告诉”
我认为我正在尝试加入两个不相容的事物,但我很感激任何想法,即使它告诉我这是不可能完成的。
额外:
file.read()
方法,并且就我而言,它上传前阅读整个文档。我的愿望是在下载内容时上传内容,以避免不必要地使用本地存储。您收到该错误是因为您使用 Python 中的
requests
库检索的对象没有像 tell()
这样的属性或方法。
根据此文档,您可以使用
response.text
从服务器读取内容响应。如果您处理 JSON 格式的数据,也可以使用 response.json()
。如果您想获取数据的原始字节流,请在发出请求时首先使用 response.raw
并设置 stream=True
。
由于您正在使用 upload_from_file 进行流上传,因此您可以尝试在代码中使用
response.raw
。这是一个例子:
import requests
from google.cloud import storage
url = "https://people.sc.fsu.edu/~jburkardt/data/csv/addresses.csv"
# GCP info
client = storage.Client(project="my-project")
bucket = client.get_bucket('my-bucket')
target_blob = bucket.blob("test/report_01.csv")
with requests.get(url, stream=True) as f:
target_blob.upload_from_file(f.raw)