The personal URL shortener
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

80 lines
2.4 KiB

import os
import logging
import trafaret
from pathlib import Path
from flask import Flask
from flask import render_template
from flask import request
from flask import redirect
from flask import abort
class Web:
def __init__(self, handler, debug=False):
self.logger = logging.getLogger(self.__class__.__name__)
self.app = None
self.host = None
self.port = None
self.handler = handler
self.debug = debug
def start_up(self):
self.init()
self.app.run(host=self.host, port=self.port, debug=self.debug)
def init(self):
self.app = Flask(__name__)
self.setup_routes()
def setup_routes(self):
self.app.add_url_rule('/', '/', self.handler.index,
methods=['GET'])
self.app.add_url_rule('/shortenit', '/shortenit', self.handler.shortenit,
methods=['POST'])
self.app.add_url_rule('/<identifier>', '/identifier', self.handler.short_redirect,
methods=['GET'])
class SiteHandler:
def __init__(self, configuration, database, shorten_url, lenghten_url):
self.logger = logging.getLogger(self.__class__.__name__)
self.configuration = configuration
self.database = database
self.shorten_url = shorten_url
self.lenghten_url = lenghten_url
self.shortenit_load_format = trafaret.Dict({
trafaret.Key('url'): trafaret.URL,
trafaret.Key('timestamp'): trafaret.Int
})
def shortenit(self):
data = request.get_json()
try:
data = self.shortenit_load_format(data)
except Exception as e:
self.logger.error(e)
return {}, 400
self.logger.error(e)
abort(400)
try:
short_url = self.shorten_url(
self.configuration, self.database,
data['url'], data['timestamp'])
except KeyError as e:
self.logger.error(e)
abort(400)
self.logger.debug(short_url)
return {"url": short_url}
def short_redirect(self, identifier):
url = self.lenghten_url(self.database, identifier)
self.logger.debug("The URL is...")
self.logger.debug(url)
if not url:
abort(404)
return redirect(url)
def index(self):
return render_template('index.html')