Rob*_*ool 4 python django django-rest-framework
在 Django Rest Framework 中,我想在收到文件后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)
Run Code Online (Sandbox Code Playgroud)
我的另一台服务器接收请求(通过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"}]
Run Code Online (Sandbox Code Playgroud)
使用邮递员将文件直接发布到表单数据中的 api 时,它按预期工作:
print(file) # <FileStorage: u'file.pdf' ('application/pdf')>
print(os.path.getsize(path)) #8541
Run Code Online (Sandbox Code Playgroud)
有关如何解决此问题的任何帮助,即将InMemoryUploadedFile类型转换为普通 REST api 可以理解的内容?或者也许只是添加正确的标题?
我必须解决这个问题,将上传的文件从 Django 前端网站传递到 Python 3 中的 Django 后端 API。可以通过对象的 .file 属性的 .getvalue() 方法访问 InMemoryUploadedFile 的实际文件数据。
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)
Run Code Online (Sandbox Code Playgroud)
并且可以缩短
file = request.FILES['my_file'].file.getvalue()
files = {'my_file': file}
Run Code Online (Sandbox Code Playgroud)
在此之前,尝试发送 InMemoryUploadFile 对象、文件属性或 read() 方法的结果都被证明在到达 API 时发送了一个空白/空文件。
| 归档时间: |
|
| 查看次数: |
2486 次 |
| 最近记录: |