【问题标题】:How to upload HTTP API to AWS S3 bucket in JSON File format using Python?如何使用 Python 以 JSON 文件格式将 HTTP API 上传到 AWS S3 存储桶?
【发布时间】:2021-11-03 18:39:59
【问题描述】:

我可以将我的 HTTP API 上传到 S3 存储桶,但没有为其分配任何文件格式。如何将其作为 JSON 文件上传?

import json
import requests
import boto3

s3 = boto3.client('s3', aws_access_key_id='***', aws_secret_access_key='***')

covid_text = requests.get('https://disease.sh/v3/covid-19/continents')

data = covid_text.json()

s3.put_object(Body=json.dumps(data), Bucket='my_bucket', Key='httpsGETdisease.sh/v3/covid-19/continents')

【问题讨论】:

    标签: python json amazon-s3 python-requests boto3


    【解决方案1】:

    这是我在内部使用的用于将文件(通常是 JSON)上传到 S3 的代码的 sn-p。 self.client 是一个缓存属性,相当于上面代码中的boto3.client('s3');只有我为了可重用性而缓存了它,因为它在向同一个存储桶发出多个请求时会更快一些,比如读取上传的文件然后重新上传。

        def upload(self, file_name, bucket, key=None, content_type='application/json'):
            """upload a file (usually a JSON file) to S3"""
            self.client.upload_file(
                file_name, bucket, key or file_name, {'ContentType': content_type})
    

    当我从 S3 下载文件(通常是 JSON 文件)时,类似的代码 sn-p。这里我们只检查对象的内容类型,如果是 JSON,我们加载它并将数据作为 Python list 或 dict 类型返回。否则,我们只是将对象数据作为明文返回。

            content_type = res.get('ContentType', 'application/json')
    
            data = res['Body'].read().decode(encoding)
            if content_type.endswith('json'):
                return json.loads(data)
    
            return data
    

    【讨论】:

    • 谢谢!问题是我没有文件。我只有我提供的 API URL。
    • 啊,我可能错过了。我想你可以继续使用put_object,并且可能会有content_type 参数(我会参考 S3 上的 boto3 文档进行说明)
    • 参考下面put_object 请求的文档,我看到Body=b'bytes'|file,所以它期望Body 是字节。您可以尝试使用covid_text.content 获取字节内容,然后将其作为Body 参数传递?也许那会奏效。 boto3.amazonaws.com/v1/documentation/api/latest/reference/…
    • 另外我看到了一个 ContentType 参数,所以这可能是您想要用来将文件标记为包含 JSON 内容的方法。由于这是一个 API 响应,因此您可以使用来自响应对象 covid_text 本身的相同标头。
    • 我的代码是这样工作的:import json import requests import boto3 s3 = boto3.client('s3', aws_access_key_id='***', aws_secret_access_key='***') covid_text = requests.get('https://disease.sh/v3/covid-19/continents') data = covid_text.json() s3.put_object(Body=json.dumps(data), Bucket='my_bucket', Key='httpsGETdisease.sh/v3/covid-19/continents', ContentType='application/json')
    猜你喜欢
    • 2018-04-25
    • 2019-11-05
    • 1970-01-01
    • 2019-04-28
    • 2021-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-10
    相关资源
    最近更新 更多