python requests 常见的接口数据处理

简介: 重点讲解python如何利用requests库来进行常见的post请求,这里涉及到三种常见的方式:application/x-www-form-urlencoded ;application/json 和 multipart/form-data 。

1 requests 概述


python requests 是HTTP相关操作至关重要的一个库,并且被很多大型公司所采用,它采用python语言编写,在python内置模块的基础上进行了封装,从而让HTTP网络请求变得异常简单和方便。使用requests可以轻松的完成浏览器可有的任何操作,该库完全满足当前的 web 应用相关需求,其主要的特征有:

  • Keep-Alive & 连接池
  • 国际化域名和 URL
  • 带持久 Cookie 的会话
  • 浏览器式的 SSL 认证
  • 自动内容解码
  • 基本/摘要式的身份认证
  • 优雅的 key/value Cookie
  • 自动解压
  • Unicode 响应体
  • HTTP(S) 代理支持
  • 文件分块上传
  • 流下载
  • 连接超时
  • 分块请求
  • 支持 .netrc

     requests支持 Python 2.6—2.7以及3.3—3.7,而且能在 PyPy 下完美运行。安装也非常方便,执行如下语句即可:

pip install requests

2 requests 快速入门


python requests库使用起来非常简单,首先 import requests 导入 requests ,然后就可以用requests来进行HTTP相关的操作,比如get和post请求。官网示例如下所示:

# GET usage:importrequestsr=requests.get('https://www.python.org')
print(r.status_code)
#200print(r.content)
############################################ POST usage:importrequestspayload=dict(key1='value1', key2='value2')
r=requests.post('https://httpbin.org/post', data=payload)
print(r.text)

从源码中可以看出,get和post方法底层是基于request方法,且其中的参数比较多,比如url ,params ,data , json ,headers 等。具体如下所示:

defrequest(method, url, **kwargs):
"""Constructs and sends a :class:`Request <Request>`.    :param method: method for the new :class:`Request` object: ``GET``, ``OPTIONS``, ``HEAD``, ``POST``, ``PUT``, ``PATCH``, or ``DELETE``.    :param url: URL for the new :class:`Request` object.    :param params: (optional) Dictionary, list of tuples or bytes to send        in the query string for the :class:`Request`.    :param data: (optional) Dictionary, list of tuples, bytes, or file-like        object to send in the body of the :class:`Request`.    :param json: (optional) A JSON serializable Python object to send in the body of the :class:`Request`.    :param headers: (optional) Dictionary of HTTP Headers to send with the :class:`Request`.    :param cookies: (optional) Dict or CookieJar object to send with the :class:`Request`.    :param files: (optional) Dictionary of ``'name': file-like-objects`` (or ``{'name': file-tuple}``) for multipart encoding upload.        ``file-tuple`` can be a 2-tuple ``('filename', fileobj)``, 3-tuple ``('filename', fileobj, 'content_type')``        or a 4-tuple ``('filename', fileobj, 'content_type', custom_headers)``, where ``'content-type'`` is a string        defining the content type of the given file and ``custom_headers`` a dict-like object containing additional headers        to add for the file.    :param auth: (optional) Auth tuple to enable Basic/Digest/Custom HTTP Auth.    :param timeout: (optional) How many seconds to wait for the server to send data        before giving up, as a float, or a :ref:`(connect timeout, read        timeout) <timeouts>` tuple.    :type timeout: float or tuple    :param allow_redirects: (optional) Boolean. Enable/disable GET/OPTIONS/POST/PUT/PATCH/DELETE/HEAD redirection. Defaults to ``True``.    :type allow_redirects: bool    :param proxies: (optional) Dictionary mapping protocol to the URL of the proxy.    :param verify: (optional) Either a boolean, in which case it controls whether we verify            the server's TLS certificate, or a string, in which case it must be a path            to a CA bundle to use. Defaults to ``True``.    :param stream: (optional) if ``False``, the response content will be immediately downloaded.    :param cert: (optional) if String, path to ssl client cert file (.pem). If Tuple, ('cert', 'key') pair.    :return: :class:`Response <Response>` object    :rtype: requests.Response    Usage::      >>> import requests      >>> req = requests.request('GET', 'https://httpbin.org/get')      >>> req      <Response [200]>    """# By using the 'with' statement we are sure the session is closed, thus we# avoid leaving sockets open which can trigger a ResourceWarning in some# cases, and look like a memory leak in others.withsessions.Session() assession:
returnsession.request(method=method, url=url, **kwargs)
defget(url, params=None, **kwargs):
r"""Sends a GET request.    :param url: URL for the new :class:`Request` object.    :param params: (optional) Dictionary, list of tuples or bytes to send        in the query string for the :class:`Request`.    :param \*\*kwargs: Optional arguments that ``request`` takes.    :return: :class:`Response <Response>` object    :rtype: requests.Response    """returnrequest('get', url, params=params, **kwargs)
defoptions(url, **kwargs):
r"""Sends an OPTIONS request.    :param url: URL for the new :class:`Request` object.    :param \*\*kwargs: Optional arguments that ``request`` takes.    :return: :class:`Response <Response>` object    :rtype: requests.Response    """returnrequest('options', url, **kwargs)
defhead(url, **kwargs):
r"""Sends a HEAD request.    :param url: URL for the new :class:`Request` object.    :param \*\*kwargs: Optional arguments that ``request`` takes. If        `allow_redirects` is not provided, it will be set to `False` (as        opposed to the default :meth:`request` behavior).    :return: :class:`Response <Response>` object    :rtype: requests.Response    """kwargs.setdefault('allow_redirects', False)
returnrequest('head', url, **kwargs)
defpost(url, data=None, json=None, **kwargs):
r"""Sends a POST request.    :param url: URL for the new :class:`Request` object.    :param data: (optional) Dictionary, list of tuples, bytes, or file-like        object to send in the body of the :class:`Request`.    :param json: (optional) json data to send in the body of the :class:`Request`.    :param \*\*kwargs: Optional arguments that ``request`` takes.    :return: :class:`Response <Response>` object    :rtype: requests.Response    """returnrequest('post', url, data=data, json=json, **kwargs)

