筆記:Python的requests除錯



1.察看某python模組版本號

https://stackoverflow.com/questions/20180543

以requests模組為例

在BASH

$ pip freeze | grep requests
requests==2.23.0

在python shell

>>> import requests
>>> print(requests.__version__)
2.23.0

2. 顯示Request的詳細資訊

https://blog.anank.ke/w/Enable-Debug-Mode-for-Requests

加入程式碼
import logging

try:
    from http.client import HTTPConnection
except ImportError:
    from httplib import HTTPConnection
HTTPConnection.debuglevel = 1

logging.basicConfig()
logging.getLogger().setLevel(logging.DEBUG)
requests_log = logging.getLogger("requests.packages.urllib3")
requests_log.setLevel(logging.DEBUG)
requests_log.propagate = True

執行時在螢幕上可看到
  • 送出的request在
    send: 'POST /.....
  • server回覆的http response
    reply: 'HTTP/1.1 XXX .....
  • 回覆的header
    header: Content-Type: ....
其實requests的回覆也可以在程式中取得
resp = requests.get(in_url)
print ('URL:',      resp.url)
print ('status:',   resp.status_code)

print ('headers:',   resp.headers)

3. 解決http 302問題

加入重導向參數allow_redirects
resp = requests.post(url, data=obj, allow_redirects=True)

4. 顯示Request連線伺服器IP

https://stackoverflow.com/questions/22492484

針對requests 22.0.0之後版本,設定啟用設定stream可以簡單取的連線伺服器IP

>>> resp = requests.post(url, data=obj, allow_redirects=True, stream=True)
>>> print(resp.raw._connection.sock.getsockname())
('2001:b011:8:1050:3697:f6ff:fe83:84ec', 35054, 0, 0)

5. 在python shell載入script

python2

>>> execfile('runPython.py')

python2/python3

>>> exec(open("runPython.py").read())

6. 跑一次python script之後停在shell

$ python -i {your_python_script}



https://requests.readthedocs.io/en/master/user/quickstart/

留言