user15483624
user15483624

Reputation:

How to print post data when using requests?

import requests
import logging
logging.basicConfig(level=logging.DEBUG)
r = requests.post('http://httpbin.org/post'
        , headers = {'h1': 'v1'}
        , data = {'key': 'value'}
        )
print(r)

When I run the above code, I see the following output. But the detailed info of the data posted is not shown. Is there a way to configure the log so that what has been posted will also been shown?

DEBUG:urllib3.connectionpool:Starting new HTTP connection (1): httpbin.org
DEBUG:urllib3.connectionpool:http://httpbin.org:80 "POST /post HTTP/1.1" 200 497
<Response [200]>

Upvotes: 1

Views: 801

Answers (3)

Simon
Simon

Reputation: 421

Since urllib3 uses http.client.HTTPConnection, its debugging output can be enabled by debuglevel = 1.

import requests
import logging
logging.basicConfig(level=logging.DEBUG)

import http.client
http.client.HTTPConnection.debuglevel = 1

r = requests.post('http://httpbin.org/post'
        , headers = {'h1': 'v1'}
        , data = {'key': 'value'}
        )
DEBUG:urllib3.connectionpool:Starting new HTTP connection (1): httpbin.org:80
send: b'POST /post HTTP/1.1\r\nHost: httpbin.org\r\nUser-Agent: python-requests/2.25.1\r\nAccept-Encoding: gzip, deflate\r\nAccept: */*\r\nConnection: keep-alive\r\nh1: v1\r\nContent-Length: 9\r\nContent-Type: application/x-www-form-urlencoded\r\n\r\n'
send: b'key=value'
reply: 'HTTP/1.1 200 OK\r\n'
header: Date: Sat, 03 Apr 2021 04:35:19 GMT
header: Content-Type: application/json
header: Content-Length: 495
header: Connection: keep-alive
header: Server: gunicorn/19.9.0
header: Access-Control-Allow-Origin: *
header: Access-Control-Allow-Credentials: true
DEBUG:urllib3.connectionpool:http://httpbin.org:80 "POST /post HTTP/1.1" 200 495

Upvotes: 1

Liong
Liong

Reputation: 1564

Maybe you can use some asynchronous way to get text even still doing request. You can use this article for references

Upvotes: 0

Sam Szotkowski
Sam Szotkowski

Reputation: 354

This is what I like to use:

import json

print(json.dumps(r.json(), indent=4))

This is the type of question you can answer via documentation, you could check type(r) then google that class and look at its properties/methods.

Upvotes: 0

Related Questions