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)


目录
打赏
0
0
0
0
3052
分享
相关文章
|
2月前
|
【02】优雅草央央逆向技术篇之逆向接口协议篇-以小红书为例-python逆向小红书将用户名转换获得为uid-优雅草央千澈
【02】优雅草央央逆向技术篇之逆向接口协议篇-以小红书为例-python逆向小红书将用户名转换获得为uid-优雅草央千澈
113 1
如何在Python中高效实现CSV到JSON的数据转换
在实际项目中,数据格式转换是常见问题,尤其从CSV到JSON的转换。本文深入探讨了多种转换方法,涵盖Python基础实现、数据预处理、错误处理、性能优化及调试验证技巧。通过分块处理、并行处理等手段提升大文件转换效率,并介绍如何封装为命令行工具或Web API,实现自动化批量处理。关键点包括基础实现、数据清洗、异常捕获、性能优化和单元测试,确保转换流程稳定高效。
127 83
利用Python自动化处理Excel数据:从基础到进阶####
本文旨在为读者提供一个全面的指南,通过Python编程语言实现Excel数据的自动化处理。无论你是初学者还是有经验的开发者,本文都将帮助你掌握Pandas和openpyxl这两个强大的库,从而提升数据处理的效率和准确性。我们将从环境设置开始,逐步深入到数据读取、清洗、分析和可视化等各个环节,最终实现一个实际的自动化项目案例。 ####
371 10
从零开始:用Python爬取网站的汽车品牌和价格数据
在现代化办公室中,工程师小李和产品经理小张讨论如何获取懂车帝网站的汽车品牌和价格数据。小李提出使用Python编写爬虫,并通过亿牛云爬虫代理避免被封禁。代码实现包括设置代理、请求头、解析网页内容、多线程爬取等步骤,确保高效且稳定地抓取数据。小张表示理解并准备按照指导操作。
从零开始:用Python爬取网站的汽车品牌和价格数据
从集思录可转债数据探秘:Python与C++实现的移动平均算法应用
本文探讨了如何利用移动平均算法分析集思录提供的可转债数据,帮助投资者把握价格趋势。通过Python和C++两种编程语言实现简单移动平均(SMA),展示了数据处理的具体方法。Python代码借助`pandas`库轻松计算5日SMA,而C++代码则通过高效的数据处理展示了SMA的计算过程。集思录平台提供了详尽且及时的可转债数据,助力投资者结合算法与社区讨论,做出更明智的投资决策。掌握这些工具和技术,有助于在复杂多变的金融市场中挖掘更多价值。
39 12
实战指南:通过1688开放平台API获取商品详情数据(附Python代码及避坑指南)
1688作为国内最大的B2B供应链平台,其API为企业提供合法合规的JSON数据源,直接获取批发价、SKU库存等核心数据。相比爬虫方案,官方API避免了反爬严格、数据缺失和法律风险等问题。企业接入1688商品API需完成资质认证、创建应用、签名机制解析及调用接口四步。应用场景包括智能采购系统、供应商评估模型和跨境选品分析。提供高频问题解决方案及安全合规实践,确保数据安全与合法使用。立即访问1688开放平台,解锁B2B数据宝藏!
python 群晖nas接口(一)
这段代码展示了如何通过群晖NAS的API获取认证信息(SID)并列出指定文件夹下的所有文件。首先,`get_sid()`函数通过用户名和密码登录NAS,获取会话ID(SID)。接着,`list_file(filePath, sid)`函数使用该SID访问FileStation API,列出给定路径`filePath`下的所有文件。注意需替换`yourip`、`username`和`password`为实际值。
76 18
|
19天前
|
python泛微e9接口开发
通过POST请求向指定IP的API注册设备以获取`secrit`和`spk`。请求需包含`appid`、`loginid`、`pwd`等头信息。响应中包含状态码、消息及`secrit`(注意拼写)、`secret`和`spk`字段。示例代码使用`curl`命令发送请求,成功后返回相关信息。
40 5
python 群晖nas接口(二)
这段代码展示了如何通过API将文件上传到群晖NAS。它使用`requests`库发送POST请求,指定文件路径、创建父级目录及覆盖同名文件的参数,并打印上传结果。确保替换`yourip`和`sid`为实际值。
44 2

热门文章

最新文章

AI助理

你好,我是AI助理

可以解答问题、推荐解决方案等