Instantly share code, notes, and snippets.

@jdp /crunch.py
Created Feb 17, 2016

Embed
What would you like to do?
Toy URL shortener with Flask, Redis, and BaseConverter
from baseconv import BaseConverter
from flask import Flask, abort, make_response, redirect, request, url_for
from flask.ext.redis import FlaskRedis
app = Flask(__name__)
store = FlaskRedis(app)
converter = BaseConverter('23456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz')
@app.route('/<shortcode>')
def resolve_url(shortcode):
url = store.get('crunch-url:{shortcode}'.format(shortcode=shortcode))
if url:
return redirect(url, 301)
abort(404)
@app.route('/', methods=['POST'])
def shorten_url():
url = request.form['url']
shortcode = converter.encode(store.incr('crunch-id'))
store.set('crunch-url:{shortcode}'.format(shortcode=shortcode), url)
return make_response(url_for('resolve_url', shortcode=shortcode), 201)
if __name__ == '__main__':
app.run()
Flask==0.10.1
Flask-Redis==0.1.0
itsdangerous==0.24
Jinja2==2.8
MarkupSafe==0.23
python-baseconv==1.1.3
redis==2.10.5
Werkzeug==0.11.4
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment