Python 3脚本上传文件到REST URL(多部分请求)
我刚开始学习Python,现在用的是Python 3.2。我想写一个Python脚本,让用户可以从他们的电脑上选择一个文件(比如图片文件),然后通过REST的方式把这个文件提交到服务器。这个Python脚本在被调用时应该能够访问一个REST的URL,并提交文件。
这有点像浏览器上传文件时使用的多部分POST请求,但我想通过Python脚本来实现这个功能。
如果可以的话,我希望不使用任何外部库,尽量保持这个Python脚本简单,只用Python自带的功能。
有没有人能指导我一下?或者分享一些示例脚本,帮助我实现这个目标?
3 个回答
0
你也可以使用 unirest。下面是一个示例代码:
import unirest
# consume async post request
def consumePOSTRequestSync():
params = {'test1':'param1','test2':'param2'}
# we need to pass a dummy variable which is open method
# actually unirest does not provide variable to shift between
# application-x-www-form-urlencoded and
# multipart/form-data
params['dummy'] = open('dummy.txt', 'r')
url = 'http://httpbin.org/post'
headers = {"Accept": "application/json"}
# call get service with headers and params
response = unirest.post(url, headers = headers,params = params)
print "code:"+ str(response.code)
print "******************"
print "headers:"+ str(response.headers)
print "******************"
print "body:"+ str(response.body)
print "******************"
print "raw_body:"+ str(response.raw_body)
# post sync request multipart/form-data
consumePOSTRequestSync()
你可以查看这个帖子,了解更多细节:http://stackandqueue.com/?p=57
5
用RESTful的方式上传图片,如果你知道图片的链接,可以使用PUT
请求。
#!/usr/bin/env python3
import http.client
h = http.client.HTTPConnection('example.com')
h.request('PUT', '/file/pic.jpg', open('pic.jpg', 'rb'))
print(h.getresponse().read())
upload_docs.py这个文件里有个例子,教你怎么用基本的HTTP认证上传文件,格式是multipart/form-data
。这个例子支持Python 2.x和Python 3。
你也可以使用requests
库来以multipart/form-data
的格式上传文件:
#!/usr/bin/env python3
import requests
response = requests.post('http://httpbin.org/post',
files={'file': open('filename','rb')})
print(response.content)
14
你需要用到Requests这个库。你可以通过输入 pip install requests
来安装它。
>>> url = 'http://httpbin.org/post'
>>> files = {'file': open('report.xls', 'rb')}
>>> r = requests.post(url, files=files)