File: http-client

package info (click to toggle)
ccache 4.12.2-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 5,188 kB
  • sloc: cpp: 47,282; asm: 28,570; sh: 8,674; ansic: 5,357; python: 685; perl: 68; makefile: 23
file content (51 lines) | stat: -rwxr-xr-x 1,482 bytes parent folder | download
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
#!/usr/bin/env python3

# This is a simple HTTP client to test readiness of the asynchronously
# launched HTTP server.

import base64
import sys
import time
import urllib.request


def run(url, timeout, basic_auth):
    deadline = time.time() + timeout
    req = urllib.request.Request(url, method="HEAD")
    if basic_auth:
        credentials = base64.b64encode(basic_auth.encode("ascii")).decode("ascii")
        req.add_header("Authorization", f"Basic {credentials}")
    while True:
        try:
            response = urllib.request.urlopen(req)
            print(f"Connection successful (code: {response.getcode()})")
            break
        except urllib.error.URLError as e:
            print(e.reason)
            if time.time() > deadline:
                sys.exit(f"All connection attempts failed within {timeout} seconds.")
            time.sleep(0.5)


if __name__ == "__main__":
    import argparse

    parser = argparse.ArgumentParser()
    parser.add_argument("--basic-auth", "-B", help="Basic auth tuple like user:pass")
    parser.add_argument(
        "--timeout",
        "-t",
        metavar="TIMEOUT",
        default=10,
        type=int,
        help="Maximum seconds to wait for successful connection attempt "
        "[default: 10 seconds]",
    )
    parser.add_argument("url", type=str, help="URL to connect to")
    args = parser.parse_args()

    run(
        url=args.url,
        timeout=args.timeout,
        basic_auth=args.basic_auth,
    )