我想创建一个简单的API,为POST请求提供一个唯一的终结点,该终结点将json作为参数,然后将此json存储在存储桶中到Google存储。
要完成这项工作,我正在使用Django框架。
我想了解有关如何构建api应用程序以及在哪里存储gcloud凭据的最佳实践和模式。 (顺便说一句,我愿意接受其他(更好的)方法/ technos / frameworks / patterns做此类API的建议)
目前,我正在使用google.cloud软件包,并将所有内容放入 apps.py 文件中;
class ApiConfig(AppConfig):
storage_client = storage.Client.from_service_account_json('credentials.json')
bucket = storage_client.get_bucket('bucket_name')
然后在 views.py 文件中,我使用apps.py文件中定义的存储区进行发布功能定义。
class upload_to_bucket(APIView):
def post(self, request):
if request.method == 'POST':
json_file = json.loads(request.body)
blob = ApiConfig.bucket.blob(json_file['name'])
blob.upload_from_string(
data=json.dumps(json_file['json_file_to_upload']),
content_type='application/json'
)
return Response(json_file['json_file_to_upload'])
感谢您对我的帮助
答案 0 :(得分:0)
您可以使用Secrets Manager存储凭据,但是除此之外,我认为没有问题。
答案 1 :(得分:0)
如果托管应用程序,则不需要服务帐户密钥文件。您可以使用ADC (Application Default Credential)。
在python中,对于存储API,您可以将其用作described in the documentation
storage_client = storage.Client()
像这样,您不需要任何服务帐户。在本地,执行gcloud auth application-default login
以将您自己的凭据加载为默认凭据,并在代码中使用相同的默认构造函数。