requests post,get,等等方法及其說明
阿新 • • 發佈:2019-01-12
首先是統一編碼。
這個模組實現了requests的api。
從本模組下倒入sessions,主要的實現都是sessions裡面實現,其他的檔案都是helper。這個也依賴urllib3等
# -*- coding: utf-8 -*- """ requests.api ~~~~~~~~~~~~ This module implements the Requests API. :copyright: (c) 2012 by Kenneth Reitz. :license: Apache2, see LICENSE for more details. """ from . import sessions
首先是request方法,也是其他方法的基本方法。
method ,get,post,delete等等。
url 將要訪問的url地址
**kwargs 其他引數常用引數
param,請求的連結太長了,可以通過存入param中。
data, 這個用來儲存表單資料,和上面的區別就是,不顯示在瀏覽器的導航欄。
headers,請求頭,在瀏覽器開發者模式下的network欄裡面可以看到動態請求。
cookies,可以在headers裡面設定,也可以自己更明確的新增。
auth ,授權,在一些地方可以用到。
timeout,設定連線和響應超時時長
proxy,代理,特別是那種喜歡拉黑人家ip的網站,可以用代理進行避免。
stream,下載檔案,不想一直阻塞。中間想要觀察資料動向可以使用。
下面是具體的格式。
#: A case-insensitive dictionary of headers to be sent on each #: :class:`Request <Request>` sent from this #: :class:`Session <Session>`. self.headers = default_headers() #: Default Authentication tuple or object to attach to #: :class:`Request <Request>`. self.auth = None #: Dictionary mapping protocol or protocol and host to the URL of the proxy #: (e.g. {'http': 'foo.bar:3128', 'http://host.name': 'foo.bar:4012'}) to #: be used on each :class:`Request <Request>`. self.proxies = {} #: Event-handling hooks. self.hooks = default_hooks() #: Dictionary of querystring data to attach to each #: :class:`Request <Request>`. The dictionary values may be lists for #: representing multivalued query parameters. self.params = {} #: Stream response content default. self.stream = False #: SSL Verification default. self.verify = True #: SSL client certificate default, if String, path to ssl client #: cert file (.pem). If Tuple, ('cert', 'key') pair. self.cert = None #: Maximum number of redirects allowed. If the request exceeds this #: limit, a :class:`TooManyRedirects` exception is raised. #: This defaults to requests.models.DEFAULT_REDIRECT_LIMIT, which is #: 30. self.max_redirects = DEFAULT_REDIRECT_LIMIT #: Trust environment settings for proxy configuration, default #: authentication and similar. self.trust_env = True #: A CookieJar containing all currently outstanding cookies set on this #: session. By default it is a #: :class:`RequestsCookieJar <requests.cookies.RequestsCookieJar>`, but #: may be any other ``cookielib.CookieJar`` compatible object. self.cookies = cookiejar_from_dict({}) # Default connection adapters. self.adapters = OrderedDict() self.mount('https://', HTTPAdapter()) self.mount('http://', HTTPAdapter())
def request(method, url, **kwargs):
"""Constructs and sends a :class:`Request <Request>`.
:param method: method for the new :class:`Request` object.
method用於將要建立的類Requet的引數
:param url: URL for the new :class:`Request` object.
傳入Request的URL引數
:param params: (optional) Dictionary, list of tuples or bytes to send
in the body of the :class:`Request`.
字典型別或者是tuple集合或者byte型別
params是引數,也就是 ?key=value&key=value&...
也可以通過 [(key,value)] 也可以是直接按照http協議編碼好的資料
:param data: (optional) Dictionary, list of tuples, bytes, or file-like
object to send in the body of the :class:`Request`.
data 字典型別或者是tuple集合或者byte型別或者是一個檔案一樣的類
:param json: (optional) A JSON serializable Python object to send in the body of the
:class:`Request`.
json,序列化傳送過去的資料
:param headers: (optional) Dictionary of HTTP Headers to send with the
:class:`Request`.
請求頭,包括許多的格式和標準還有引數資訊等等。字典或者http Headers
:param cookies: (optional) Dict or CookieJar object to send with the
:class:`Request`.
cookies可以放入headers中也可以手動新增。可以是字典,cookiejar物件
: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')``
file-tuple可以是兩個元素或者是三個元素的元組,或者是四個元素的元組
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
設定超時,等待伺服器多少秒後就放棄傳送。可以是float或者是一個元組,分別是連線和響應超時時長
:param allow_redirects: (optional) Boolean. Enable/disable
GET/OPTIONS/POST/PUT/PATCH/DELETE/HEAD redirection. Defaults to ``True``.
:type allow_redirects: bool
傳入一個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``.
如果是一個bool值就是控制是否給證書,如果是一個字串就是整數存放的位置。預設是True。
:param stream: (optional) if ``False``, the response content will be immediately
downloaded.
是按照stream還是直接下載,預設是直接下載,如果我們下載檔案,視訊什麼的可以通過流下載。
我們可以看一下you-get
: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')
<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模式我們可以保證session會被關閉。避免離開sockets導致了錯誤,比如其他地方記憶體益處。
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 body of the :class:`Request`.
:param \*\*kwargs: Optional arguments that ``request`` takes.
:return: :class:`Response <Response>` object
:rtype: requests.Response
"""
kwargs.setdefault('allow_redirects', True)
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
"""
kwargs.setdefault('allow_redirects', True)
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.
: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)
def put(url, data=None, **kwargs):
r"""Sends a PUT 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('put', url, data=data, **kwargs)
def patch(url, data=None, **kwargs):
r"""Sends a PATCH 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('patch', url, data=data, **kwargs)
def delete(url, **kwargs):
r"""Sends a DELETE 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('delete', url, **kwargs)
其他的都是上層的高階方法呼叫request。