- Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathlesson06_http_status.py
More file actions
Latest commit
52 lines (49 loc) · 1.67 KB
/
Copy pathlesson06_http_status.py
File metadata and controls
52 lines (49 loc) · 1.67 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# SuperFastPython.com
# example of checking the status of multiple webpages
importasyncio
importurllib.parse
# get the http status of a webpage
asyncdefget_status(url):
# split the url into components
url_parsed=urllib.parse.urlsplit(url)
# open the connection, assumes https
reader, writer=awaitasyncio.open_connection(
url_parsed.hostname, 443, ssl=True)
# send GET request
query=f'GET {url_parsed.path} HTTP/1.1\r\n' \
f'Host: {url_parsed.hostname}\r\n\r\n'
# write query to socket
writer.write(query.encode())
# wait for the bytes to be written to the socket
awaitwriter.drain()
# read the single line response
response=awaitreader.readline()
# close the connection
writer.close()
# decode and strip white space
status=response.decode().strip()
# return the response
returnstatus
# main coroutine
asyncdefmain():
# list of top 10 websites to check
sites= ['https://www.google.com/',
'https://www.youtube.com/',
'https://www.facebook.com/',
'https://twitter.com/',
'https://www.instagram.com/',
'https://www.baidu.com/',
'https://www.wikipedia.org/',
'https://yandex.ru/',
'https://yahoo.com/',
'https://www.whatsapp.com/']
# create all coroutine requests
coros= [get_status(url) forurlinsites]
# execute all coroutines and wait
results=awaitasyncio.gather(*coros)
# process all results
forurl, statusinzip(sites, results):
# report status
print(f'{url:25}:\t{status}')
# run the asyncio program
asyncio.run(main())