3 requests 常见的接口数据请求


第一种,可以基于Content-Type :application/x-www-form-urlencoded 来通过HTTP POST来发送请求,这里可以用软件nc 来查看请求的内容,这里需要提取开启一个端口8888的HTTP服务,命令如下所示:

nc-lk8888

      用如下的python代码来进行请求,代码如下所示:

importrequestsrequests.post('http://localhost:8888',data={'a':1,'b':'2'})

    此时nc所在的命令窗口会显示requests post过来的请求内容,输出如下所示:

POST/HTTP/1.1Host: localhost:8888User-Agent: python-requests/2.26.0Accept-Encoding: gzip, deflateAccept: */*Connection: keep-aliveContent-Length: 7Content-Type: application/x-www-form-urlencodeda=1&b=2

   如果参数通过params来传递,则与data不同,示意如下所示:

importrequestsrequests.post('http://localhost:8888',params={'a':1,'b':'2'})

此时nc所在的命令窗口会显示requests post过来的请求内容,输出如下所示:

# POST /?a=1&b=2 HTTP/1.1# Host: localhost:8888# User-Agent: python-requests/2.26.0# Accept-Encoding: gzip, deflate# Accept: */*# Connection: keep-alive# Content-Length: 0

第二种,可以基于Content-Type :application/json 来通过HTTP POST来发送请求。用如下的python代码来进行请求,代码如下所示:

importrequestsurl="http://localhost:8888"headers= {"Content-Type": "application/json; charset=utf-8"}
data= {
"id": 1001,
"name": "geek",
"passion": "coding",
}
response=requests.post(url, headers=headers, json=data)
print("Status Code", response.status_code)
print("JSON Response ", response.json())

    此时nc所在的命令窗口会显示requests post过来的请求内容,输出如下所示:

