当前位置:   article > 正文

python - requests 发送带文件请求_requests.post(gen_url, files=files)

requests.post(gen_url, files=files)

python - requests 发送带文件请求

Max.Bai

2017-08


1. requests发送文件功能

Requests 使得上传多部分编码文件变得很简单

  1. >>> url = 'http://httpbin.org/post'
  2. >>> files = {'file': open('report.xls', 'rb')}
  3. >>> r = requests.post(url, files=files)
  4. >>> r.text
  5. {
  6. ...
  7. "files": {
  8. "file": "<censored...binary...data>"
  9. },
  10. ...
  11. }
你可以显式地设置文件名,文件类型和请求头:

  1. >>> url = 'http://httpbin.org/post'
  2. >>> files = {'file': ('report.xls', open('report.xls', 'rb'), 'application/vnd.ms-excel', {'Expires': '0'})}
  3. >>> r = requests.post(url, files=files)
  4. >>> r.text
  5. {
  6. ...
  7. "files": {
  8. "file": "<censored...binary...data>"
  9. },
  10. ...
  11. }
如果你想,你也可以发送作为文件来接收的字符串:

  1. >>> url = 'http://httpbin.org/post'
  2. >>> files = {'file': ('report.csv', 'some,data,to,send\nanother,row,to,send\n')}
  3. >>> r = requests.post(url, files=files)
  4. >>> r.text
  5. {
  6. ...
  7. "files": {
  8. "file": "some,data,to,send\\nanother,row,to,send\\n"
  9. },
  10. ...
  11. }

如果你发送一个非常大的文件作为 multipart/form-data 请求,你可能希望将请求做成数据流。默认下 requests 不支持, 但有个第三方包 requests-toolbelt 是支持的。你可以阅读 toolbelt 文档 来了解使用方法。


2. requests发送多个文件请求

只要把文件设到一个元组的列表中,其中元组结构为 (form_field_name, file_info)
按照如下格式发送数据

  1. data = {'ts_id': tsid}
  2. files = [('images',('1.png', open('/home/1.png', 'rb'),'image/png')),('images',('2.png', open('/home/2.png', 'rb'),'image/png'))]
  3. r = requests.post(url, data=data, files=files)
  4. print r.text

3. Django 接收文件

附带介绍Django里面如何接收图片文件数据:
读取文件:

  1. from werkzeug.utils import secure_filename
  2. def upload_file(request):
  3. if request.method == 'POST':
  4. uploaded_files = request.FILES.getlist("images")
  5. try:
  6. for file in uploaded_files:
  7. filename = secure_filename(file.name)
  8. handle_uploaded_file(os.path.join(ft, filename), file)
  9. except Exception as e:
  10. result_json = {"msg": str(e)}
  11. result = {
  12. 'json': result_json
  13. }
  14. return JsonResponse(result, safe=False)

保存文件:

  1. def handle_uploaded_file(filename, f):
  2. try:
  3. destination = open(filename, 'wb+')
  4. for chunk in f.chunks():
  5. destination.write(chunk)
  6. destination.close()
  7. except Exception as e:
  8. raise Exception('save %s failed: %s' % (filename, str(e)))


requests 官网:http://docs.python-requests.org/zh_CN/latest/user/quickstart.html#post-multipart-encoded




声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/从前慢现在也慢/article/detail/172782
推荐阅读
相关标签
  

闽ICP备14008679号