Skip to content

Commit

Permalink
Merge branch 'master' into feature/raise-only-own-exceptions
Browse files Browse the repository at this point in the history
  • Loading branch information
blikenoother committed Feb 1, 2018
2 parents 7b44e3a + 80c0432 commit d7a2a48
Show file tree
Hide file tree
Showing 5 changed files with 37 additions and 14 deletions.
16 changes: 13 additions & 3 deletions aiourlshortener/shorteners/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ def __init__(self, engine, **kwargs):
self._class = _shorten_class[self.engine]
else:
raise UnknownAioUrlShortenerError('Please enter a valid shortener. {} class does not exist'.
format(self.engine))
format(engine))

for key, item in list(kwargs.items()):
setattr(self, key, item)
Expand All @@ -70,7 +70,12 @@ def short(self, url: str) -> str:
if not self.kwargs.get('timeout'):
self.kwargs['timeout'] = 10

self.shorten = yield from self._class(**self.kwargs).short(url)
instance = self._class(**self.kwargs)
try:
self.shorten = yield from instance.short(url)
finally:
yield from instance.close()

return self.shorten

@coroutine
Expand All @@ -90,5 +95,10 @@ def expand(self, url: str) -> str:
if not self.kwargs.get('timeout'):
self.kwargs['timeout'] = 10

self.expanded = yield from self._class(**self.kwargs).expand(url)
instance = self._class(**self.kwargs)
try:
self.expanded = yield from instance.expand(url)
finally:
yield from instance.close()

return self.expanded
9 changes: 6 additions & 3 deletions aiourlshortener/shorteners/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ class BaseShortener(object):
Base class for all Shorteners
"""
api_url = None
_session = None

def __init__(self, **kwargs):
self._session = aiohttp.ClientSession(connector=aiohttp.TCPConnector(use_dns_cache=True))
Expand Down Expand Up @@ -47,10 +48,12 @@ def expand(self, url: str) -> str:

@coroutine
def close(self):
try:
if self._session is not None:
yield from self._session.close()
except TypeError:
pass

def __del__(self):
if self._session is not None and not self._session.closed:
self._session.close()

@classmethod
def __subclasshook__(cls, c):
Expand Down
4 changes: 2 additions & 2 deletions aiourlshortener/shorteners/bitly.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,13 +25,13 @@ def __init__(self, **kwargs):
@coroutine
def short(self, url: str) -> str:
params = {'access_token': self.access_token, 'longUrl': url, 'format': 'json'}
response = {}
try:
response = yield from self._get(self._short_url, params=params)
response = yield from response.json()
except (aiohttp.ClientError, FetchError) as err:
raise ShorteningError('There was an error shortening the url "{}": {}'.format(url, repr(err)))

yield from self.close()
if 'data' in response and isinstance(response['data'], dict) and 'url' in response['data']:
return response['data']['url']

Expand All @@ -40,13 +40,13 @@ def short(self, url: str) -> str:
@coroutine
def expand(self, url: str) -> str:
params = {'access_token': self.access_token, 'link': url, 'format': 'json'}
response = {}
try:
response = yield from self._get(self._expand_url, params=params)
response = yield from response.json()
except (aiohttp.ClientError, FetchError) as err:
raise ExpandingError('There was an error expanding the url "{}": {}'.format(url, repr(err)))

yield from self.close()
if 'data' in response and isinstance(response['data'], dict) and 'original_url' in response['data']:
return response['data']['original_url']

Expand Down
4 changes: 2 additions & 2 deletions aiourlshortener/shorteners/google.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,13 +26,13 @@ def __init__(self, **kwargs):
def short(self, url: str) -> str:
data = {'longUrl': url}
params = {'key': self.api_key}
response = {}
try:
response = yield from self._post(self.api_url, data=json.dumps(data), params=params, headers=self._headers)
response = yield from response.json()
except (aiohttp.ClientError, FetchError) as err:
raise ShorteningError('There was an error shortening the url "{}": {}'.format(url,repr(err)))

yield from self.close()
if 'id' in response:
return response['id']

Expand All @@ -41,13 +41,13 @@ def short(self, url: str) -> str:
@coroutine
def expand(self, url: str) -> str:
params = {'key': self.api_key, 'shortUrl': url}
response = {}
try:
response = yield from self._get(self.api_url, params=params, headers=self._headers)
response = yield from response.json()
except (aiohttp.ClientError, FetchError) as err:
raise ExpandingError('There was an error expanding the url "{}": {}'.format(url, repr(err)))

yield from self.close()
if 'longUrl' in response:
return response['longUrl']

Expand Down
18 changes: 14 additions & 4 deletions setup.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,21 @@
import codecs
import os
import re
from setuptools import setup, find_packages
import aiourlshortener

_PACKAGE_FILE = os.path.join(os.path.dirname(__file__),
'aiourlshortener',
'__init__.py')
with codecs.open(_PACKAGE_FILE, 'r', 'utf-8') as package_reader:
_RAW_PACKAGE_METADATA = package_reader.read()

PACKAGE_METADATA = dict(re.findall("(__[a-z]+__) = '([^']+)'",
_RAW_PACKAGE_METADATA))
setup(
name='aiourlshortener',
version=aiourlshortener.__version__,
license=aiourlshortener.__license__,
author=aiourlshortener.__author__,
version=PACKAGE_METADATA['__version__'],
license=PACKAGE_METADATA['__license__'],
author=PACKAGE_METADATA['__author__'],
author_email='[email protected]',
url='https://github.com/blikenoother/aiourlshortener',
description='asynchronous python3 lib to short long url',
Expand Down

0 comments on commit d7a2a48

Please sign in to comment.