# POST / HTTP/1.1# Host: localhost:8888# User-Agent: python-requests/2.26.0# Accept-Encoding: gzip, deflate# Accept: */*# Connection: keep-alive# Content-Type: application/json; charset=utf-8# Content-Length: 49# {"id": 1001, "name": "geek", "passion": "coding"}

第三种,可以基于Content-Type :multipart/form-data 来通过HTTP POST来发送请求,这里一般可以用于上传文件,比如mp4或者pdf等。用如下的python代码来进行请求,代码如下所示:

importrequestsdefupload_file(host,token,filename):
headers= {
'Authorization': 'Bearer {}'.format(token)
'User-Agent': 'Chrome/44.0.2403.125'    }
url=f"{host}/upload"# files = {'file': open(filename, 'rb'),'Content-Type': 'application/mp4'}files= {'personVideo': (f'{filename}', open(f'{filename}', 'rb'), 'application/mp4')}
r=requests.post(url,headers=headers,files=files,verify=True)
returnr.textif__name__=='__main__' :
host='http://localhost:8888'token='xxxx-xxxx-xxxx-xxxx'filename='1404210078662001000520210104224515.MP4'upload_file(host,token,filename)

    此时nc所在的命令窗口会显示requests post过来的请求内容,输出如下所示:

# POST /upload HTTP/1.1# Host: localhost:8888# User-Agent: Chrome/44.0.2403.125# Accept-Encoding: gzip, deflate# Accept: */*# Connection: keep-alive# Authorization: Bearer xxxx-xxxx-xxxx-xxxx# Content-Length: 217# Content-Type: multipart/form-data; boundary=212e0076bb7ae887ffe5751ba9eab5be# --212e0076bb7ae887ffe5751ba9eab5be# Content-Disposition: form-data; name="personVideo"; filename="1404210078662001000520210104224515.MP4"# Content-Type: application/mp4# [xxxx文件内容xxxx]# --212e0076bb7ae887ffe5751ba9eab5be--

另外,还可以指定boundary,下面给出示例代码:

importrequests# pip install requests_toolbeltfromrequests_toolbeltimportMultipartEncoderdefupload_file(host,token,filename):
url=f"{host}/upload"fields= {
'personVideo': (f'{filename}', open(f'{filename}', 'rb'), 'application/mp4')
    }
boundary='----WebKitFormBoundaryJVpKw2XlPggKaD87'm=MultipartEncoder(fields=fields, boundary=boundary)
print(m.content_type)
#multipart/form-data; boundary=----WebKitFormBoundaryJVpKw2XlPggKaD87headers= {
'Authorization': 'Bearer {}'.format(token),
'Content-Type': m.content_type    }  
r=requests.post(url,headers=headers,data=m)
returnr.textif__name__=='__main__' :
host='http://localhost:8888'token='xxxx-xxxx-xxxx-xxxx'filename='1404210078662001000520210104224515.MP4'upload_file(host,token,filename)


