내 Python 어플리케이션에서 전송되는 전체 HTTP 요청을 보려면 어떻게 해야 합니까?
ㅇㅇㅇㅇㅇㅇㅇㅇ를 사용하고 requests
HTTPS, PayPal API, API.불행하게도 PayPal에서 오류가 발생하고 있으며, PayPal 지원에서는 오류의 원인이나 원인을 파악할 수 없습니다., 포함했습니다.헤더를 포함한 전체 요청을 제공해주세요'라고 합니다.
내가 어떻게 그럴 수 있을까?
간단한 방법: 요청의 최신 버전(1.x 이상)에서 로깅을 활성화합니다.
는 " " 를 합니다.http.client
★★★★★★★★★★★★★★★★★」logging
여기서 설명하는 것처럼 로깅 상세도를 제어하는 모듈 구성.
데모
링크된 문서에서 발췌한 코드:
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
답니다 it 가 있는 요청 있습니다.필요한 정보가 포함된 요청 속성이 있습니다.
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
수도 빠졌을 수도 있습니다..body
거기 . - 거기 있어. - 거기 있어.
HTTP Toolkit을 사용하면 이 작업을 정확하게 수행할 수 있습니다.
코드 변경 없이 빠르게 해야 할 경우 특히 유용합니다. HTTP Toolkit에서 단말기를 열고 그곳에서 정상적으로 Python 코드를 실행하면 모든 HTTP/HTTPS 요청의 전체 내용을 즉시 볼 수 있습니다.
필요한 모든 것을 할 수 있는 무료 버전이 있으며 100% 오픈 소스입니다.
저는 HTTP Toolkit을 만든 사람입니다.저는 얼마 전에 같은 문제를 해결하기 위해 직접 이 툴을 구축했습니다.저도 결제 통합을 디버깅하려고 했는데 SDK가 작동하지 않아서 이유를 알 수 없었고, 제대로 수정하려면 실제로 무슨 일이 일어나고 있는지 알아야 했습니다.매우 답답하지만, 원시 교통을 볼 수 있다는 것은 큰 도움이 됩니다.
Python 2.x 를 사용하고 있는 경우는, urlib2 오프너를 인스톨 해 주세요.HTTPS에 접속하기 위해서 사용하고 있는 다른 Opener와 조합할 필요가 있는 경우도 있습니다만, 헤더를 인쇄합니다.
import urllib2
urllib2.install_opener(urllib2.build_opener(urllib2.HTTPHandler(debuglevel=1)))
urllib2.urlopen(url)
HTTP 로컬 요구를 디버깅하는 훨씬 간단한 방법은 넷캣을 사용하는 것입니다.뛰면
nc -l 1234
1234
HTTP " " " " 입니다.은 하다, , 하다, 하다를 통해서 할 수 있어요.http://localhost:1234/foo/foo/...
.
단말기에 엔드포인트로 전송한 원시 데이터가 표시됩니다.예를 들어 다음과 같습니다.
POST /foo/foo HTTP/1.1
Accept: application/json
Connection: keep-alive
Host: example.com
Accept-Language: en-en
Authorization: Bearer ay...
Content-Length: 15
Content-Type: application/json
{"test": false}
그verbose
구성 옵션을 사용하면 원하는 항목을 볼 수 있습니다.설명서에 예가 있습니다.
메모: 다음 코멘트를 읽어주세요.자세한 구성 옵션은 더 이상 사용할 수 없는 것 같습니다.
완전히 동작하는 로깅 시스템은 없습니다(요청 2.26에서는 매우 오래된 버전에서는 다른 동작이 있었을 가능성이 있습니다).
좋은 해결책은 '훅'을 사용하여 발생하는 대로 세부 정보를 인쇄하는 것입니다.
이는 https://findwork.dev/blog/advanced-usage-python-requests-timeouts-retries-hooks/에서 충분히 설명되어 있습니다.
"모든 것을 파괴한다"는 제목으로
여기서 링크가 끊어질 경우를 대비해서
import requests
from requests_toolbelt.utils import dump
def logging_hook(response, *args, **kwargs):
data = dump.dump_all(response)
print(data.decode('utf-8'))
http = requests.Session()
http.hooks["response"] = [logging_hook]
http.get("https://api.openaq.org/v1/cities", params={"country": "BA"})
이번 결과는 전송된 쿼리와 수신된 응답의 완전한 트레이스입니다.
POST와 많은 헤더를 사용하여 성공적으로 시도했습니다만, 동작합니다.install requests_toolbelt를 pip으로 설치하는 것을 잊지 마십시오.
# Output
< GET /v1/cities?country=BA HTTP/1.1
< Host: api.openaq.org
> HTTP/1.1 200 OK
> Content-Type: application/json; charset=utf-8
> Transfer-Encoding: chunked
> Connection: keep-alive
>
{
"meta":{
"name":"openaq-api",
"license":"CC BY 4.0",
"website":"https://docs.openaq.org/",
"page":1,
"limit":100,
"found":1
},
"results":[
{
"country":"BA",
"name":"Goražde",
"city":"Goražde",
"count":70797,
"locations":1
}
]
}
이전 답변은 "완전히 작동하지 않는 것"으로 시작하여 다음과 같은 완벽한 솔루션을 제공하기 때문에 다운 투표된 것으로 보입니다.
- 를 인스톨 합니다.
requests_toolbelt
와의 유틸리티의 수집pip install requests-toolbelt
. - 다음과 같이 사용합니다.
import requests from requests_toolbelt.utils import dump response = requests.get("https://v2.jokeapi.dev/joke/Any?safe-mode") print(dump.dump_all(response).decode("utf-8"))
다른 사람들이 지적한 바와 같이 좋은 점이 있다.requests-toolbelt
요청 후크를 사용하여 요청 및 응답 콘텐츠를 덤프할 수 있는 편리한 기능을 갖춘 모듈입니다.유감스럽게도 (현재는) 요청이 정상적으로 완료되었을 때 호출되는 후크만 있습니다.항상 그런 건 아니에요.즉, 요청은 다음과 같은 결과가 될 수 있습니다.ConnectionError
또는Timeout
예외입니다.
그requests-toolbelt
모듈 자체에서도 완료된 요청만 덤프하는 공용 기능을 제공합니다.단, 비공개 API와 세션 서브클래싱을 사용하여 송신 전 요청 로깅과 수신 후 응답 로깅을 구현할 수 있습니다.
주의: 코드는 구현 상세/비공개 API에 의존합니다.requests-toolbelt
장차 예기치 않게 파손될 수 있습니다.
import requests
from requests_toolbelt.utils import dump
class MySession(requests.Session):
def send(self, req, *args, **kwargs):
prefixes = dump.PrefixSettings(b'< ', b'> ')
data = bytearray()
try:
dump._dump_request_data(req, prefixes, data)
resp = super().send(req, *args, **kwargs)
dump._dump_response_data(resp, prefixes, data)
finally:
print(data.decode('utf-8'))
return resp
사용 예를 다음에 나타냅니다.
>>> MySession().get('https://httpbin.org/headers')
< GET /headers HTTP/1.1
< Host: httpbin.org
< User-Agent: python-requests/2.25.1
< Accept-Encoding: gzip, deflate
< Accept: */*
< Connection: keep-alive
<
> HTTP/1.1 200 OK
> Date: Fri, 19 Aug 2022 10:43:51 GMT
> Content-Type: application/json
> Content-Length: 225
> Connection: keep-alive
> Server: gunicorn/19.9.0
> Access-Control-Allow-Origin: *
> Access-Control-Allow-Credentials: true
>
{
"headers": {
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate",
"Host": "httpbin.org",
"User-Agent": "python-requests/2.25.1"
}
}
>>> MySession().get('https://non.existent')
< GET / HTTP/1.1
< Host: non.existent
< User-Agent: python-requests/2.25.1
< Accept-Encoding: gzip, deflate
< Accept: */*
< Connection: keep-alive
<
Traceback (most recent call last):
File "/usr/lib/python3/dist-packages/urllib3/connection.py", line 169, in _new_conn
conn = connection.create_connection(
File "/usr/lib/python3/dist-packages/urllib3/util/connection.py", line 73, in create_connection
for res in socket.getaddrinfo(host, port, family, socket.SOCK_STREAM):
File "/usr/lib/python3.10/socket.py", line 955, in getaddrinfo
for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
socket.gaierror: [Errno -2] Name or service not known
...
언급URL : https://stackoverflow.com/questions/10588644/how-can-i-see-the-entire-http-request-thats-being-sent-by-my-python-application
'programing' 카테고리의 다른 글
Liquibase/MariaDB 또는 Mysql에 대한 FULLTEXT 지수 (0) | 2022.09.18 |
---|---|
Mariadb / Mysql BUG ? : 서브쿼리에서 'master'별로 그룹화 (0) | 2022.09.18 |
인덱스를 사용하여 panda DataFrame의 특정 셀 값 설정 (0) | 2022.09.18 |
MySql 표시 성능 (0) | 2022.09.18 |
가변 길이 어레이 사용에 대한 오버헤드가 있습니까? (0) | 2022.08.28 |