73779315f4b3222efc33438817b41722683e0ba2
[sdc/sdc-distribution-client.git] /
1 from __future__ import absolute_import
2 from base64 import b64encode
3
4 from ..packages.six import b
5
6 ACCEPT_ENCODING = 'gzip,deflate'
7
8
9 def make_headers(keep_alive=None, accept_encoding=None, user_agent=None,
10                  basic_auth=None, proxy_basic_auth=None, disable_cache=None):
11     """
12     Shortcuts for generating request headers.
13
14     :param keep_alive:
15         If ``True``, adds 'connection: keep-alive' header.
16
17     :param accept_encoding:
18         Can be a boolean, list, or string.
19         ``True`` translates to 'gzip,deflate'.
20         List will get joined by comma.
21         String will be used as provided.
22
23     :param user_agent:
24         String representing the user-agent you want, such as
25         "python-urllib3/0.6"
26
27     :param basic_auth:
28         Colon-separated username:password string for 'authorization: basic ...'
29         auth header.
30
31     :param proxy_basic_auth:
32         Colon-separated username:password string for 'proxy-authorization: basic ...'
33         auth header.
34
35     :param disable_cache:
36         If ``True``, adds 'cache-control: no-cache' header.
37
38     Example::
39
40         >>> make_headers(keep_alive=True, user_agent="Batman/1.0")
41         {'connection': 'keep-alive', 'user-agent': 'Batman/1.0'}
42         >>> make_headers(accept_encoding=True)
43         {'accept-encoding': 'gzip,deflate'}
44     """
45     headers = {}
46     if accept_encoding:
47         if isinstance(accept_encoding, str):
48             pass
49         elif isinstance(accept_encoding, list):
50             accept_encoding = ','.join(accept_encoding)
51         else:
52             accept_encoding = ACCEPT_ENCODING
53         headers['accept-encoding'] = accept_encoding
54
55     if user_agent:
56         headers['user-agent'] = user_agent
57
58     if keep_alive:
59         headers['connection'] = 'keep-alive'
60
61     if basic_auth:
62         headers['authorization'] = 'Basic ' + \
63             b64encode(b(basic_auth)).decode('utf-8')
64
65     if proxy_basic_auth:
66         headers['proxy-authorization'] = 'Basic ' + \
67             b64encode(b(proxy_basic_auth)).decode('utf-8')
68
69     if disable_cache:
70         headers['cache-control'] = 'no-cache'
71
72     return headers