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)


相关文章
|
1月前
|
API Python
【02】优雅草央央逆向技术篇之逆向接口协议篇-以小红书为例-python逆向小红书将用户名转换获得为uid-优雅草央千澈
【02】优雅草央央逆向技术篇之逆向接口协议篇-以小红书为例-python逆向小红书将用户名转换获得为uid-优雅草央千澈
94 1
|
2月前
|
数据采集 数据可视化 数据挖掘
利用Python自动化处理Excel数据:从基础到进阶####
本文旨在为读者提供一个全面的指南,通过Python编程语言实现Excel数据的自动化处理。无论你是初学者还是有经验的开发者,本文都将帮助你掌握Pandas和openpyxl这两个强大的库,从而提升数据处理的效率和准确性。我们将从环境设置开始,逐步深入到数据读取、清洗、分析和可视化等各个环节,最终实现一个实际的自动化项目案例。 ####
292 10
|
2月前
|
数据采集 存储 XML
Python爬虫:深入探索1688关键词接口获取之道
在数字化经济中,数据尤其在电商领域的价值日益凸显。1688作为中国领先的B2B平台,其关键词接口对商家至关重要。本文介绍如何通过Python爬虫技术,合法合规地获取1688关键词接口,助力商家洞察市场趋势,优化营销策略。
|
4天前
|
数据采集 数据安全/隐私保护 Python
从零开始:用Python爬取网站的汽车品牌和价格数据
在现代化办公室中,工程师小李和产品经理小张讨论如何获取懂车帝网站的汽车品牌和价格数据。小李提出使用Python编写爬虫,并通过亿牛云爬虫代理避免被封禁。代码实现包括设置代理、请求头、解析网页内容、多线程爬取等步骤,确保高效且稳定地抓取数据。小张表示理解并准备按照指导操作。
从零开始:用Python爬取网站的汽车品牌和价格数据
|
8天前
|
API 文件存储 数据安全/隐私保护
python 群晖nas接口(一)
这段代码展示了如何通过群晖NAS的API获取认证信息(SID)并列出指定文件夹下的所有文件。首先,`get_sid()`函数通过用户名和密码登录NAS,获取会话ID(SID)。接着,`list_file(filePath, sid)`函数使用该SID访问FileStation API,列出给定路径`filePath`下的所有文件。注意需替换`yourip`、`username`和`password`为实际值。
49 18
|
6天前
|
API Python
python泛微e9接口开发
通过POST请求向指定IP的API注册设备以获取`secrit`和`spk`。请求需包含`appid`、`loginid`、`pwd`等头信息。响应中包含状态码、消息及`secrit`(注意拼写)、`secret`和`spk`字段。示例代码使用`curl`命令发送请求,成功后返回相关信息。
29 5
|
6天前
|
API 文件存储 Python
python 群晖nas接口(二)
这段代码展示了如何通过API将文件上传到群晖NAS。它使用`requests`库发送POST请求,指定文件路径、创建父级目录及覆盖同名文件的参数,并打印上传结果。确保替换`yourip`和`sid`为实际值。
25 2
|
1月前
|
数据采集 Web App开发 数据可视化
Python用代理IP获取抖音电商达人主播数据
在当今数字化时代,电商直播成为重要的销售模式,抖音电商汇聚了众多达人主播。了解这些主播的数据对于品牌和商家至关重要。然而,直接从平台获取数据并非易事。本文介绍如何使用Python和代理IP高效抓取抖音电商达人主播的关键数据,包括主播昵称、ID、直播间链接、观看人数、点赞数和商品列表等。通过环境准备、代码实战及数据处理与可视化,最终实现定时任务自动化抓取,为企业决策提供有力支持。
|
1月前
|
SQL 分布式计算 数据处理
云产品评测|分布式Python计算服务MaxFrame | 在本地环境中使用MaxFrame + 基于MaxFrame实现大语言模型数据处理
本文基于官方文档,介绍了由浅入深的两个部分实操测试,包括在本地环境中使用MaxFrame & 基于MaxFrame实现大语言模型数据处理,对步骤有详细说明。体验下来对MaxCompute的感受是很不错的,值得尝试并使用!
48 1
|
1月前
|
人工智能 分布式计算 数据处理
有奖评测,基于分布式 Python 计算服务 MaxFrame 进行数据处理
阿里云MaxCompute MaxFrame推出分布式Python计算服务MaxFrame评测活动,助力开发者高效完成大规模数据处理、可视化探索及ML/AI开发。活动时间为2024年12月17日至2025年1月31日,参与者需体验MaxFrame并发布评测文章,有机会赢取精美礼品。

热门文章

最新文章