博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[Python]-使用Requests进行HTTP请求与文件上传下载
阅读量:2056 次
发布时间:2019-04-28

本文共 3685 字,大约阅读时间需要 12 分钟。

文章目录

requests库是基于urllib编写的,方便HTTP请求的python库。

requests模块

要使用requests模块,就需要先引入import requests

主要方法

requests模块中主要包括以下方法:

方法 解释
requests.request() 构造一个请求,支持以下各种方法
requests.get() 获取html的主要方法
requests.head() 获取html头部信息的主要方法
requests.post() 向html网页提交post请求的方法
requests.put() 向html网页提交put请求的方法
requests.patch() 向html提交局部修改的请求
requests.delete() 向html提交删除请求

请求参数

以get为例

  • 定义为:def get(url, params=None, **kwargs)
  • 一般调用为:requests.get(url=srvUrl, params=param, headers=header)

requests请求一般有如下一些参数:

  • url:请求服务器地址;
  • params:字典或字节序列形式的请求参数(请求地址中?后面的键值对参数);
  • data:字典,字节序或文件对象;向服务器提交的数据内容;
  • json:json格式的数据(与data=json.dumps(jsBody)等价);
  • headers:字典,请求头信息;
  • cookies:字典或CookieJar,只从http中解析cookie;
  • auth:元组,支持http认证功能;
  • files:字典,向服务器上传文件;
  • timeout:设定超时秒数;
  • proxies:字典,设定访问代理服务器;
  • allow_redirects: 开关, 表示是否允许对url进行重定向, 默认为True。
  • stream: 开关, 指是否对获取内容进行立即下载, 默认为True。
  • verify:开关, 用于认证SSL证书, 默认为True。
  • cert: 用于设置保存本地SSL证书路径

文件参数

文件参数用于文件上传,常用两种格式:

  • 'name': fileobj:字段名与服务端匹配即可;
  • {'name': file-tuple}:文件元组为('filename', fileobj[, 'content_type'[, custom_headers]])

可通过元组传递多个文件:

upFile = {    'file': (name, open('conf.xml', 'rb'))}upFiles = [	('images', ('foo.png', open('foo.png', 'rb'), 'image/png')),	('file', ('conf.json', open('myJson.json', 'rb')))]

应答response

HTTP请求返回为response对象,其对应的常见属性:

属性 说明
r.status_code http请求的返回状态,若为200则表示请求成功。
r.text http响应内容的字符串形式,即返回的页面内容
r.encoding 从http header 中猜测的相应内容编码方式
r.headers 返回的头信息
r.content http响应内容的二进制形式
r.json() 以json格式获取返回的内容

示例程序

程序所需导入的模块与用于格式化Json的辅助函数

import requestsimport jsonimport osimport randomdef pretty_print(data):    out = json.dumps(data, sort_keys=False, indent=4, separators=(',', ':'))    print(out)

get

设get需要query、page两个参数,且返回json格式的数据:

def get_request(srvUrl):    try:        header = {
"Content-Type": "application/json;charset=UTF-8"} param = {
# query参数 "query": "test", } param["page"] = True # 字典中可随意增加参数 resp = requests.get(url=srvUrl, params=param, headers=header) print(resp) if resp.content: pretty_print(resp.json()) # 返回json格式body体 except Exception as ex: print(ex)

post

设上传的body为JSON格式的(可通过json或data参数设定)

def post_request(srvUrl):    try:        header = {
"Content-Type": "application/json;charset=UTF-8"} body = {
# JSON格式body数据 "query": "test-" + str(random.randint(1000, 9999)), "page": 0, "size": 10 } # resp = requests.post(url=srvUrl, headers=header, data=json.dumps(body)) resp = requests.post(url=srvUrl, headers=header, json=body) print(resp) except Exception as ex: print(ex)

下载文件

文件内容以content属性返回,只需把其写入到文件中即可:

def export_file(srvUrl, file):    try:        header = {
"Content-Type": "application/json;charset=UTF-8"} resp = requests.post(url=srvUrl, headers=header) print(resp) if resp.status_code != requests.codes.ok: return # error! header = resp.headers name = header.get("Content-Disposition") # 假设头中携带文件信息,可获取用于写文件 print(name) with open(file, "wb") as conf: conf.write(resp.content) except Exception as ex: print(ex)

上传文件

上传的文件以files参数设定:

def import_file(srvUrl, file):    try:        header = {
"Content-Type": "application/json;charset=UTF-8"} resp = requests.post(url=srvUrl, headers=header) print(resp) if resp.status_code != requests.codes.ok: return # error! name = os.path.basename(file) with open(file, "rb") as conf: upFile = {
'file': (name, conf) } resp = requests.post(url=srvUrl, files=upFile) print(resp) except Exception as ex: print(ex)

转载地址:http://yzilf.baihongyu.com/

你可能感兴趣的文章
Contour 学习笔记(一):使用 Contour 接管 Kubernetes 的南北流量
查看>>
K8s 学习者绝对不能错过的最全知识图谱(内含 58个知识点链接)
查看>>
Contour 学习笔记(一):使用 Contour 接管 Kubernetes 的南北流量
查看>>
Contour 学习笔记(二):使用级联功能实现蓝绿部署和金丝雀发布
查看>>
Kubectl 的替代品:kubeman
查看>>
以后别人再问你什么是 Istio,就把这篇文章甩给他
查看>>
新书推荐 |《Prometheus监控实战》
查看>>
Tekton Pipeline 教程
查看>>
Istio 1.3 发布,HTTP 遥测不再需要 Mixer
查看>>
Kubernetes Dashboard 终结者:KubeSphere
查看>>
AdGuard Home 安装使用教程
查看>>
Porter:面向裸金属环境的 Kubernetes 开源负载均衡器
查看>>
Kubernetes Dashboard 终结者:KubeSphere
查看>>
手把手教你部署 Istio 1.3
查看>>
CentOS 8 都发布了,你还不会用 nftables?
查看>>
一点也不流氓的搜狗输入法皮肤
查看>>
Grafana 6.4 正式发布!
查看>>
etcd 性能测试与调优
查看>>
Docker 大势已去,Podman 万岁
查看>>
Podman 使用指南
查看>>