1818from __future__ import print_function
1919from __future__ import unicode_literals
2020
21- from collections import namedtuple
2221import json
2322
24- try :
25- from urllib import urlencode
26- from urllib import quote
27- except ImportError :
28- from urllib .parse import urlencode
29- from urllib .parse import quote
30-
31- try :
32- import httplib # Python 2
33- except ImportError :
34- import http .client as httplib # Python 3
35-
36- try :
37- import urllib2 # Python 2
38- except ImportError :
39- import urllib as urllib2 # Python 3
23+ try : # Python 2
24+ from urllib import urlencode , quote
25+ from urllib2 import urlopen , Request , HTTPError , URLError
26+ except ImportError : # Python 3
27+ from urllib .parse import urlencode , quote
28+ from urllib .request import urlopen , Request
29+ from urllib .error import HTTPError , URLError
4030
4131from attributecode import ERROR
4232from attributecode import Error
4636API call helpers
4737"""
4838
49- def build_api_url (url , api_username , api_key , license_key ):
50- """
51- Return a URl suitable for making an API call.
52- """
53- url = url .rstrip ('/' )
54-
55- payload = {'username' : api_username ,
56- 'api_key' : api_key ,
57- 'format' : 'json' }
58- encoded_payload = urlencode (payload )
59-
60- api_url = '%(url)s/%(license_key)s/?%(encoded_payload)s' % locals ()
61-
62- # handle special characters in URL such as space etc.
63- api_url = quote (api_url , safe = "%/:=&?~#+!$,;'@()*[]" )
64- return api_url
65-
66-
67- def get_license_data (self , url , api_username , api_key , license_key ):
68- """
69- Return a list of errors and a dictionary of license data, given a DejaCode
70- API url and a DejaCode license_key, send an API request to get license
71- data for the license_key, authenticating through an api_key and username.
72- """
73- full_url = build_api_url (url , api_username , api_key , license_key )
74-
75- errors = []
76- license_data = {}
77-
78- msg = 'Failed to collect license data for %(license_key)s.'
79-
80- try :
81- request = urllib2 .Request (full_url )
82- response = urllib2 .urlopen (request )
83- response_content = response .read ()
84- license_data = json .loads (response_content )
85-
86- except urllib2 .HTTPError as e :
87- if e .code == httplib .UNAUTHORIZED :
88- msg = msg + ('Authorization denied: '
89- 'Invalid api_username: %(api_username)s '
90- 'or api_key: %(api_key)s.' )
91- # FIXME: what about 404 and other cases?
92- errors .append (Error (ERROR , msg % locals ()))
93-
94- except urllib2 .URLError as e :
95- msg = msg + 'Network problem. Check your internet connection.'
96- errors .append (Error (ERROR , msg % locals ()))
97-
98- except Exception as e :
99- # only keep the first 100 char of the exception
100- emsg = repr (e )[:100 ]
101- msg = msg + ' Error: %(emsg)s'
102- errors .append (Error (ERROR , msg % locals ()))
103-
104- return errors , license_data
105-
106-
107- LicenseInfo = namedtuple ('LicenseInfo' , ['key' , 'name' , 'text' ])
108-
109-
110- def get_license_info (self , url , api_username , api_key , license_key ,
111- caller = get_license_data ):
112- """
113- Return a list of errors and a tuple of key, name, text for a given
114- license_key using a DejaCode API request at url. caller is the function
115- used to call the API and is used mostly for mocking in tests.
116- """
117- errors , data = get_license_data (url , api_username , api_key , license_key )
118- key = data .get ('key' )
119- name = data .get ('name' )
120- text = data .get ('full_text' )
121- return errors , LicenseInfo (key , name , text )
122-
12339
12440def request_license_data (url , api_key , license_key ):
12541 """
12642 Return a dictionary of license data.
12743 Send a request to a given API URL to gather license data for
12844 license_key, authenticating through an api_key.
12945 """
46+ headers = {
47+ 'Authorization' : 'Token %s' % api_key ,
48+ }
13049 payload = {
13150 'api_key' : api_key ,
13251 'key' : license_key ,
@@ -137,40 +56,42 @@ def request_license_data(url, api_key, license_key):
13756 encoded_payload = urlencode (payload )
13857 full_url = '%(url)s/?%(encoded_payload)s' % locals ()
13958 # handle special characters in URL such as space etc.
140- full_url = quote (full_url , safe = "%/:=&?~#+!$,;'@()*[]" )
141- headers = { 'Authorization' : 'Token %s' % api_key }
59+ quoted_url = quote (full_url , safe = "%/:=&?~#+!$,;'@()*[]" )
60+
14261 license_data = {}
14362 errors = []
14463 try :
145- request = urllib2 . Request (full_url , headers = headers )
146- response = urllib2 . urlopen (request )
147- response_content = response .read ()
64+ request = Request (quoted_url , headers = headers )
65+ response = urlopen (request )
66+ response_content = response .read (). decode ( 'utf-8' )
14867 license_data = json .loads (response_content )
14968 if not license_data ['results' ]:
150- msg = ( u"Invalid 'license': " + license_key )
69+ msg = u"Invalid 'license': %s" % license_key
15170 errors .append (Error (ERROR , msg ))
152- except urllib2 . HTTPError as http_e :
71+ except HTTPError as http_e :
15372 # some auth problem
15473 if http_e .code == 403 :
155- msg = (u"Authorization denied. Invalid '--api_key'. License generation is skipped." )
74+ msg = (u"Authorization denied. Invalid '--api_key'. "
75+ u"License generation is skipped." )
15676 errors .append (Error (ERROR , msg ))
15777 else :
15878 # Since no api_url/api_key/network status have
15979 # problem detected, it yields 'license' is the cause of
16080 # this exception.
161- msg = ( u"Invalid 'license': " + license_key )
81+ msg = u"Invalid 'license': %s" % license_key
16282 errors .append (Error (ERROR , msg ))
16383 except Exception as e :
16484 errors .append (Error (ERROR , str (e )))
16585 finally :
16686 license_data = license_data .get ('results' )[0 ] if license_data .get ('count' ) == 1 else {}
87+
16788 return license_data , errors
16889
16990
17091def get_license_details_from_api (url , api_key , license_key ):
17192 """
172- Returns the license_text of a given license_key using an API request.
173- Returns an empty string if the text is not available.
93+ Return the license_text of a given license_key using an API request.
94+ Return an empty string if the text is not available.
17495 """
17596 license_data , errors = request_license_data (url , api_key , license_key )
17697 license_name = license_data .get ('name' , '' )
0 commit comments