软硬件环境
ubuntu 19.04 64bit
anaconda3 with python 3.7.3
pycurl 7.43.0.2
简介
CURL
是一个基于URL
进行数据传输的命令行工具,使用C
语言编写,支持http
,https
,ftp
,telnet
,file
,ldap
等常见网络传输协议,具有速度快、体积小、效率高等特点。libcurl
是对应的C
库。pycurl
是对应的python
库`。
安装pycurl
anaconda3
中已经内置了pycurl
。如果你使用的是其它环境,可以通过pip
来安装
pip install pycurl
或者下载源码进行安装
tar xvf pycurl-7.65.3.tar.gz
cd pycurl-7.65.3
sudo python setup.py install
测试pycurl
是否安装成功,命令行执行python
import pycurl
print(pycurl.version)
HTTP GET操作
这里的示例,实现一个从web server
上下载一个文件到本地的功能,利用pycurl
这个模块,直接上代码
import pycurlPYCURL_CONNECTTIMEOUT = 30
PYCURL_TIMEOUT = 300
PYCURL_DOWNLOADURL = "http://127.0.0.1/test.mp4"
PYCURL_DOWNLOAD_FILE = "download.file"fp = open(PYCURL_DOWNLOAD_FILE,'wb+')def pycurl_writeFile(buffer):fp.write(buffer)def pycurl_download(url):# 全局初始化pycurl.global_init(pycurl.GLOBAL_ALL)# 实例化对象c = pycurl.Curl()# 参数设置c.setopt(pycurl.URL, url)c.setopt(pycurl.WRITEDATA, fp)c.setopt(pycurl.WRITEFUNCTION, pycurl_writeFile)c.setopt(pycurl.NOPROGRESS, 0)c.setopt(pycurl.CONNECTTIMEOUT, PYCURL_CONNECTTIMEOUT)c.setopt(pycurl.TIMEOUT, PYCURL_TIMEOUT)c.setopt(pycurl.VERBOSE, 1)# 执行c.perform()# 资源回收c.close()fp.close()if __name__ == '__main__':pycurl_download(PYCURL_DOWNLOADURL)
上述代码执行结果
HTTP POST操作
首先我们准备搭建个web
服务,这里我们使用flask
这个框架,post
接口接受一个json
并打印出来,然后返回一个字符串,如下
from flask import Flask, requestflask_app = Flask(__name__)@flask_app.route('/processPOSTJSON', methods=['POST'])
def processPOSTJSON():'''处理客户端上传的JSON数据:return:'''content = request.get_json()print(content)return "success"
启动服务
# flask_server.py是上述文件的名字
export FLASK_APP=flask_server.py
flask run
接着使用pycurl
构建客户端的代码,如下
import pycurl
import jsonURL = "http://127.0.0.1:5000/processPOSTJSON"c = pycurl.Curl()
c.setopt(pycurl.URL, URL)
c.setopt(pycurl.HTTPHEADER, ['Content-Type: application/json'])
data = json.dumps({"name": "xgx", "sex": "male", "country": "china"})
c.setopt(pycurl.POST, 1)
c.setopt(pycurl.POSTFIELDS, data)
c.setopt(pycurl.VERBOSE, 1)
c.perform()
c.close()
运行客户端的代码,可以看到服务端返回过来的字符串success
,同时在服务端,json
的值也被打印了出来。由于我们在flask
中使用了get_json
方法,因此,在客户端必须要设置HTTPHEADER
,否则,会打印出None
参考资料
https://curl.haxx.se/
https://github.com/curl/curl
https://stackoverflow.com/questions/47033632/send-json-request-to-flask-via-curl