Skip to content

Instantly share code, notes, and snippets.

@vilaca
Created Feb 6, 2020
Embed
What would you like to do?
from bidict import bidict
from django.core.exceptions import ValidationError
from django.core.validators import URLValidator
from flask import Flask, request, redirect
from flask_restful import Resource, Api
from random import randrange
class Redirects(Resource):
def get(self, short):
if not store.get(short, None):
return 'Not found.', 404
return redirect(store.get(short))
class Shorten(Resource):
def post(self):
url = request.form['v']
if not url.startswith('http://') and not url.startswith('https://'):
return {'status': 'NOK', 'message': 'Only available for http/https URLs.'}, 400
if len(url) < 10:
return {'status': 'NOK', 'message': 'URL too short.'}, 400
try:
validator(url)
except ValidationError as e:
return 'Invalid URL.', 400
if store.inverse.get(url, None):
return {'status': 'OK', 'short': store.inverse[url]}, 409
short = str()
while True:
for x in range(6):
short += base64[randrange(2 ** 6)]
if short not in store:
break
short = str()
store.put(short, url)
return {'status': 'OK', 'short': short}, 201
base64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+_'
app = Flask(__name__)
api = Api(app)
store = bidict()
validator = URLValidator()
api.add_resource(Shorten, '/')
api.add_resource(Redirects, '/<short>')
if __name__ == '__main__':
app.run(debug=True)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment