[python] Python 응용 프로그램에서 전송 한 전체 HTTP 요청을 어떻게 볼 수 있습니까?

필자의 경우 requests라이브러리를 사용하여 HTTPS를 통해 PayPal의 API를 호출 하고 있습니다. 불행히도 PayPal에서 오류가 발생하여 PayPal 지원 팀에서 오류의 원인 또는 원인을 파악할 수 없습니다. 그들은 “전체 요청을 제공하십시오. 헤더 포함”.

어떻게해야합니까?



답변

간단한 방법 : 최신 버전의 요청 (1.x 이상)에서 로깅 사용

요청은 여기에 설명 된대로 http.clientlogging모듈 구성을 사용하여 로깅 상세도를 제어 합니다 .

데모

링크 된 문서에서 발췌 한 코드 :

import requests
import logging

# These two lines enable debugging at httplib level (requests->urllib3->http.client)
# You will see the REQUEST, including HEADERS and DATA, and RESPONSE with HEADERS but without DATA.
# The only thing missing will be the response.body which is not logged.
try:
    import http.client as http_client
except ImportError:
    # Python 2
    import httplib as http_client
http_client.HTTPConnection.debuglevel = 1

# You must initialize logging, otherwise you'll not see debug output.
logging.basicConfig()
logging.getLogger().setLevel(logging.DEBUG)
requests_log = logging.getLogger("requests.packages.urllib3")
requests_log.setLevel(logging.DEBUG)
requests_log.propagate = True

requests.get('https://httpbin.org/headers')

출력 예

$ python requests-logging.py
INFO:requests.packages.urllib3.connectionpool:Starting new HTTPS connection (1): httpbin.org
send: 'GET /headers HTTP/1.1\r\nHost: httpbin.org\r\nAccept-Encoding: gzip, deflate, compress\r\nAccept: */*\r\nUser-Agent: python-requests/1.2.0 CPython/2.7.3 Linux/3.2.0-48-generic\r\n\r\n'
reply: 'HTTP/1.1 200 OK\r\n'
header: Content-Type: application/json
header: Date: Sat, 29 Jun 2013 11:19:34 GMT
header: Server: gunicorn/0.17.4
header: Content-Length: 226
header: Connection: keep-alive
DEBUG:requests.packages.urllib3.connectionpool:"GET /headers HTTP/1.1" 200 226


답변

r = requests.get('https://api.github.com', auth=('user', 'pass'))

r응답입니다. 필요한 정보가있는 요청 속성이 있습니다.

r.request.allow_redirects  r.request.headers          r.request.register_hook
r.request.auth             r.request.hooks            r.request.response
r.request.cert             r.request.method           r.request.send
r.request.config           r.request.params           r.request.sent
r.request.cookies          r.request.path_url         r.request.session
r.request.data             r.request.prefetch         r.request.timeout
r.request.deregister_hook  r.request.proxies          r.request.url
r.request.files            r.request.redirect         r.request.verify

r.request.headers 헤더를 제공합니다.

{'Accept': '*/*',
 'Accept-Encoding': 'identity, deflate, compress, gzip',
 'Authorization': u'Basic dXNlcjpwYXNz',
 'User-Agent': 'python-requests/0.12.1'}

그런 다음 r.request.data본문을 매핑으로 사용합니다. 원하는 urllib.urlencode경우 다음과 같이 변환 할 수 있습니다 .

import urllib
b = r.request.data
encoded_body = urllib.urlencode(b)

응답의 유형에 따라 .data-attribute가 누락되고 .body대신 -attribute가있을 수 있습니다.


답변

HTTP Toolkit 을 사용 하여 정확하게 수행 할 수 있습니다 .

코드 변경없이이 작업을 빠르게 수행해야하는 경우 특히 유용합니다. HTTP 툴킷에서 터미널을 열고 정상적으로 Python 코드를 실행할 수 있으며 모든 HTTP / HTTPS의 전체 내용을 볼 수 있습니다 즉시 요청하십시오.

필요한 모든 것을 할 수있는 무료 버전이 있으며 100 % 오픈 소스입니다.

저는 HTTP Toolkit의 제작자입니다. 나는 실제로 나를 위해 똑같은 문제를 해결하기 위해 실제로 그것을 만들었습니다! 지불 통합을 디버깅하려고했지만 SDK가 작동하지 않아 이유를 알 수 없었으며 실제로 올바르게 수정하기 위해 진행중인 작업을 알아야했습니다. 매우 실망 스럽지만 원시 트래픽을 볼 수 있으면 실제로 도움이됩니다.


답변

Python 2.x를 사용하는 경우 urllib2 오프너를 설치하십시오 . 헤더를 인쇄해야하지만 HTTPS를 칠하는 데 사용하는 다른 오프너와 결합해야 할 수도 있습니다.

import urllib2
urllib2.install_opener(urllib2.build_opener(urllib2.HTTPHandler(debuglevel=1)))
urllib2.urlopen(url)


답변

verbose구성 옵션을 사용하면 당신이 원하는 것을 볼 수 있습니다. 이 문서의 예 .

참고 : 아래의 주석을 읽으십시오. 자세한 구성 옵션을 더 이상 사용할 수없는 것 같습니다.


답변