Created
March 11, 2011 16:07
-
-
Save fabiocerqueira/866090 to your computer and use it in GitHub Desktop.
migre.me api client for python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#-*- coding: utf-8 -*- | |
import urllib | |
from xml.etree import ElementTree | |
class MigreMe(object): | |
URL_BASE = 'http://migre.me/' | |
URN_SHORT = 'api.txt?url=%s' | |
URN_INFO = 'api_redirect2.xml?url=%s' | |
def __init__(self, url=''): | |
""" Cria um objeto MigreMe a partir de um url não encurtada. | |
parms: | |
url - url que será encurtada | |
""" | |
self.url = url | |
self.short_url = '' | |
self.shorten() | |
def shorten(self): | |
if not self.short_url: | |
self.short_url = urllib.urlopen(MigreMe.URL_BASE + MigreMe.URN_SHORT % self.url).read() | |
return self.short_url | |
@classmethod | |
def short(cls, short_url): | |
""" Cria um objeto MigreMe a partir de uma url já encurtada | |
Parms: | |
short_url - url encurtada | |
Return: | |
Objeto MigreMe com url e short_url atribuidos. | |
""" | |
xml = urllib.urlopen(MigreMe.URL_BASE + MigreMe.URN_INFO % short_url).read() | |
xmlp = ElementTree.fromstring(xml) | |
xmlp = dict((c.tag,c.text) for c in xmlp.getchildren()) | |
m = cls() | |
m.short_url = short_url | |
m.url = xmlp['url'] | |
return m | |
if __name__ == '__main__': | |
m = MigreMe('http://www.acens.com.br') | |
print m.short_url | |
print m.url | |
m2 = MigreMe.short(m.short_url) | |
print m2.short_url | |
print m2.url |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment