Skip to content

url

plantdb.client.url Link

Robust server‑availability checker with built‑in SSRF / safety guards.

ServerCheckResult dataclass Link

ServerCheckResult(url, status_code, ok, final_url, message)

Class containing information about the server's response.

is_server_available Link

is_server_available(url, timeout=5.0, max_redirects=2, max_retries=3, backoff_factor=0.3, allow_private_ip=False)

Check if a server is available by making an HTTP request to the given URL.

Parameters:

Name Type Description Default
url str

The URL of the server to check.

required
timeout float

The maximum number of seconds to wait for a response. Default is 5.0.

5.0
max_redirects int

The maximum number of redirects to follow. Default is 2.

2
max_retries int

The maximum number of retries in case of failure. Default is 3.

3
backoff_factor float

A factor to multiply the delay between retry attempts. Default is 0.3.

0.3
allow_private_ip bool

If True, the checker will accept URLs whose resolved IPs are private or non‑routable. Default is False.

False

Returns:

Type Description
ServerCheckResult

An object containing details about the server check result.

  • url (str): The original URL that was checked.
  • status_code (int): The HTTP status code received from the server.
  • ok (bool): True if the server responded with a successful status code, False otherwise.
  • final_url (str): The final URL after all redirects have been followed.

Examples:

>>> from plantdb.server.test_rest_api import TestRestApiServer
>>> from plantdb.client.url import is_server_available
>>> # EXAMPLE 1: Test with a valid online server
>>> result = is_server_available("https://example.com")
>>> print(result.ok)
True
>>> print(result.url)
https://example.com
>>> # EXAMPLE 2: Test with a valid local IP (allowed for test purposes) and a running server
>>> server = TestRestApiServer(test=True, ssl=False)  # initialize the server
>>> server.start()  # start the server
>>> result = is_server_available("http://127.0.0.1:5000", allow_private_ip=True)
>>> print(result.ok)
True
>>> print(result.message)
Valid URL.
>>> server.stop()  # stop the server
Notes

This function uses the requests library to perform HTTP requests. It handles retries and redirects according to the parameters provided.

See Also

requests.Session : The class used for sending HTTP requests. urllib.parse.urljoin : Used to resolve relative URLs in redirects.

Source code in plantdb/client/url.py
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
def is_server_available(
        url: str,
        timeout: float = 5.0,
        max_redirects: int = 2,
        max_retries: int = 3,
        backoff_factor: float = 0.3,
        allow_private_ip: bool = False,
) -> ServerCheckResult:
    """
    Check if a server is available by making an HTTP request to the given URL.

    Parameters
    ----------
    url : str
        The URL of the server to check.
    timeout : float, optional
        The maximum number of seconds to wait for a response. Default is 5.0.
    max_redirects : int, optional
        The maximum number of redirects to follow. Default is 2.
    max_retries : int, optional
        The maximum number of retries in case of failure. Default is 3.
    backoff_factor : float, optional
        A factor to multiply the delay between retry attempts. Default is 0.3.
    allow_private_ip : bool, optional
        If True, the checker will accept URLs whose resolved IPs are private or non‑routable.
        Default is False.

    Returns
    -------
    ServerCheckResult
        An object containing details about the server check result.

        - url (str): The original URL that was checked.
        - status_code (int): The HTTP status code received from the server.
        - ok (bool): True if the server responded with a successful status code,
          False otherwise.
        - final_url (str): The final URL after all redirects have been followed.

    Examples
    --------
    >>> from plantdb.server.test_rest_api import TestRestApiServer
    >>> from plantdb.client.url import is_server_available
    >>> # EXAMPLE 1: Test with a valid online server
    >>> result = is_server_available("https://example.com")
    >>> print(result.ok)
    True
    >>> print(result.url)
    https://example.com
    >>> # EXAMPLE 2: Test with a valid local IP (allowed for test purposes) and a running server
    >>> server = TestRestApiServer(test=True, ssl=False)  # initialize the server
    >>> server.start()  # start the server
    >>> result = is_server_available("http://127.0.0.1:5000", allow_private_ip=True)
    >>> print(result.ok)
    True
    >>> print(result.message)
    Valid URL.
    >>> server.stop()  # stop the server

    Notes
    -----
    This function uses the `requests` library to perform HTTP requests. It handles
    retries and redirects according to the parameters provided.

    See Also
    --------
    requests.Session : The class used for sending HTTP requests.
    urllib.parse.urljoin : Used to resolve relative URLs in redirects.
    """
    parsed = _parse_url(url, allow_private_ip=allow_private_ip)
    if not parsed:
        message = f"URL '{url}' is not a valid URL."
        logger.warning(message)
        return ServerCheckResult(url=url, status_code=0, ok=False, final_url=url, message=message)

    session = requests.Session()
    retry = Retry(
        total=max_retries,
        read=max_retries,
        connect=max_retries,
        backoff_factor=backoff_factor,
        status_forcelist=[500, 502, 503, 504],
        allowed_methods={"GET", "HEAD"},
    )
    adapter = HTTPAdapter(max_retries=retry, pool_connections=10, pool_maxsize=10)
    session.mount("http://", adapter)
    session.mount("https://", adapter)

    current_url = url
    for _ in range(max_redirects + 1):
        try:
            resp = session.get(
                current_url,
                timeout=timeout,
                verify=True,  # TLS cert verification
                allow_redirects=False,  # We handle redirects manually
                stream=True,  # Do not download the body unless we need to
            )
        except requests.RequestException as err:
            message = f"Request to {current_url} failed with: {err}"
            return ServerCheckResult(url=url, status_code=0, ok=False, final_url=current_url, message=message)

        # If we get a redirect, validate the target URL
        if 300 <= resp.status_code < 400:
            location = resp.headers.get("Location")
            if not location:
                message = f"Request to {current_url} (redirect) failed to determine next location."
                return ServerCheckResult(url=url, status_code=resp.status_code, ok=False, final_url=current_url, message=message)

            # Resolve relative URLs
            next_url = urllib.parse.urljoin(current_url, location)

            # Safety check on the next hop
            if not _parse_url(next_url, allow_private_ip=allow_private_ip):
                message = f"Request to {current_url} (redirect) is not a valid URL."
                return ServerCheckResult(url=url, status_code=resp.status_code, ok=False, final_url=next_url, message=message)

            current_url = next_url
            continue

        # Not a redirect – return the result
        return ServerCheckResult(
            url=url,
            status_code=resp.status_code,
            ok=200 <= resp.status_code < 400,
            final_url=current_url,
            message="Valid URL.",
        )

    # Too many redirects
    message = f"URL '{url}' has too many redirects to follow (>= {max_redirects})."
    return ServerCheckResult(url=url, status_code=0, ok=False, final_url=current_url, message=message)