Skip to content

Commit

Permalink
Refactor to improve exceptions handling
Browse files Browse the repository at this point in the history
  • Loading branch information
jrrodri committed Mar 11, 2019
1 parent 9025162 commit 80c2083
Show file tree
Hide file tree
Showing 5 changed files with 38 additions and 32 deletions.
4 changes: 2 additions & 2 deletions abraia/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ def upload_file(self, file, path, type=''):
data = file if isinstance(file, BytesIO) else open(file, 'rb')
resp = requests.put(url, data=data, headers={'Content-Type': type})
if resp.status_code != 200:
raise APIError('PUT {} {}'.format(url, resp), resp.status_code)
raise APIError(resp.text, resp.status_code)
return {'name': name, 'source': source}

def move_file(self, old_path, new_path):
Expand All @@ -74,7 +74,7 @@ def remove_file(self, path):
url = '{}/files/{}'.format(config.API_URL, path)
resp = requests.delete(url, auth=self.auth)
if resp.status_code != 200:
raise APIError('DELETE {} {}'.format(url, resp), resp.status_code)
raise APIError(resp.text, resp.status_code)
resp = resp.json()
return resp['file']

Expand Down
Empty file added images/fake.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
50 changes: 28 additions & 22 deletions scripts/abraia
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,13 @@ from datetime import datetime

from abraia import config
from abraia import Abraia
from abraia import APIError

abraia = Abraia(folder='batch/')


def process_info():
print('Abraia CLI v0.4.4')
print('Abraia CLI v0.4.5')
user = abraia.user()
print('Email:', user['email'])
print('Credits:', user['credits'])
Expand Down Expand Up @@ -66,32 +67,37 @@ def process_optimize(args):
fileout = dest
root, oext = os.path.splitext(fileout)
if ext.lower() in config.IMAGE_EXTS and oext.lower() in config.IMAGE_EXTS:
abraia.from_file(filename).resize(
width=args.get('width'),
height=args.get('height')).filter(args.get('filter')).to_file(fileout)
if ext == oext and os.path.getsize(fileout) > os.path.getsize(filename):
shutil.copy2(filename, fileout)
sizein = os.path.getsize(filename) / 1024
sizeout = os.path.getsize(fileout) / 1024
tqdm.write('[{3:04.1f}%] {1:6.1f}KB -> {2:6.1f}KB ({0})'.format(
os.path.split(fileout)[1], sizein, sizeout, 100 * (1 - sizeout / sizein)))
try:
source = abraia.from_file(filename)
source = source.resize(
width=args.get('width'), height=args.get('height'))
source = source.filter(args.get('filter'))
source.to_file(fileout)
if ext == oext and os.path.getsize(fileout) > os.path.getsize(filename):
shutil.copy2(filename, fileout)
sizein = os.path.getsize(filename) / 1024
sizeout = os.path.getsize(fileout) / 1024
tqdm.write('[{3:04.1f}%] {1:6.1f}KB -> {2:6.1f}KB ({0})'.format(
os.path.split(fileout)[1], sizein, sizeout, 100 * (1 - sizeout / sizein)))
except APIError as error:
print('Error', error.code, error.message)
else:
shutil.copy2(filename, fileout)
else:
process_url(args)
fileout = os.path.split(path) if dest is None else dest
process_url(path, fileout, args)


def process_url(args):
path = args['path']
dest = args.get('dest')
fileout = os.path.split(path) if dest is None else dest
def process_url(path, fileout, args):
try:
abraia.from_url(path).resize(
width=args.get('width'),
height=args.get('height')).to_file(fileout)
print('New image saved:', dest)
except:
print('Error to processing:', path)
source = abraia.from_url(path)
source = source.resize(
width=args.get('width'), height=args.get('height'))
source = source.filter(args.get('filter'))
source.to_file(fileout)
print('New image saved:', fileout)
except APIError as error:
print('Error', error.code, error.message)


def process_list(path):
Expand Down Expand Up @@ -136,7 +142,7 @@ def add_parser_store(subparser):

def parse_input():
parser = argparse.ArgumentParser(description='Abraia image optimization tool')
parser.add_argument('-V', '--version', action='version', version='0.4.4')
parser.add_argument('-V', '--version', action='version', version='0.4.5')
subparser = parser.add_subparsers(dest='command')
parser_info = add_parser_info(subparser)
parser_configure = add_parser_configure(subparser)
Expand Down
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

setup(
name='abraia',
version='0.4.4',
version='0.4.5',
description='Abraia Python SDK',
long_description=long_description,
long_description_content_type='text/markdown',
Expand Down
14 changes: 7 additions & 7 deletions tests/test_abraia.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import os
import pytest

from abraia import Client, Abraia
from abraia import Abraia, Client, APIError

abraia = Abraia()

Expand Down Expand Up @@ -55,9 +56,8 @@ def test_remove_stored_image():
assert resp['name'] == 'tiger.jpg'


# def test_exception():
# """Test an API exception to save no file"""
# source = abraia.from_url('https://abraia.me/images/tiger.jpg')
# with pytest.raises(client.APIError):
# source.to_file(os.path.join(
# os.path.dirname(__file__), '../images/error.jpg'))
def test_server_error():
with pytest.raises(APIError) as excinfo:
abraia.from_file('images/fake.jpg')
error = excinfo.value
assert error.code == 501

0 comments on commit 80c2083

Please sign in to comment.