python - 使用实际文件从 s3 模拟下载文件
问题描述
我想编写一个测试来模拟从 s3 下载一个函数,并用我机器上存在的实际文件在本地替换它。我从这篇文章中获得了灵感。思路如下:
from moto import mock_s3
import boto3
def dl(src_f, dest_f):
s3 = boto3.resource('s3')
s3.Bucket('fake_bucket').download_file(src_f, dest_f)
@mock_s3
def _create_and_mock_bucket():
# Create fake bucket and mock it
bucket = "fake_bucket"
# We need to create the bucket since this is all in Moto's 'virtual' AWS account
file_path = "some_real_file.txt"
s3 = boto3.client("s3", region_name="us-east-1")
s3.create_bucket(Bucket=bucket)
s3.put_object(Bucket=bucket, Key=file_path, Body="")
dl(file_path, 'some_other_real_file.txt')
_create_and_mock_bucket()
现在some_other_real_file.txt
存在,但它不是some_real_file.txt
. 关于如何做到这一点的任何想法?
解决方案
如果您的系统上已存在“some_real_file.txt”,则应改用upload_file: https ://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/s3.html#S3.Client.upload_file
对于您的示例:
file_path = "some_real_file.txt"
s3 = boto3.client("s3", region_name="us-east-1")
s3.create_bucket(Bucket=bucket)
s3_resource = boto3.resource('s3')
s3_resource.meta.client.upload_file(file_path, bucket, file_path)
您的代码当前在 S3 中创建了一个空文件(因为 Body=""),这正是下载到“some_other_real_file.txt”的内容。请注意,如果您更改 Body 参数以在其中包含一些文本,则该确切内容将下载到“some_other_real_file.txt”。
推荐阅读
- flutter - 构建失败,出现异常 - 'dart:html'
- ios - 如何在 Xcode 崩溃日志系统中获取崩溃原因?
- python - 在 pip 安装 nbinteract 后,打开 Jupyter-Notebook 时出现内部服务器错误
- voximplant - 加入独立的 VoxImplant 会议
- mysql - 在 Laravel Migrations 中存储时区的最佳方法是什么
- flutter - 在颤振中执行异步代码时出现问题
- java - 最终变量是否会随着时间的推移而改变其值?
- android - 在 Android Studio 中创建后立即动态添加的片段崩溃
- r - 考虑模型中的空间自相关
- javascript - Canvas 内的 HTML 文本