【发布时间】:2021-10-21 13:09:42
【问题描述】:
我有一个云函数,旨在通过 API 调用创建 CSV,然后将该 CSV 发送到 Cloud Storage。
这是我的代码:
import requests
import pprint
import pandas as pd
from flatsplode import flatsplode
import csv
import datetime
import schedule
import time
import json
import numpy as np
import os
import tempfile
from google.cloud import storage
api_url = 'https://[YOUR_DOMAIN].com/api/v2/[API_KEY]/keywords/list?site_id=[SITE_ID][&start={start}][&results=100]&format=json'
def export_data(url):
response = requests.get(url) # Make a GET request to the URL
payload = response.json() # Parse `response.text` into JSON
pp = pprint.PrettyPrinter(indent=1)
# Use the flatsplode package to quickly turn the JSON response to a DF
new_list = pd.DataFrame(list(flatsplode(payload)))
# Drop certain columns from the DF
idx = np.r_[1:5,14:27,34,35]
new_list = new_list.drop(new_list.columns[idx], axis=1)
# Create a csv and load it to google cloud storage
new_list = new_list.to_csv('/tmp/temp.csv')
def upload_blob(bucket_name, source_file_name, destination_blob_name):
storage_client = storage.Client()
bucket = storage_client.get_bucket(bucket_name)
blob = bucket.blob(destination_blob_name)
blob.upload_from_file(source_file_name)
message = "Data for CSV file" # ERROR HERE
csv = open(new_list, "w")
csv.write(message)
with open(new_list, 'r') as file_obj:
upload_blob('data-exports', file_obj, 'data-' + str(datetime.date.today()) + '.csv')
export_data(api_url)
我尝试将文件设为/tmp 格式,以便将其写入存储,但没有取得多大成功。 API 调用就像一个魅力,我能够在本地获取 CSV。上传到云存储是我得到错误的地方。
非常感谢任何帮助!
【问题讨论】:
-
欢迎堆栈溢出!你能告诉我们更多关于出了什么问题的信息吗?具体来说,full traceback 或您看到的任何日志都会非常有帮助。
标签: python pandas google-cloud-platform google-cloud-functions google-cloud-storage