更新时间:2022-05-08 04:23:51
python requests 是HTTP相关操作至关重要的一个库,并且被很多大型公司所采用,它采用python语言编写,在python内置模块的基础上进行了封装,从而让HTTP网络请求变得异常简单和方便。使用requests可以轻松的完成浏览器可有的任何操作,该库完全满足当前的 web 应用相关需求,其主要的特征有:
requests支持 Python 2.6—2.7以及3.3—3.7,而且能在 PyPy 下完美运行。安装也非常方便,执行如下语句即可:
pip install requests
python requests库使用起来非常简单,首先 import requests 导入 requests ,然后就可以用requests来进行HTTP相关的操作,比如get和post请求。官网示例如下所示:
# GET usage: import requests r = requests.get('https://www.python.org') print(r.status_code) #200 print(r.content) ########################################### # POST usage: import requests payload = 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 等。具体如下所示:
def request(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. with sessions.Session() as session: return session.request(method=method, url=url, **kwargs) def get(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 """ return request('get', url, params=params, **kwargs) def options(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 """ return request('options', url, **kwargs) def head(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) return request('head', url, **kwargs) def post(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 """ return request('post', url, data=data, json=json, **kwargs)
第一种,可以基于Content-Type : application/x-www-form-urlencoded 来通过HTTP POST来发送请求,这里可以用软件nc 来查看请求的内容,这里需要提取开启一个端口8888的HTTP服务,命令如下所示:
nc -lk 8888
用如下的python代码来进行请求,代码如下所示:
import requests requests.post('http://localhost:8888',data={'a':1,'b':'2'})
此时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-Length: 7 Content-Type: application/x-www-form-urlencoded a=1&b=2
如果参数通过params来传递,则与data不同,示意如下所示:
import requests requests.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代码来进行请求,代码如下所示:
import requests url = "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代码来进行请求,代码如下所示:
import requests def upload_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) return r.text if __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,下面给出示例代码:
import requests # pip install requests_toolbelt from requests_toolbelt import MultipartEncoder def upload_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=----WebKitFormBoundaryJVpKw2XlPggKaD87 headers = { 'Authorization': 'Bearer {}'.format(token), 'Content-Type': m.content_type } r = requests.post(url,headers=headers,data = m) return r.text if __name__ == '__main__' : host = 'http://localhost:8888' token = 'xxxx-xxxx-xxxx-xxxx' filename = '1404210078662001000520210104224515.MP4' upload_file(host,token,filename)