简体   繁体   English

Python Django:在内存中创建文件对象,而无需实际创建文件

[英]Python Django : Creating file object in memory without actually creating a file

I have an endpoint where I want to collect the response data and dump it into a file on S3 like this - https://stackoverflow.com/a/18731115/4824482 我有一个端点,我想在其中收集响应数据并将其转储到S3上的文件中,如下所示-https://stackoverflow.com/a/18731115/4824482

This is how I was trying to do it - 这就是我试图做到的方式-

file_obj = open('/some/path/log.csv', 'w+')
file_obj.write(request.POST['data'])

and then passing file_obj to the S3 related code as in the above link. 然后按照上述链接将file_obj传递到S3相关代码。

The problem is that I don't have permissions to create a file on the server. 问题是我没有在服务器上创建文件的权限。 Is there any way I can create a file object just in memory and then pass it to the S3 code? 有什么办法可以在内存中创建文件对象,然后将其传递给S3代码?

Probably that's duplicate question of How to upload a file to S3 without creating a temporary local file . 可能是重复的问题,即如何在不创建临时本地文件的情况下将文件上传到S3 You would find best suggestion by checking out answers to that question. 您可以通过查看该问题的答案找到最佳建议。

Shortly the answer is code below: 很快答案是下面的代码:

from boto.s3.key import Key
k = Key(bucket)
k.key = 'yourkey'
k.set_contents_from_string(request.POST['data'])

Try tempfile https://docs.python.org/2/library/tempfile.html 尝试tempfile https://docs.python.org/2/library/tempfile.html

f = tempfile.TemporaryFile()
f.write(request.POST['data'])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM