我正在尝试从我的 Django 应用程序将HTML字符串作为PDF文件上传到 GCS。
import google, os
from google.cloud import storage
class GcpHelper:
def __init__(self, bucket_name):
self.service_account_json_path = 'google_auth.json'
storage_client = storage.Client.from_service_account_json(self.service_account_json_path)
try:
self.__bucket_name = bucket_name
self.bucket = storage_client.get_bucket(bucket_name)
except Exception as err:
logger.error("Error {} while connecting to bucket {}!".format(str(err), bucket_name))
def put_data_in_bucket(self, file_name, data, content_type="application/pdf"):
"""Uploads data to gcp bucket"""
try:
blob = self.bucket.blob(file_name)
blob.upload_from_string(data, content_type=content_type)
return True
except Exception as err:
logger.error("Unable to upload file {} due to {}".format(file_name, str(err)))
raise Exception("Write to gcp failed!")
gcp_helper = GcpHelper('bucket_name')
voucher_html = open('voucher_test.html').read()
#some operations on voucher_html string here
gcp_helper.put_data_in_bucket("booking/voucher.pdf", voucher_html)
我试图以某种方式直接上传字符串,而不是将其保存为 PDF 文件然后上传文件。(如果没有任何效果,那么将不得不这样做)
但当然这不起作用,因为上传的 PDF 文件已损坏。我希望blob.upload_from_string能够处理所需的任何格式/编码。但看起来,事实并非如此。;)