【发布时间】:2021-03-02 17:51:08
【问题描述】:
我正在尝试设置一个脚本,将文件(现在使用 python 请求库)上传到在 Docker (-compose) 容器内运行的 Flask 环境。 python 脚本在管理程序中运行,我也强制它使用相同版本的 python (3.6)。我能够从服务器得到响应,但是我上传的文件是 12Kb,Flask 容器接收到的文件是 2Kb,我不知道出了什么问题。
似乎当我使用 WireShark 捕获 tcp 流时,我也收到了一个 2Kb 的文件,所以我猜请求库应用了一些压缩,但我似乎找不到任何关于这种情况的 documentation。
我试图用文件句柄替换发送代码中的文件元组,但这似乎没有效果。发送不同大小的文件会导致 Flask / Docker 中的文件大小不同。
发送字符串而不是文件处理程序(“1234567890”)会导致文件大小与字符串长度(10 字节)一样大。
将文件打开方法从rb 替换为r 会导致UnicodeDecodeError: 'ascii' codec can't decode byte 0xdf in position 14: ordinal not in range(128) 在requests -> encodings 内引发。
管理程序:send.py
import requests
with open('file.docx', 'rb') as f:
url = 'http://localhost:8081/file'
r = requests.post(url, files={'file': ('file', f, 'multipart/form-data')})
print(r.text)
烧瓶:file.py
@app.route('/file', methods=['POST'])
def parse_from_post():
file = request.files['file']
fn = secure_filename("file.docx") # did this manually instead of getting it from the request for testing reasons
folder = "/app/files/"
fl = os.path.join(folder, fn)
# Removes old file
if os.path.exists(fl):
os.remove(fl)
file.save(fl)
return ""
【问题讨论】:
标签: python flask python-requests