Debian Codegraph @

examples/quickstart/response_headers.py

raw
1 #! /usr/bin/env python
2 # vi:ts=4:et
3
4 import pycurl
5 import re
6 from io import BytesIO
7
8 headers = {}
9 def header_function(header_line):
10 # HTTP standard specifies that headers are encoded in iso-8859-1.
11 header_line = header_line.decode('iso-8859-1')
12
13 # Header lines include the first status line (HTTP/1.x ...).
14 # We are going to ignore all lines that don't have a colon in them.
15 # This will botch headers that are split on multiple lines...
16 if ':' not in header_line:
17 return
18
19 # Break the header line into header name and value.
20 name, value = header_line.split(':', 1)
21
22 # Remove whitespace that may be present.
23 # Header lines include the trailing newline, and there may be whitespace
24 # around the colon.
25 name = name.strip()
26 value = value.strip()
27
28 # Header names are case insensitive.
29 # Lowercase name here.
30 name = name.lower()
31
32 # Now we can actually record the header name and value.
33 headers[name] = value
34
35 buffer = BytesIO()
36 c = pycurl.Curl()
37 c.setopt(c.URL, 'http://pycurl.io')
38 c.setopt(c.WRITEFUNCTION, buffer.write)
39 # Set our header function.
40 c.setopt(c.HEADERFUNCTION, header_function)
41 c.perform()
42 c.close()
43
44 # Figure out what encoding was sent with the response, if any.
45 # Check against lowercased header name.
46 encoding = None
47 if 'content-type' in headers:
48 content_type = headers['content-type'].lower()
49 match = re.search('charset=(\S+)', content_type)
50 if match:
51 encoding = match.group(1)
52 print('Decoding using %s' % encoding)
53 if encoding is None:
54 # Default encoding for HTML is iso-8859-1.
55 # Other content types may have different default encoding,
56 # or in case of binary data, may have no encoding at all.
57 encoding = 'iso-8859-1'
58 print('Assuming encoding is %s' % encoding)
59
60 body = buffer.getvalue()
61 # Decode using the encoding we figured out.
62 print(body.decode(encoding))