如何使用 python 请求库验证 POST 文件传输?

How to verify POST file transfer with python requests library?

我正在使用 python requests 库的会话功能从远程服务器请求动态生成的图像并将它们写入文件。远程服务器通常不可靠,会以 html 文档或图像片段作为响应。验证内容确实是正确格式(不是 html)并且已完全加载的最佳方法是什么? (我的格式是png和csv)我的代码示例如下:

import requests
ses = requests.Session()
data = ses.get("http://url")
localDest = os.path.join("local/file/path")
with open(localDest,'wb') as f:
   for chunk in data.iter_content()
      f.write(chunk)

我将如何修改此代码以检查它的格式是否正确并且是一个完整的文件?

您有两个选择:

  1. 如果服务器在 headers 中提供了有关内容的正确信息,请检查内容类型或内容长度是否无效。

  2. 如果服务器在内容类型方面撒谎或将内容长度设置为不完整图像的大小,请随后验证内容。

以下两者:

import imghdr
import os
import os.path
import requests
import shutil

ses = requests.Session()
r = ses.get("http://url", stream=True)
localDest = os.path.join("local/file/path")

if r.status_code == 200:
    ctype = r.headers.get('content-type', '')
    if ctype.partition('/')[0].lower() != 'image':
        raise ValueError('Not served an image')

    clength = r.headers.get('content-length')
    clength = clength and int(clength)

    with open(localDest, 'wb') as f:
        r.raw.decode_content = True
        shutil.copyfileobj(r.raw, f)        

    if clength and os.path.getsize(localDest) != clength:
        os.remove(localDest)
        raise ValueError('Served incomplete response')

    image_type = imghdr.test(localDest)
    if image_type is None:
        os.remove(localDest)
        raise ValueError('Not served an image')

您还可以安装 Pillow 并进一步验证图像。