Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

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

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

from base64 import b64encode 

 

from ..packages import six 

 

 

ACCEPT_ENCODING = 'gzip,deflate' 

 

 

def make_headers(keep_alive=None, accept_encoding=None, user_agent=None, 

                 basic_auth=None, proxy_basic_auth=None): 

    """ 

    Shortcuts for generating request headers. 

 

    :param keep_alive: 

        If ``True``, adds 'connection: keep-alive' header. 

 

    :param accept_encoding: 

        Can be a boolean, list, or string. 

        ``True`` translates to 'gzip,deflate'. 

        List will get joined by comma. 

        String will be used as provided. 

 

    :param user_agent: 

        String representing the user-agent you want, such as 

        "python-urllib3/0.6" 

 

    :param basic_auth: 

        Colon-separated username:password string for 'authorization: basic ...' 

        auth header. 

 

    :param proxy_basic_auth: 

        Colon-separated username:password string for 'proxy-authorization: basic ...' 

        auth header. 

 

    Example: :: 

 

        >>> make_headers(keep_alive=True, user_agent="Batman/1.0") 

        {'connection': 'keep-alive', 'user-agent': 'Batman/1.0'} 

        >>> make_headers(accept_encoding=True) 

        {'accept-encoding': 'gzip,deflate'} 

    """ 

    headers = {} 

    if accept_encoding: 

        if isinstance(accept_encoding, str): 

            pass 

        elif isinstance(accept_encoding, list): 

            accept_encoding = ','.join(accept_encoding) 

        else: 

            accept_encoding = ACCEPT_ENCODING 

        headers['accept-encoding'] = accept_encoding 

 

    if user_agent: 

        headers['user-agent'] = user_agent 

 

    if keep_alive: 

        headers['connection'] = 'keep-alive' 

 

    if basic_auth: 

        headers['authorization'] = 'Basic ' + \ 

            b64encode(six.b(basic_auth)).decode('utf-8') 

 

    if proxy_basic_auth: 

        headers['proxy-authorization'] = 'Basic ' + \ 

            b64encode(six.b(proxy_basic_auth)).decode('utf-8') 

 

    return headers