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

import sys
import argparse
from gruvi.http import HttpClient, parse_url

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

url = parse_url(args.url)

client = HttpClient()
client.connect(url.addr, ssl=url.ssl)
client.request('GET', url.target)

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

stdout = getattr(sys.stdout, 'buffer', sys.stdout)

while True:
    buf = resp.body.read(4096)
    if not buf:
        break
    stdout.write(buf)