相关文章
|
4天前
|
数据采集 Web App开发 数据可视化
Python零基础爬取东方财富网股票行情数据指南
东方财富网数据稳定、反爬宽松,适合爬虫入门。本文详解使用Python抓取股票行情数据,涵盖请求发送、HTML解析、动态加载处理、代理IP切换及数据可视化,助你快速掌握金融数据爬取技能。
82 1
|
5天前
|
存储 Java 数据处理
(numpy)Python做数据处理必备框架!(一):认识numpy;从概念层面开始学习ndarray数组:形状、数组转置、数值范围、矩阵...
Numpy是什么? numpy是Python中科学计算的基础包。 它是一个Python库,提供多维数组对象、各种派生对象(例如掩码数组和矩阵)以及用于对数组进行快速操作的各种方法,包括数学、逻辑、形状操作、排序、选择、I/0 、离散傅里叶变换、基本线性代数、基本统计运算、随机模拟等等。 Numpy能做什么? numpy的部分功能如下: ndarray,一个具有矢量算术运算和复杂广播能力的快速且节省空间的多维数组 用于对整组数据进行快速运算的标准数学函数(无需编写循环)。 用于读写磁盘数据的工具以及用于操作内存映射文件的工具。 线性代数、随机数生成以及傅里叶变换功能。 用于集成由C、C++
89 1
|
5天前
|
Java 数据处理 索引
(Pandas)Python做数据处理必选框架之一!(二):附带案例分析;刨析DataFrame结构和其属性;学会访问具体元素;判断元素是否存在;元素求和、求标准值、方差、去重、删除、排序...
DataFrame结构 每一列都属于Series类型,不同列之间数据类型可以不一样,但同一列的值类型必须一致。 DataFrame拥有一个总的 idx记录列,该列记录了每一行的索引 在DataFrame中,若列之间的元素个数不匹配,且使用Series填充时,在DataFrame里空值会显示为NaN;当列之间元素个数不匹配,并且不使用Series填充,会报错。在指定了index 属性显示情况下,会按照index的位置进行排序,默认是 [0,1,2,3,...] 从0索引开始正序排序行。
52 0
|
5天前
|
Java 数据挖掘 数据处理
(Pandas)Python做数据处理必选框架之一!(一):介绍Pandas中的两个数据结构;刨析Series:如何访问数据;数据去重、取众数、总和、标准差、方差、平均值等;判断缺失值、获取索引...
Pandas 是一个开源的数据分析和数据处理库,它是基于 Python 编程语言的。 Pandas 提供了易于使用的数据结构和数据分析工具,特别适用于处理结构化数据,如表格型数据(类似于Excel表格)。 Pandas 是数据科学和分析领域中常用的工具之一,它使得用户能够轻松地从各种数据源中导入数据,并对数据进行高效的操作和分析。 Pandas 主要引入了两种新的数据结构:Series 和 DataFrame。
102 0
|
5天前
|
Java 数据处理 索引
(numpy)Python做数据处理必备框架!(二):ndarray切片的使用与运算;常见的ndarray函数:平方根、正余弦、自然对数、指数、幂等运算;统计函数:方差、均值、极差;比较函数...
ndarray切片 索引从0开始 索引/切片类型 描述/用法 基本索引 通过整数索引直接访问元素。 行/列切片 使用冒号:切片语法选择行或列的子集 连续切片 从起始索引到结束索引按步长切片 使用slice函数 通过slice(start,stop,strp)定义切片规则 布尔索引 通过布尔条件筛选满足条件的元素。支持逻辑运算符 &、|。
45 0
|
17天前
|
缓存 监控 算法
唯品会item_search - 按关键字搜索 VIP 商品接口深度分析及 Python 实现
唯品会item_search接口支持通过关键词、分类、价格等条件检索商品,广泛应用于电商数据分析、竞品监控与市场调研。结合Python可实现搜索、分析、可视化及数据导出,助力精准决策。
|
6天前
|
JSON API 数据安全/隐私保护
Python采集淘宝拍立淘按图搜索API接口及JSON数据返回全流程指南
通过以上流程,可实现淘宝拍立淘按图搜索的完整调用链路,并获取结构化的JSON商品数据,支撑电商比价、智能推荐等业务场景。
|
17天前
|
缓存 监控 算法
苏宁item_search - 按关键字搜索商品接口深度分析及 Python 实现
苏宁item_search接口支持通过关键词、分类、价格等条件检索商品,广泛应用于电商分析、竞品监控等场景。具备多维度筛选、分页获取、数据丰富等特性,结合Python可实现搜索、分析与可视化,助力市场研究与决策。
|
17天前
|
缓存 监控 算法
苏宁item_get - 获得商品详情接口深度# 深度分析及 Python 实现
苏宁易购item_get接口可实时获取商品价格、库存、促销等详情,支持电商数据分析与竞品监控。需认证接入,遵守调用限制,适用于价格监控、销售分析等场景,助力精准营销决策。(238字)
|
14天前
|
数据采集 关系型数据库 MySQL
python爬取数据存入数据库
Python爬虫结合Scrapy与SQLAlchemy,实现高效数据采集并存入MySQL/PostgreSQL/SQLite。通过ORM映射、连接池优化与批量提交,支持百万级数据高速写入,具备良好的可扩展性与稳定性。

推荐镜像

更多