Skip to content

Commit 07cced4

Browse files
committed
Added get_redirect() method to fetch expand url when api does not provide endpoint.
1 parent 2cc5198 commit 07cced4

File tree

1 file changed

+18
-1
lines changed

1 file changed

+18
-1
lines changed

shorty.py

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@
3636
THE SOFTWARE.
3737
"""
3838

39-
from urllib2 import urlopen, Request, URLError, HTTPError
39+
from urllib2 import urlopen, Request, URLError, HTTPError, HTTPRedirectHandler, build_opener
4040
from urllib import urlencode, quote
4141
from urlparse import urlparse
4242
from random import randint
@@ -76,6 +76,23 @@ def request(url, parameters=None, username_pass=None):
7676
except URLError, e:
7777
raise ShortyError(e)
7878

79+
def get_redirect(url):
80+
81+
class StopRedirectHandler(HTTPRedirectHandler):
82+
def http_error_301(self, req, fp, code, smg, headers):
83+
return None
84+
o = build_opener(StopRedirectHandler())
85+
try:
86+
o.open(url)
87+
except HTTPError, e:
88+
if e.code == 301:
89+
return e.headers['Location']
90+
else:
91+
raise ShortyError(e)
92+
except URLError, e:
93+
raise ShortyError(e)
94+
return None
95+
7996
"""Base interface that all services implement."""
8097
class Service(object):
8198

0 commit comments

Comments
 (0)