[Python]-使用Requests进行HTTP请求与文件上传下载

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_codehttp请求的返回状态,若为200则表示请求成功。
r.texthttp响应内容的字符串形式,即返回的页面内容
r.encoding从http header 中猜测的相应内容编码方式
r.headers返回的头信息
r.contenthttp响应内容的二进制形式
r.json()以json格式获取返回的内容

示例程序

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

import requests
import json
import os
import random


def 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)
  • 0
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值