The user wants a Python script to check website uptime and response times.
-
Identify the core requirements:
- Input: A list of URLs or a single URL.
- Functionality: Send an HTTP request to the URL(s).
- Metrics: Measure response time (latency) and determine status (UP/DOWN based on HTTP status code).
- Output: Display the results clearly (e.g., console output, log to a file).
-
Choose the right tools:
- HTTP Library:
requests is the industry standard in Python for this. It's easy to use and handles timing well.
- Timing:
requests has a built-in elapsed attribute which is perfect.
- Asynchronous vs. Synchronous:
- Synchronous (
requests): Easy to write, fine for a small list of sites.
- Asynchronous (
aiohttp + asyncio): Much better for checking many sites simultaneously.
- Decision: I should provide a simple synchronous version first (easier to understand) and maybe an async version or at least mention how to handle multiple sites efficiently (using
ThreadPoolExecutor). Let's stick to a clean, object-oriented approach using requests for simplicity and readability, perhaps adding concurrent.futures for checking multiple sites to make it robust without the complexity of async/await for a beginner script.
-
Drafting the Script Structure:
- Imports:
requests, time, sys (maybe for args), datetime.
- Configuration: User-agent (to avoid 403s from some sites), Timeout settings.
- The Check Function:
- Try/Except block (crucial for network errors).
requests.get()
- Capture
response.status_code and response.elapsed.total_seconds().
- Define "UP" (usually 200 OK, but 3xx might be okay depending on context. Let's stick to 200 for simplicity, or < 400).
- Handle exceptions (ConnectionError, Timeout).
-
Refining the Logic (Iterative process):
-
Attempt 1 (Mental Draft):
import requests
r = requests.get(url)
print(r.status_code, r.elapsed)
Critique: Too basic. Needs error handling.
-
Attempt 2 (Adding error handling):
try:
r = requests.get(url, timeout=5)
if r.status_code == 200:
return "UP", time
else:
return "DOWN", time
except:
return "ERROR", 0
Critique: Better. The timeout is important so the script doesn't hang.
-
Attempt 3 (Adding features):
- Check multiple sites.
- Color-coded output (optional but nice).
- Logging.
-
Developing the Final Code Structure:
- I will create a class-based structure or a clean function set. Let's go with functions to keep it script-like.
- Feature: Check a single site.
- Feature: Loop through a list.
- Feature: Output formatting.
-
Writing the Code (Mental or Scratchpad):
import requests
import time
from datetime import datetime
def check_uptime(url):
start_time = time.time()
try:
response = requests.get(url, timeout=10)
end_time = time.time()
# Logic for status
# ...
except requests.exceptions.RequestException as e:
# Logic for failure
# ...
-
Addressing specific edge cases:
- HTTPS vs HTTP: Let the user specify.
- Redirects:
allow_redirects=True (default) is usually fine.
- Thresholds: Is a 5-second response "UP"? Technically yes, but it's slow. I should report the time and let the user decide, or flag it as "SLOW".
-
Constructing the Example:
I will provide a robust script that:
- Imports necessary libraries.
- Defines a list of sites.
- Iterates through them.
- Uses
try-except to catch network failures.
- Prints a formatted report.
Self-Correction during coding: Using concurrent.futures is a "nice to have" but adds complexity. I'll stick to a sequential check for the basic version but write the code so it's easy to expand. Actually, for a "production-like" utility script, handling exceptions cleanly is key.
-
Final Polish of the Code:
- Add a User-Agent header (some sites block default Python requests).
- Format the time in milliseconds (ms) or seconds (s). Seconds with 3 decimals is standard.
- Add status colors (Green/Red) using ANSI codes for better readability in terminals.
-
Output Explanation:
- Explain what libraries are needed (
pip install requests).
- Explain how the code works.
- Show how to run it.
-
Review against User Prompt: "Implement a Python script to check website uptime and response times."
- Uptime: Handled via status code checks.
- Response Time: Handled via
response.elapsed.
Bonus: I will add a small loop option to show how to monitor continuously.
(Self-Correction during final code generation):
Make sure to handle the requests.exceptions specifically rather than a bare except. This makes debugging easier.
Let's structure the response:
- Prerequisites (install requests).
- The Code (well-commented).
- Explanation of key parts.
- Enhancements (Async, Logging).
This looks like a solid plan. Proceed to generate output.
Here is a complete, robust Python script to check website uptime and response times.
This script uses the popular requests library. It handles errors gracefully (like domains that don't exist or connection timeouts) and formats the output into a readable table.
Prerequisites
You will need the requests library. Install it via pip:
pip install requests
The Python Script
Save this code as uptime_checker.py.
import requests
import time
import sys
from datetime import datetime
# Configuration
WEBSITES = [
"https://www.google.com",
"https://www.github.com",
"https://www.python.org",
"https://thisurldoesnotexist12345.com", # Intentionally broken for demo
"https://httpstat.us/500" # Intentionally returning 500 error
]
REQUEST_TIMEOUT = 5 # Seconds to wait before giving up
USER_AGENT = "Mozilla/5.0 (compatible; UptimeChecker/1.0)"
def check_website(url):
"""
Checks the uptime and response time of a single URL.
Returns a dictionary with status data.
"""
result = {
"url": url,
"status": "UNKNOWN",
"response_time": None,
"status_code": None
}
try:
start_time = time.time()
# make the GET request
response = requests.get(
url,
headers={"User-Agent": USER_AGENT},
timeout=REQUEST_TIMEOUT,
allow_redirects=True # Follow redirects (e.g., http -> https)
)
end_time = time.time()
# Calculate elapsed time in milliseconds
elapsed_ms = (end_time - start_time) * 1000
result["response_time"] = f"{elapsed_ms:.2f} ms"
result["status_code"] = response.status_code
# Determine UP or DOWN based on status code
if 200 <= response.status_code < 400:
result["status"] = "UP"
else:
result["status"] = "DOWN (HTTP Error)"
except requests.exceptions.Timeout:
result["status"] = "DOWN (Timeout)"
except requests.exceptions.ConnectionError:
result["status"] = "DOWN (Connection Error)"
except requests.exceptions.RequestException as e:
result["status"] = f"DOWN (Error: {e})"
return result
def format_output(results):
"""
Prints the results in a clean table format.
"""
print(f"\n{'='*80}")
print(f"WEBSITE UPTIME REPORT - {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
print(f"{'='*80}")
# Table Header
print(f"{'URL':<40} | {'STATUS':<20} | {'TIME (ms)':<12} | {'CODE':<5}")
print(f"{'-'*40}-+-{'-'*20}-+-{'-'*12}-+-{'-'*5}")
for res in results:
url_display = res['url'][:38] + '..' if len(res['url']) > 40 else res['url']
code_display = res['status_code'] if res['status_code'] else "N/A"
time_display = res['response_time'] if res['response_time'] else "N/A"
# Simple color coding for terminal (optional visual aid)
status = res['status']
if "UP" in status:
status_str = f"\033[92m{status}\033[0m" # Green
else:
status_str = f"\033[91m{status}\033[0m" # Red
print(f"{url_display:<40} | {status_str:<29} | {time_display:<12} | {code_display}")
print(f"{'='*80}\n")
if __name__ == "__main__":
all_results = []
print(f"Checking {len(WEBSITES)} websites...")
for site in WEBSITES:
# Ensure URL has schema, default to https if missing
if not site.startswith(('http://', 'https://')):
site = "https://" + site
res = check_website(site)
all_results.append(res)
# Optional: Print a dot for every check to show progress
sys.stdout.write('.')
sys.stdout.flush()
format_output(all_results)
How it works
- Configuration: The
WEBSITES list holds the URLs you want to monitor. REQUEST_TIMEOUT ensures the script doesn't hang on a slow server.
check_website Function:
- Uses
time.time() before and after the request to calculate the Response Time in milliseconds.
- Uses
try...except blocks to catch specific network errors.
- 200-399 Status Codes: Considered "UP".
- 400+ Status Codes: Considered "DOWN" (e.g., 404 Not Found, 500 Server Error).
- Exceptions: Catches Timeouts and DNS failures (ConnectionError).
format_output Function:
- Uses Python f-strings to create a neatly aligned table.
- Includes ANSI color codes (Green for UP, Red for DOWN) for better readability in the terminal.
Example Output
When you run python uptime_checker.py, you will see:
Checking 5 websites...
.....
================================================================================
WEBSITE UPTIME REPORT - 2023-10-27 10:00:00
================================================================================
URL | STATUS | TIME (ms) | CODE
------------------------------------------+----------------------+--------------+-------
https://www.google.com | UP | 45.12 ms | 200
https://www.github.com | UP | 120.55 ms | 200
https://thisurldoesnotexist12345.com | DOWN (Connection Error) | N/A | N/A
https://httpstat.us/500 | DOWN (HTTP Error) | 210.00 ms | 500
================================================================================
Advanced Improvements
If you want to take this to a production level, consider adding:
- Concurrency: Use
concurrent.futures (ThreadPoolExecutor) to check 50+ websites simultaneously instead of one by one.
- Alerting: Add an
if "DOWN" in status: block that uses smtplib to send an email or calls a Slack/Discord webhook when a site goes down.
- Logging: Write the results to a CSV file or a database (like SQLite or InfluxDB) to track history and plot graphs over time.