requests.post()方法中的data參數和json參數


requests.post()
在通過requests.post()進行POST請求時,傳入報文的參數有兩個,一個是data,一個是json。
常見的form表單可以直接使用data參數進行報文提交,而data的對象則是python中的字典類型;
而在最新爬蟲的過程中遇到了一種payload報文,是一種json格式的報文,因此傳入的報文對象也應該是格式的;這里有兩種方法進行報文提交:

import requests
import json
 
url = "http://httpbin.org/post"
data = {
    "name":"haha",
    "age":18
}
# 1-data需要用json模塊轉一下
requests.post(url, data=json.dumps(data))
# 2-json參數會自動將字典類型的對象轉換為json格式
requests.post(url, json=data)

請求的結果:

{
    "args": {},
    "data": "{\r\n    \"name\":\"haha\",\r\n    \"age\":18\r\n}",
    "files": {},
    "form": {},
    "headers": {
        "Accept": "*/*",
        "Accept-Encoding": "gzip, deflate, br",
        "Cache-Control": "no-cache",
        "Content-Length": "38",
        "Content-Type": "application/json",
        "Host": "httpbin.org",
        "Postman-Token": "4ab45225-e133-4d9d-9a58-30f651fe8af8",
        "User-Agent": "PostmanRuntime/7.28.4",
        "X-Amzn-Trace-Id": "Root=1-616792a5-477ed8535b0b24aa4cc7c177"
    },
    "json": {
        "age": 18,
        "name": "haha"
    },
    "origin": "218.*.*.44",
    "url": "http://httpbin.org/post"
}

解析:

優點:

1. 不需要再用json.dumps做轉換傳參給data了

2. 也不需要加請求頭了:

headers = {
    'Content-Type': 'application/json'
}    

主要是因為源碼中這塊已經做了該做的事情了

    def prepare_body(self, data, files, json=None):
        """Prepares the given HTTP body data."""

        # Check if file, fo, generator, iterator.
        # If not, run through normal process.

        # Nottin' on you.
        body = None
        content_type = None

        if not data and json is not None:
            # urllib3 requires a bytes-like body. Python 2's json.dumps
            # provides this natively, but Python 3 gives a Unicode string.
            content_type = 'application/json'
            body = complexjson.dumps(json)
            if not isinstance(body, bytes):
                body = body.encode('utf-8')

        is_stream = all([
            hasattr(data, '__iter__'),
            not isinstance(data, (basestring, list, tuple, Mapping))
        ])

        if is_stream:
            try:
                length = super_len(data)
            except (TypeError, AttributeError, UnsupportedOperation):
                length = None

            body = data

            if getattr(body, 'tell', None) is not None:
                # Record the current file position before reading.
                # This will allow us to rewind a file in the event
                # of a redirect.
                try:
                    self._body_position = body.tell()
                except (IOError, OSError):
                    # This differentiates from None, allowing us to catch
                    # a failed `tell()` later when trying to rewind the body
                    self._body_position = object()

            if files:
                raise NotImplementedError('Streamed bodies and files are mutually exclusive.')

            if length:
                self.headers['Content-Length'] = builtin_str(length)
            else:
                self.headers['Transfer-Encoding'] = 'chunked'
        else:
            # Multi-part file uploads.
            if files:
                (body, content_type) = self._encode_files(files, data)
            else:
                if data:
                    body = self._encode_params(data)
                    if isinstance(data, basestring) or hasattr(data, 'read'):
                        content_type = None
                    else:
                        content_type = 'application/x-www-form-urlencoded'

            self.prepare_content_length(body)

            # Add content-type if it wasn't explicitly provided.
            if content_type and ('content-type' not in self.headers):
                self.headers['Content-Type'] = content_type

        self.body = body

不得不贊美一下作者,想的周到了,可是知道的有點晚了


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM