【问题标题】:Using Python requests for automatic file uploading to Flask environment使用 Python 请求自动将文件上传到 Flask 环境
【发布时间】: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


    【解决方案1】:

    问题在于文件大小,python 请求不直接处理。我使用requests_toolbelt 包中的MultipartEncoder 来封装文件,而不是直接在请求后调用中插入文件。

    管理程序:send.py

    import requests
    from requests_toolbelt import MultipartEncoder
    
    with open('file.docx', 'rb') as f:
        url = 'http://localhost:8081/file'
        
        m = MultipartEncoder(fields={
            "file": ("file.docx", f)
        })
    
        r = requests.post(url, data=m, headers={'Content-Type': m.content_type})
        print(r.text)
    
    

    我实际上找到了这个结果from another post on SO,请参阅链接到https://toolbelt.readthedocs.io/...的问题的第一条评论。

    【讨论】:

      猜你喜欢
      • 2017-09-02
      • 1970-01-01
      • 2016-11-10
      • 2021-12-27
      • 1970-01-01
      • 1970-01-01
      • 2020-02-29
      • 1970-01-01
      • 2017-10-11
      相关资源
      最近更新 更多