A Python library for generating short URLs.
Project description
A Python library for generating short URLs.
It’s gevent-safe, so you can use it with Gunicorn (and consequently Flask, Django and Pyramid).
Installation
Install with pip: pip install shorten
If you want to run the tests, ensure nose is installed with pip install nose.
The basics
Make a shortener:
import shorten import redis shortener = shorten.shortener('redis', redis=redis.Redis())
Map a short key to a long value:
# '2111' key = shortener.insert('http://mitpress.mit.edu/sicp/full-text/book/book.html')
Map multiple keys and values from greenlets:
import gevent values = [ 'aardvark', 'bonobo', 'caiman', 'degu', 'elk', ] jobs = [gevent.spawn(shortener.insert, v) for v in values] keys = map(lambda j: j.value, gevent.joinall(jobs, timeout=2)) # ['2111', '2112', '2114', '2113', '2115'] print(keys)
If you wish to store the keys with some sort of prefix, pass in a formatter function when a KeyStore is created:
import shorten import redis def to_key_format(token): return 'my:namespace:key:{0}'.format(token) shortener = shorten.shortener('redis', redis=redis.Redis(), formatter=to_key_format) # 'my:namespace:key:2111' key = shortener.insert('http://mitpress.mit.edu/sicp/full-text/book/book.html')
Custom alphabets of symbols (any 0-index based iterable) can be passed to the shortener function too:
import shorten # Use an alternative alphabet with faces alphabet = [ ':)', ':(', ';)', ';(', '>:)', ':D', ':x', ':X', ':|', ':O', '><', '<<', '>>', '^^', 'O_o', u'?_?', ] shortener = shorten.shortener('memory', alphabet=alphabet) values = [ 'aardvark', 'bonobo', 'caiman', 'degu', 'elk', ] keys = map(shortener.insert, values) # [':(:):):)', ':(:):):(', ':(:):);)', ':(:):);(', ':(:):)>:)'] print(keys)
Example
For a more real-world example, here’s a URL-shortening website that accepts URLs and returns the shortened key via JSON.
# For example, run as: # gunicorn -w 4 example:app import re from redis import Redis from flask import Flask, request, redirect, url_for, jsonify from werkzeug import iri_to_uri from shorten import shortener app = Flask(__name__) app_name = 'short.ur' redis = Redis() def is_url(string): return re.match('http(s){0,1}://.+\..+', string, re.I) is not None def to_short_token(key): return key.split(to_short_key(''), 1)[1] def to_short_key(token): return '{0}:key:{1}'.format(app_name, token) counter_key = '{0}:counter'.format(app_name) shortener = shortener('redis', redis=redis, counter_key=counter_key, formatter=to_short_key) @app.route('/') def shorten(): try: url = request.args['u'].strip() if not is_url(url): return jsonify({'error' : 'not a valid url'}) else: token = to_short_token(shortener.insert(url)) return jsonify({'short' : url_for('bounce', token=token)}) except KeyError, e: return jsonify({'error' : 'no url to shorten'}) @app.route('/<token>') def bounce(token): try: token = to_short_key(token) return redirect(iri_to_uri(shortener[token])) except KeyError: return jsonify({'error' : 'no short url found'}) if __name__ == '__main__': app.run('0.0.0.0')
Project details
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.