python request上传多个文件和其他字段

发布时间 2023-09-05 12:58:45作者: 西北逍遥

使用 requests 库可以方便地上传多个文件和其他字段。当使用Python的requests.post函数时,您可以在其中添加异常处理来捕获可能的网络错误或HTTP错误。

 

import requests

url = 'http://cbim.com/upload'
files = {'file1': ('file1.txt', open('file1.txt', 'rb'), 'text/plain'),
          'file2': ('file2.txt', open('file2.txt', 'rb'), 'text/plain')}
data = {'field1': 'value1', 'field2': 'value2'}

try:
    response = requests.post(url, files=files, data=data)
    response.raise_for_status()  # 检查响应状态码
    # 处理响应数据
    print(response.text)
except requests.exceptions.RequestException as e:
    # 处理网络请求异常
    print("请求异常:", e)
except requests.exceptions.HTTPError as e:
    # 处理HTTP错误
    print("HTTP错误:", e)
except Exception as e:
    # 处理其他异常
    print("其他异常:", e)
finally:
    # 关闭文件等资源
    for key, value in files.items():
        if value[1]:
            value[1].close()

 

在上面的代码中,使用try-except语句来捕获可能的异常。requests.exceptions.RequestException用于捕获一般的网络请求异常,requests.exceptions.HTTPError用于捕获HTTP错误,而Exception用于捕获其他未列出的异常。在except块中,可以根据需要编写处理异常的代码。

请注意,在finally块中,关闭了上传的文件,以确保释放资源。这是推荐的最佳实践,即使在发生异常的情况下也要确保资源的正确关闭。

 

#####################################