当前位置: 首页 > 工具软件 > HTTPretty > 使用案例 >

python post 请求超时,python – 模拟HTTP请求,使用HTTPretty超时

陈俊誉
2023-12-01

同时我明白了,使用

HTTPretty callback body似乎产生了理想的行为.请参阅下面的内联评论.

这实际上与我正在寻找的不完全相同(它不是一个无法访问的服务器,因此请求超时但是一旦到达就抛出超时异常的服务器,但是,效果对我而言是相同的用例.

不过,如果有人知道不同的解决方案,我很期待.

import httpretty

import requests

# enable HTTPretty

httpretty.enable()

# create a callback body that raises an exception when opened

def exceptionCallback(request, uri, headers):

# raise your favourite exception here, e.g. requests.ConnectionError or requests.Timeout

raise requests.Timeout('Connection timed out.')

# set up a mock and use the callback function as response's body

httpretty.register_uri(

method=httpretty.GET,

uri='http://www.fakeurl.com',

status=200,

body=exceptionCallback

)

# try to get a response from the mock server and catch the exception

try:

response = requests.get('http://www.fakeurl.com')

except requests.Timeout as e:

print('requests.Timeout exception got caught...')

print(e)

# do whatever...

# clean up

httpretty.disable()

httpretty.reset()

 类似资料: