python请求将字符串作为文件发送

标签 python python-requests

在我的代码中,我目前正在分 block 一个文件并将其读取到一个临时文件中,然后将这个临时文件传递到请求中。有没有办法仍然发送这个

with open(full_path, 'r+b') as f:
  i=0
  while True:
  chunk = f.read(max_chunk_size)
  if not chunk:
    break
  with tempfile.TemporaryFile() as t:
    t.write(chunk)
    t.seek(0)
    r = requests.post(endpoint + 'upload_chunk',
                      files={'chunk':t},
                      data={'mod_time':file_update_time,
                            'directory':'/'.join(subdirs),
                            'filename':filename,
                            'chunk_pos':i},
                      auth=auth)
    i+=max_chunk_size

有没有办法将 block 发送到服务器而不将其写入临时文件,然后在 requests.post 中读取这个文件?我更愿意不必更改服务器端代码。我认为不必读取/写入额外的 4 兆字节会提高执行速度。

分 block 文件是必要的;此代码尚未完成。

最佳答案

通读请求 Quickstart page , 在 POST a Multipart-Encoded File 下部分。

在那里你会发现这个:

If you want, you can send strings to be received as files:

>>> url = 'http://httpbin.org/post'
>>> files = {'file': ('report.csv', 'some,data,to,send\nanother,row,to,send\n')}

>>> r = requests.post(url, files=files)
>>> r.text
{
  ...
  "files": {
    "file": "some,data,to,send\\nanother,row,to,send\\n"
  },
  ...
}

请注意,"file" 是服务器期望的文件上传字段的名称。它将对应于以下 HTML:

<input type="file" name="file">

关于python请求将字符串作为文件发送,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24443280/

相关文章:

python - 如何在 Python 请求中禁用 SNI?

python - Discord.py - 检查用户是否具有执行命令的特定角色

python - 如何打印requirement.txt中每个包的安装时间

python - 使用 Pandas 清理 HTML 表格

python - ValueError : illegal value in 4-th argument of internal None when running sklearn LinearRegression(). fit()

python - 如何在 python 的 POST 请求中将 null 作为值传递?

python - 做声明在神社中不起作用

Python 请求 - 从文件中 POST 数据

python - 在启动时创建对象并跨请求共享

python - HTML URL生成下载时如何了解PDF的内容类型