Code: Alles auswählen
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import with_statement
import sys
if sys.version_info[0] < 3:
from urllib2 import urlopen, Request
from urllib import urlencode
else:
from urllib.request import urlopen, Request
from urllib.parse import urlencode
try:
import json
except ImportError:
import simplejson as json
from contextlib import closing
API_URL = 'http://api.bit.ly/v3/shorten'
class ShortError(Exception):
def __init__(self, val):
self.val = val
def __str__(self):
return repr(self.val)
def get_short_url(login, api_key, long_url):
data = urlencode({'login': login, 'apiKey' : api_key,
'longUrl' : long_url, 'format' : 'json'})
with closing(urlopen(Request(API_URL, data, {'User-agent' : 'Python-bitly/2.6'}))) as stream:
parsed_response = json.load(stream)
if not parsed_response['status_code'] == 200:
raise ShortError(parsed_response['status_txt'])
return parsed_response['data']['url']
if __name__ == '__main__':
login = raw_input('Login?: ')
api_key = raw_input('Api_key?: ')
long_url = raw_input('Long url?: ')
print get_short_url(login, api_key, long_url)