- Mastering Concurrency in Python
- Quan Nguyen
- 255字
- 2021-06-10 19:24:09
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.
- JavaScript全程指南
- Learning Flask Framework
- Java技術(shù)手冊(原書第7版)
- Java編程的邏輯
- Mastering Xamarin.Forms(Second Edition)
- Mastering Python Design Patterns
- R語言數(shù)據(jù)可視化:科技圖表繪制
- Delphi開發(fā)典型模塊大全(修訂版)
- Three.js權(quán)威指南:在網(wǎng)頁上創(chuàng)建3D圖形和動畫的方法與實踐(原書第4版)
- Jakarta EE Cookbook
- Visual FoxPro程序設(shè)計實驗教程
- PHP高性能開發(fā):基礎(chǔ)、框架與項目實戰(zhàn)
- C# 7.0核心技術(shù)指南(原書第7版)
- Pentaho Analytics for MongoDB Cookbook
- 趣學(xué)Python游戲編程