官术网_书友最值得收藏!

Support from httpstat.us and simulation in Python

In addition to different options for status codes, the httpstat.us website additionally provides a way to simulate a delay in its response when we send in requests. Specifically, we can customize the delay time (in milliseconds) with a query argument in our GET request. For example, httpstat.us/200?sleep=5000 will return a response after five seconds of delay.

Now, let us see how a delay like this would affect the execution of our program. Consider the Chapter05/example5.py file, which contains the current request logic of our ping test application but has a different URL list:

# Chapter05/example5.py

import threading
import requests

class MyThread(threading.Thread):
def __init__(self, url):
threading.Thread.__init__(self)
self.url = url
self.result = None

def run(self):
res = requests.get(self.url)
self.result = f'{self.url}: {res.text}'

urls = [
'http://httpstat.us/200',
'http://httpstat.us/200?sleep=20000',
'http://httpstat.us/400'
]

threads = [MyThread(url) for url in urls]
for thread in threads:
thread.start()
for thread in threads:
thread.join()
for thread in threads:
print(thread.result)

print('Done.')

Here we have a URL that will take around 20 seconds to return a response. Considering that we will block the main program until all threads finish their execution (with the join() method), our program will most likely appear to be hanging for 20 seconds before any response is printed out.

Run the program to experience this for yourself. A 20 second delay will occur (which will make the execution take significantly longer to finish) and we will obtain the following output:

http://httpstat.us/200: 200 OK
http://httpstat.us/200?sleep=20000: 200 OK
http://httpstat.us/400: 400 Bad Request
Took 22.60 seconds
Done.
主站蜘蛛池模板: 万宁市| 环江| 武城县| 南华县| 阳曲县| 望都县| 韶关市| 永年县| 正蓝旗| 稻城县| 高密市| 仲巴县| 林西县| 广东省| 吉木萨尔县| 和平县| 永州市| 墨竹工卡县| 乌鲁木齐市| 三河市| 阳新县| 外汇| 麦盖提县| 兰溪市| 民丰县| 巍山| 鸡东县| 南雄市| 增城市| 彰化县| 石屏县| 晋城| 商河县| 施甸县| 外汇| 清苑县| 曲阳县| 民县| 富阳市| 永州市| 临泽县|