亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

Python實現(xiàn)打印http請求信息

 更新時間:2024年06月28日 10:45:00   作者:HMJ_  
這篇文章主要介紹了Python實現(xiàn)打印http請求信息方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教

問題

我們在開發(fā)過程中,為了快速驗證接口,

經(jīng)常采用postman或者Python代碼先行驗證的方式,確保接口正常,

在測試接口過程中偶爾會遇到接口異常,這時候要和打印完整的http請求,

幫助接口開發(fā)人員確認問題;

方法

僅僅是打印出這些信息,很簡單:

import requests
response = requests.post('http://httpbin.org/post', data={'key1':'value1'})
print(response.request.headers)
print(response.request.body)

或者:

import requests

def pretty_print_POST(req):
    print('{}\n{}\r\n{}\r\n\r\n{}'.format(
        '-----------START-----------',
        req.method + ' ' + req.url,
        '\r\n'.join('{}: {}'.format(k, v) for k, v in req.headers.items()),
        req.body,
    ))

req = requests.Request('POST','http://stackoverflow.com',headers={'X-Custom':'Test'},data='a=1&b=2')
prepared = req.prepare()
pretty_print_POST(prepared)

s = requests.Session()
resp = s.send(prepared)
print(resp.text)

但如果你想要在進行請求之前對http頭和數(shù)據(jù)進行操作,也是使用prepare:

from requests import Request, Session

s = Session()

req = Request('POST', url, data=data, headers=headers)
prepped = req.prepare()

# do something with prepped.body
prepped.body = 'No, I want exactly this as the body.'

# do something with prepped.headers
del prepped.headers['Content-Type']

resp = s.send(prepped,
    stream=stream,
    verify=verify,
    proxies=proxies,
    cert=cert,
    timeout=timeout
)

print(resp.status_code)

python 的庫的用法去對應(yīng)的庫的幫助文檔里去找,更為方便些;

總結(jié)

以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。

相關(guān)文章

最新評論