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)


相关文章
|
10天前
|
数据采集 数据可视化 Python
Python分析香港26281套在售二手房数据
Python分析香港26281套在售二手房数据
|
12天前
|
机器学习/深度学习 数据处理 Python
如何利用Python实现高效的数据清理与预处理
数据清理和预处理是数据科学家和分析师工作中不可或缺的一环,而Python作为一门强大的编程语言,可以使这个过程变得更加高效和便捷。本文将介绍一些常见的数据清理和预处理技术,并演示如何使用Python来实现这些技术。
|
15天前
|
存储 JSON 数据库
Python中列表数据的保存与读取:以txt文件为例
Python中列表数据的保存与读取:以txt文件为例
29 2
|
19小时前
|
人工智能 安全 网络安全
python运营商身份证二要素查验接口、身份证实名认证接口
翔云身份证二要素实名认证接口,实时联网,通过网民用户提供身份证号+姓名的核验方式确保交易与服务过程中的用户身份真实性是保障网络安全、防范欺诈行为的关键步骤。
|
1天前
|
算法 NoSQL Python
开山之作!Python数据与算法分析手册,登顶GitHub!
若把编写代码比作行军打仗,那么要想称霸沙场,不能仅靠手中的利刃,还需深谙兵法。 Python是一把利刃,数据结构与算法则是兵法。只有熟读兵法,才能使利刃所向披靡。只有洞彻数据结构与算法,才能真正精通Python
|
1天前
|
存储 数据处理 Python
Python中一二维数据的格式化和处理技术
Python中一二维数据的格式化和处理技术
|
1天前
|
数据采集 SQL 数据处理
Python中的Pandas库:数据处理与分析的利器
Python中的Pandas库:数据处理与分析的利器
|
2天前
|
存储 数据采集 JavaScript
基于Python的Web数据与解析
基于Python的Web数据与解析
11 0
|
2天前
|
数据采集 数据可视化 数据挖掘
使用Python进行高效数据处理
使用Python进行高效数据处理
15 1
|
2天前
|
数据采集 数据可视化 数据处理
Python中的高效数据处理:Pandas库详解
Python中的高效数据处理:Pandas库详解
20 2
http://www.vxiaotou.com