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

Running a ping test

With the basic knowledge of HTTP requests and the requests module in Python in mind, we will go through the rest of this chapter with a central problem: running a ping test. A ping test is a process in which you test the communication between your system and specific web servers, simply by making a request to each of the servers in question. By considering the HTTP response status code (potentially) returned by the server, the test is used to evaluate either the internet connection of your own system or the availability of the servers.

Ping tests are quite common among web administrators, who usually have to manage a large number of websites simultaneously. Ping tests are a good tool to quickly identify pages that are unexpectedly unresponsive or down. There are many tools that provide you with powerful options in ping tests and, in this chapter, we will be designing a ping test application that can concurrently send multiple web requests at the same time.

To simulate different HTTP response status codes to be sent back to our program, we will be using httpstat.us, a website that can generate various status codes and is commonly used to test how applications that make web requests can handle varying response. Specifically, to use a request that will return a 200 status code in a program, we can simply make a request to httpstat.us/200 and the same applies for other status codes. In our ping test program, we will have a list of httpstat.us URLs with different status codes.

Let's now a take look at the Chapter05/example2.py file, as shown in the following code:

# Chapter05/example2.py

import requests

def ping(url):
res = requests.get(url)
print(f'{url}: {res.text}')

urls = [
'http://httpstat.us/200',
'http://httpstat.us/400',
'http://httpstat.us/404',
'http://httpstat.us/408',
'http://httpstat.us/500',
'http://httpstat.us/524'
]

for url in urls:
ping(url)

print('Done.')

In this program, the ping() function takes in a URL and attempts to make a GET request to the site. It will then print out the content of the response returned by the server. In our main program, we have a list of different status codes that we mentioned earlier, each of which we will go through and call the ping() function on.

The final output after running the preceding example should be as follows:

http://httpstat.us/200: 200 OK
http://httpstat.us/400: 400 Bad Request
http://httpstat.us/404: 404 Not Found
http://httpstat.us/408: 408 Request Timeout
http://httpstat.us/500: 500 Internal Server Error
http://httpstat.us/524: 524 A timeout occurred
Done.

We see that our ping test program was able to obtain corresponding responses from the server.

主站蜘蛛池模板: 兴业县| 玉山县| 萨迦县| 丰原市| 蓬安县| 卢氏县| 洮南市| 祁连县| 稻城县| 琼海市| 巴彦县| 南郑县| 新乡市| 涿州市| 镇巴县| 锡林郭勒盟| 民勤县| 怀仁县| 十堰市| 博白县| 康乐县| 锡林浩特市| 阿图什市| 宜兴市| 漳浦县| 澄迈县| 醴陵市| 靖边县| 花莲县| 台中市| 图们市| 开封县| 武汉市| 南靖县| 洛扎县| 益阳市| 安龙县| 兴仁县| 灵川县| 云和县| 林甸县|