[英]Curl Equivalent in Python
I have a python program that takes pictures and I am wondering how I would write a program that sends those pictures to a particular URL. 我有一个python程序拍照,我想知道如何编写一个程序,将这些图片发送到特定的URL。
If it matters, I am running this on a Raspberry Pi. 如果重要的话,我在Raspberry Pi上运行它。
(Please excuse my simplicity, I am very new to all this) (请原谅我的简单,我对这一切都很新)
I've been using the requests package as well. 我一直在使用请求包。 Here's an example POST from the requests documentation.
这是请求文档中的示例POST 。
If you are feeling that you want to use CURL, try PyCurl . 如果您觉得要使用CURL,请尝试使用PyCurl 。
Install it using: 安装使用:
sudo pip install pycurl
sudo pip安装pycurl
Here is an example of how to send data using it: 以下是如何使用它发送数据的示例:
import pycurl
import json
import urllib
import cStringIO
url = 'your_url'
first_param = '12'
dArrayData = [{'data' : 'first'}, {'data':'second'}]
json_to_send = json.dumps(dArrayData, separators=(',',':'), sort_keys=False)
curlClient = pycurl.Curl()
curlClient.setopt(curlClient.USERAGENT, 'curl-user-agent')
# Sets the url of the service
curlClient.setopt(curlClient.URL, url)
# Sets the request to be of the type POST
curlClient.setopt(curlClient.POST, True)
# Sets the params of the post request
send_params = 'first_param=' + first_param + '&data=' + urllib.quote(json_to_send)
curlClient.setopt(curlClient.POSTFIELDS, send_params)
# Setting the buffer for the response to be written to
bufResponse = cStringIO.StringIO()
curlClient.setopt(curlClient.WRITEFUNCTION, bufResponse.write)
# Setting to fail on error
curlClient.setopt(curlClient.FAILONERROR, True)
# Sets the time out for the connections
curlClient.setopt(pycurl.CONNECTTIMEOUT, 25)
curlClient.setopt(pycurl.TIMEOUT, 25)
response = ''
try:
# Performs the operation
curlClient.perform()
except pycurl.error as err:
errno, errString = err
print '========'
print 'ERROR sending the data:'
print '========'
print 'CURL error code:', errno
print 'CURL error Message:', errString
else:
response = bufResponse.getvalue()
# Do what ever you want with the response.. Json it or what ever..
finally:
curlClient.close()
bufResponse.close()
请求库是最受支持和高级的方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.