【发布时间】:2019-12-04 15:32:13
【问题描述】:
在 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"}]
当使用邮递员在表单数据中直接将文件发布到该 api 时,它按预期工作:
print(file) # <FileStorage: u'file.pdf' ('application/pdf')>
print(os.path.getsize(path)) #8541
有关如何解决此问题的任何帮助,即将InMemoryUploadedFile 类型转换为普通 REST api 可以理解的内容?或者只是添加正确的标题?
【问题讨论】:
-
能否包含相关的 Flask 视图,以查看文件在接收端是如何处理的?
-
它包含 self.request.FILES
-
@kristaps 我用细节编辑了这个问题。
-
两台服务器之间是否有任何代理,可能会改变对 Flask 服务器的请求?
-
不,两台服务器是两个独立的docker容器
标签: python django django-rest-framework