python请求文件上传 [英] python requests file upload

查看:155
本文介绍了python请求文件上传的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Python请求库执行上传文件的简单任务。我搜索了堆栈溢出,没有人似乎有同样的问题,即该文件没有收到服务器:

 导入请求
url ='http://nesssi.cacr.caltech.edu/cgi-bin/getmulticonedb_release2.cgi/post'
files = {'files':open('file.txt', 'rb')}
values = {'upload_file':'file.txt','DB':'photcat','OUT':'csv','SHORT':'short'}
r = requests.post(url,files = files,data = values)

'upload_file'关键字与我的文件名,因为如果我把它留空,它说

 错误 - 您必须选择一个文件上传! 

现在我得到了

 大小字节的文件file.txt上传成功! 
查询服务结果:有0行。

只有当文件为空时才会出现。所以我坚持如何成功发送我的文件。我知道该文件的工作原理,因为如果我去这个网站并手动填写表格,它会返回一个匹配对象的好列表,这正是我所追求的。我真的很感激所有的提示。

一些其他线程相关(但不回答我的问题):

http://docs.python-requests.org/en/latest/user/quickstart/#response-content
<使用请求上传文件并发送额外的数据
http://docs.python-requests.org/en / latest / user / advanced /#body-content-workflow

解决方案

如果 upload_file 应该是文件,使用:

  files = {'upload_file':open(' file.txt','rb')} 
values = {'DB':'photc at','OUT':'csv','SHORT':'short'}

r = requests.post(url,files = files,data = values)

requests 将发送一个包含 upload_file 字段设置为 file.txt 文件的内容。


I'm performing a simple task of uploading a file using Python requests library. I searched Stack Overflow and no one seemed to have the same problem, namely, that the file is not received by the server:

import requests
url='http://nesssi.cacr.caltech.edu/cgi-bin/getmulticonedb_release2.cgi/post'
files={'files': open('file.txt','rb')}
values={'upload_file' : 'file.txt' , 'DB':'photcat' , 'OUT':'csv' , 'SHORT':'short'}
r=requests.post(url,files=files,data=values)

I'm filling the value of 'upload_file' keyword with my filename, because if I leave it blank, it says

Error - You must select a file to upload!

And now I get

File  file.txt  of size    bytes is  uploaded successfully!
Query service results:  There were 0 lines.

Which comes up only if the file is empty. So I'm stuck as to how to send my file successfully. I know that the file works because if I go to this website and manually fill in the form it returns a nice list of matched objects, which is what I'm after. I'd really appreciate all hints.

Some other threads related (but not answering my problem): Send file using POST from a Python script http://docs.python-requests.org/en/latest/user/quickstart/#response-content Uploading files using requests and send extra data http://docs.python-requests.org/en/latest/user/advanced/#body-content-workflow

解决方案

If upload_file is meant to be the file, use:

files = {'upload_file': open('file.txt','rb')}
values = {'DB': 'photcat', 'OUT': 'csv', 'SHORT': 'short'}

r = requests.post(url, files=files, data=values)

and requests will send a multi-part form POST body with the upload_file field set to the contents of the file.txt file.

这篇关于python请求文件上传的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