Example 1: curl like URL downloaderΒΆ

 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
# Gruvi example program: a cURL like URL downloader

import sys
import argparse
from six.moves.urllib_parse import urlsplit
from gruvi.http import HttpClient

parser = argparse.ArgumentParser()
parser.add_argument('url')
args = parser.parse_args()

url = urlsplit(args.url)
if not url.scheme:
    url = urlsplit('http://{0}'.format(args.url))
is_ssl = url.scheme == 'https'
port = url.port if url.port else 443 if is_ssl else 80

client = HttpClient()
client.connect((url.hostname, port), ssl=is_ssl)
client.request('GET', url.path or '/')

response = client.getresponse()
if not 200 <= response.status <= 299:
    sys.stderr.write('Error: got status {}\n'.format(response.status))
    sys.exit(1)

stdout = getattr(sys.stdout, 'buffer', sys.stdout)
while True:
    buf = response.body.read(4096)
    if not buf:
        break
    stdout.write(buf)

Previous topic

Examples

Next topic

Example 2: echo server, using a StreamServer