Skip to content

Commit 8b773d9

Browse files
authored
Merge pull request #301 from nexB/280-python3-cleanup
280 python3 cleanup
2 parents 8a47b41 + 18bc355 commit 8b773d9

File tree

6 files changed

+126
-185
lines changed

6 files changed

+126
-185
lines changed

src/attributecode/api.py

Lines changed: 23 additions & 102 deletions
Original file line numberDiff line numberDiff line change
@@ -18,25 +18,15 @@
1818
from __future__ import print_function
1919
from __future__ import unicode_literals
2020

21-
from collections import namedtuple
2221
import 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

4131
from attributecode import ERROR
4232
from attributecode import Error
@@ -46,87 +36,16 @@
4636
API 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

12440
def 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

17091
def 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', '')

src/attributecode/cmd.py

Lines changed: 6 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,6 @@
1818
from __future__ import print_function
1919
from __future__ import unicode_literals
2020

21-
import codecs
2221
import logging
2322
import os
2423
from os.path import exists, join
@@ -28,19 +27,11 @@
2827
# silence unicode literals warnings
2928
click.disable_unicode_literals_warning = True
3029

31-
import attributecode
32-
from attributecode import CRITICAL
33-
from attributecode import ERROR
34-
from attributecode import INFO
35-
from attributecode import NOTSET
36-
from attributecode import WARNING
3730
from attributecode import __about_spec_version__
3831
from attributecode import __version__
39-
from attributecode import attrib
40-
from attributecode import Error
41-
from attributecode import gen
32+
from attributecode.attrib import generate_and_save as attrib_generate_and_save
33+
from attributecode.gen import generate as gen_generate
4234
from attributecode import model
43-
from attributecode.model import About
4435
from attributecode import severities
4536
from attributecode.util import extract_zip
4637
from attributecode.util import to_posix
@@ -147,7 +138,7 @@ def inventory(location, output, quiet, format):
147138
# accept zipped ABOUT files as input
148139
location = extract_zip(location)
149140

150-
errors, abouts = attributecode.model.collect_inventory(location)
141+
errors, abouts = model.collect_inventory(location)
151142

152143
write_errors = model.write_output(abouts, output, format)
153144
for err in write_errors:
@@ -209,7 +200,7 @@ def gen(location, output, mapping, license_notice_text_location, fetch_license,
209200

210201
click.echo('Generating .ABOUT files...')
211202

212-
errors, abouts = attributecode.gen.generate(
203+
errors, abouts = gen_generate(
213204
location=location, base_dir=output, use_mapping=mapping,
214205
license_notice_text_location=license_notice_text_location,
215206
fetch_license=fetch_license)
@@ -274,7 +265,7 @@ def attrib(location, output, template, mapping, inventory, quiet):
274265
location = extract_zip(location)
275266

276267
inv_errors, abouts = model.collect_inventory(location)
277-
no_match_errors = attributecode.attrib.generate_and_save(
268+
no_match_errors = attrib_generate_and_save(
278269
abouts=abouts, output_location=output,
279270
use_mapping=mapping, template_loc=template,
280271
inventory_location=inventory)
@@ -316,7 +307,7 @@ def check(location, show_all):
316307
click.echo('Running aboutcode-toolkit version ' + __version__)
317308
click.echo('Checking ABOUT files...')
318309

319-
errors, abouts = attributecode.model.collect_inventory(location)
310+
errors, abouts = model.collect_inventory(location)
320311

321312
msg_format = '%(sever)s: %(message)s'
322313
print_errors = []

0 commit comments

Comments
 (0)