tinyurl/tinyurl.py

48 lines
1.0 KiB
Python

from flask import Flask, json, redirect, request, render_template, jsonify
import short_url
app = Flask(__name__)
found = {}
database = {}
@app.route('/', methods=['POST'])
def post_tinyurl():
body = request.get_json(silent=True, force=True)
if body is None or 'url' not in body:
return (render_template("error.html", code=400), 400)
url = body['url']
if url in found:
return jsonify({
'url': url,
'short_url_code': '/' + found[url]
})
counter = len(database) + 1
newurl = short_url.encode_url(counter)
database[newurl] = url
found[url] = newurl
return jsonify({
'url': url,
'short_url_code': '/' + newurl
})
@app.route('/<url>', methods=["GET"])
def get_tinyurl(url):
if url not in database:
return render_template('error.html', code=404), 404
return redirect(database[url], 301)
@ app.errorhandler(404)
def not_found(error):
return render_template('error.html', code=404), 404
if __name__ == '__main__':
app.run(debug=True)