Refactor Your Uptime Bot
In the previous lesson, you built out this basic version of the uptime bot. In this lesson, you’re just going to do a bit of refactoring to make the code a bit better, move it into a function, and improve the
You want to start by actually moving this success statement out of the
try block. Instead, you want to put it into an
else block. You can have
else blocks in
except statements, and the code in here only executes if the
except block didn’t run into any error.
So, only then, we want to print out the
"success". Now let’s also make the error message a bit more meaningful. I’m going to catch the exception as
e, assign it to a variable name, and then create an f-string here where I can print out the error message.
is up! A happy success message. Okay,
time.sleep()—you can leave that as is. Then let’s move this whole thing into a function. I’m going to indent it one and then create a function definition here, and I’m going to call it
uptime_bot(). It takes as input a
url comes from out here and then the function takes a
url and then executes the code logic. Now, instead of defining the
url up here, I’m going to also take this one and you’ll move it down into the
if __name__ block.
02:23 This is what you’d expect. Now let’s try it again with a valid URL, run the same code again, and this seems to be working fine. Now you’re getting that the Python documentation is up, which is always a good sign to know that the Python documentation is actually live on the internet. All right, so one thing you might notice here is yes, you did limit how often and how quickly the code runs by letting your code sleep, but it still just keeps going and keeps going, which might be fine if you have this deployed somewhere and you just want to constantly check. Maybe you want to change the time how often does it check to a minute or something like that. Let me stop this.
03:12 So instead of keeping it running all the time if your code encounters an exception, in the next lesson, you’re going to build the uptime bot out a little more to accept an argument where you can say after how many failed attempts it should stop and then do something else instead of keep checking.
Become a Member to join the conversation.