-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathShortUrlGen.py
70 lines (68 loc) · 2.14 KB
/
ShortUrlGen.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# Short URL Generator
# Author : Kang-Min Wang ( Aminzai )
# Mail : lagunwang --AT-- Gmail.com
# Date : Mon Oct 5 21:54:27 CST 2009
import urllib
import urllib2
import urlparse
import httplib
import random
class ShortURL:
services = {
'api.tr.im': '/api/trim_simple?url=',
'tinyurl.com': '/api-create.php?url=',
'is.gd': '/api.php?longurl='
}
def TrIm_query( self , url ):
shortener = 'api.tr.im'
c = httplib.HTTPConnection(shortener)
c.request("GET", self.services[shortener] + urllib.quote(url))
r = c.getresponse()
shorturl = r.read().strip()
if ("Error" not in shorturl) and ("http://" + urlparse.urlparse(shortener)[1] in shorturl):
return shorturl
else:
raise IOError
def TinyUrl_query( self , url ):
shortener = 'tinyurl.com'
c = httplib.HTTPConnection(shortener)
c.request("GET", self.services[shortener] + urllib.quote(url))
r = c.getresponse()
shorturl = r.read().strip()
if ("Error" not in shorturl) and ("http://" + urlparse.urlparse(shortener)[1] in shorturl):
return shorturl
else:
raise IOError
def IsGd_query( self , url ):
shortener = 'is.gd'
c = httplib.HTTPConnection(shortener)
c.request("GET", self.services[shortener] + urllib.quote(url))
r = c.getresponse()
shorturl = r.read().strip()
if ("Error" not in shorturl) and ("http://" + urlparse.urlparse(shortener)[1] in shorturl):
return shorturl
else:
raise IOError
def Random_Short_Url_Gen( self , url ):
choice = [ 'TrIm' , 'TinyUrl' , 'IsGd' ]
rand = random.choice( choice )
try:
if rand == 'TrIm':
return self.TrIm_query( url )
elif rand == 'TinyUrl':
return self.TinyUrl_query( url )
elif rand == 'IsGd':
return self.IsGd_query( url )
else:
return url
except IOError:
return url
if __name__ == '__main__' :
print "Try to build short url & Random Choice"
obj = ShortURL()
while 1:
a = raw_input("Please input url:")
print obj.Random_Short_Url_Gen( a )
#print obj.TrIm_query(a)
#print obj.TinyUrl_query(a)
#print obj.IsGd_query(a)