在 Django Rest 框架中,我想将作为 InMemoryUploadedFile
接收的文件在收到后立即发布到不同的服务器。
听起来很简单,但是 request.post()
函数似乎无法正确发送这样的文件:
def post(self, request, *args, **kwargs):
data = request.data
print(data)
# <QueryDict: {'file': [<InMemoryUploadedFile: myfile.pdf (application/pdf)>]}>
endpoint = OTHER_API_URL + "/endpoint"
r = requests.post(endpoint, files=data)
我的其他服务器收到带有文件名的请求(通过flask),但不包含内容:
@app.route("/endpoint", methods=["POST"])
def endpoint():
if flask.request.method == "POST":
# I removed the many checks to simplify the code
file = flask.request.files['file']
path = os.path.join(UPLOAD_FOLDER, file.filename)
file.save(path)
print(file) #<FileStorage: u'file.pdf' (None)>
print(os.path.getsize(path)) #0
return [{"response":"ok"}]
当使用 postman 将文件直接发布到表单数据中的 api 时,它按预期工作:
print(file) # <FileStorage: u'file.pdf' ('application/pdf')>
print(os.path.getsize(path)) #8541
有关如何解决此问题(即将 InMemoryUploadedFile
类型转换为普通 REST api 可以理解的内容)的任何帮助吗?或者也许只是添加正确的标题?
最佳答案
我必须解决在 Python 3 中将上传文件从 Django 前端网站传递到 Django 后端 API 时出现的问题。 InMemoryUploadedFile 的实际文件数据可以通过对象的 .file 属性的 .getvalue() 方法访问。
path="path/to/api"
in_memory_uploaded_file = request.FILES['my_file']
io_file = in_memory_uploaded_file.file
file_value = io_file.getvalue()
files = {'my_file': file_value}
make_http_request(path, files=files)
并且可以缩短
file = request.FILES['my_file'].file.getvalue()
files = {'my_file': file}
在此之前,尝试发送 InMemoryUploadFile 对象、文件属性或 read() 方法的结果都被证明在到达 API 时会发送一个空白/空文件。
关于python - Django - 将 InMemoryUploadedFile 发布到外部 REST api,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51189487/