Completing Asynchronous Support
This call to
.add_argument() adds a new
--asynchronous option to the application’s CLI. The
action argument is set to
"store_true", which tells
--asynchronous are Boolean flags that will store
True when provided at the command line.
_asynchronous_check() is defined as an asynchronous function using the
async keyword. This function takes a list of URLs and checks their connectivity asynchronously. Here, you define an inner
async function, which allows you to reuse the code that checks a single URL for connectivity.
Here, you define and initialize a placeholder
error variable, which will be used in the call to
display_check_result() later. Here, you define a
except statement to wrap the connectivity check. The
try block calls and awaits
site_is_online_async() with the target URL as an argument. If the call succeeds, then
result will be
This function runs a list of awaitable objects concurrently and returns an aggregated list of resulting values if all the awaitable objects complete successfully. To provide the list of awaitable objects, you use a generator expression that calls
_check() for each target URL.
The conditional statement checks if the user has provided the
--asynchronous flag at the command line. If that’s the case,
main() runs the connectivity checks asynchronously using
Go back to your command line and run the command seen on-screen. This shows that your application now has an
--asynchronous option that will run the connectivity checks asynchronously. Next, the content of the
sample-urls file is shown on-screen. Note the order of the websites, starting with
rpchecker runs the connectivity check synchronously, just like you did in a previous section. This is because you don’t provide the
--asynchronous flags. Note that the URLs are checked in the same order that they appear in the text file.
Now you use the
-a flag at the end of the line. This flag makes
rpchecker run the connectivity checks concurrently. Now the check results aren’t displayed in the same order as the URLs are entered, but in the order in which the responses come from the target websites.
Become a Member to join the conversation.