Updated packages and code to python3. Won't work with python 2
[twitter-api-cdsw] / oauthlib / oauth1 / rfc5849 / utils.py
1 # -*- coding: utf-8 -*-
2 """
3 oauthlib.utils
4 ~~~~~~~~~~~~~~
5
6 This module contains utility methods used by various parts of the OAuth
7 spec.
8 """
9 from __future__ import absolute_import, unicode_literals
10
11 try:
12     import urllib2
13 except ImportError:
14     import urllib.request as urllib2
15
16 from oauthlib.common import quote, unquote, bytes_type, unicode_type
17
18 UNICODE_ASCII_CHARACTER_SET = ('abcdefghijklmnopqrstuvwxyz'
19                                'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
20                                '0123456789')
21
22
23 def filter_params(target):
24     """Decorator which filters params to remove non-oauth_* parameters
25
26     Assumes the decorated method takes a params dict or list of tuples as its
27     first argument.
28     """
29     def wrapper(params, *args, **kwargs):
30         params = filter_oauth_params(params)
31         return target(params, *args, **kwargs)
32
33     wrapper.__doc__ = target.__doc__
34     return wrapper
35
36
37 def filter_oauth_params(params):
38     """Removes all non oauth parameters from a dict or a list of params."""
39     is_oauth = lambda kv: kv[0].startswith("oauth_")
40     if isinstance(params, dict):
41         return list(filter(is_oauth, list(params.items())))
42     else:
43         return list(filter(is_oauth, params))
44
45
46 def escape(u):
47     """Escape a unicode string in an OAuth-compatible fashion.
48
49     Per `section 3.6`_ of the spec.
50
51     .. _`section 3.6`: http://tools.ietf.org/html/rfc5849#section-3.6
52
53     """
54     if not isinstance(u, unicode_type):
55         raise ValueError('Only unicode objects are escapable. ' +
56                          'Got %s of type %s.' % (u, type(u)))
57     # Letters, digits, and the characters '_.-' are already treated as safe
58     # by urllib.quote(). We need to add '~' to fully support rfc5849.
59     return quote(u, safe=b'~')
60
61
62 def unescape(u):
63     if not isinstance(u, unicode_type):
64         raise ValueError('Only unicode objects are unescapable.')
65     return unquote(u)
66
67
68 def parse_keqv_list(l):
69     """A unicode-safe version of urllib2.parse_keqv_list"""
70     # With Python 2.6, parse_http_list handles unicode fine
71     return urllib2.parse_keqv_list(l)
72
73
74 def parse_http_list(u):
75     """A unicode-safe version of urllib2.parse_http_list"""
76     # With Python 2.6, parse_http_list handles unicode fine
77     return urllib2.parse_http_list(u)
78
79
80 def parse_authorization_header(authorization_header):
81     """Parse an OAuth authorization header into a list of 2-tuples"""
82     auth_scheme = 'OAuth '.lower()
83     if authorization_header[:len(auth_scheme)].lower().startswith(auth_scheme):
84         items = parse_http_list(authorization_header[len(auth_scheme):])
85         try:
86             return list(parse_keqv_list(items).items())
87         except (IndexError, ValueError):
88             pass
89     raise ValueError('Malformed authorization header')

Benjamin Mako Hill || Want to submit a patch?