From d9d763a1d1d38489ceb010a31fa7aab332936200 Mon Sep 17 00:00:00 2001 From: Elia El Lazkani Date: Sat, 5 Oct 2019 21:31:38 +0200 Subject: [PATCH] Migrating from aiohttp to flask due --- requirements/requirements.txt | 3 +- shortenit/main.py | 4 +- {templates => shortenit/templates}/index.html | 9 ++- shortenit/web.py | 77 ++++++++----------- 4 files changed, 43 insertions(+), 50 deletions(-) rename {templates => shortenit/templates}/index.html (91%) diff --git a/requirements/requirements.txt b/requirements/requirements.txt index f482b91..ffb4e9b 100644 --- a/requirements/requirements.txt +++ b/requirements/requirements.txt @@ -1,5 +1,4 @@ pyyaml cloudant -aiohttp -aiohttp-jinja2 +flask trafaret diff --git a/shortenit/main.py b/shortenit/main.py index 2a2bc2a..00ed060 100644 --- a/shortenit/main.py +++ b/shortenit/main.py @@ -27,6 +27,7 @@ def main() -> None: """ parser = argument_parse() args = parser.parse_args() + debug = True if args.verbose > 0 else False verbosity_level = verbosity(args.verbose) setup_logging(args.logger, verbosity_level) config = Config(CONFIGURATION).get_config() @@ -36,9 +37,8 @@ def main() -> None: with DB(db_config) as db: db.initialize_shortenit() - loop = asyncio.get_event_loop() handler = SiteHandler(db, shorten_url, lenghten_url) - web = Web(loop, handler) + web = Web(handler, debug=debug) web.host = server_config.get('host', None) web.port = server_config.get('port', None) web.start_up() diff --git a/templates/index.html b/shortenit/templates/index.html similarity index 91% rename from templates/index.html rename to shortenit/templates/index.html index 5519a67..5e9bb8f 100644 --- a/templates/index.html +++ b/shortenit/templates/index.html @@ -33,6 +33,7 @@ data: JSON.stringify({'url' : $('#url-input').val(), 'timestamp': Date.now()}), success: returnSuccess, + error: returnFailure, dataType: 'json', contentType: "application/json", }); @@ -41,14 +42,18 @@ function returnSuccess(data, textStatus, jqXHR) { var url = href.concat(data.url); - console.log(window.location.href) + console.log(href) if(data.url) { document.getElementById("url-result").value = url; } else { - document.getElementById("url-result").value = "Please enter a valid URL!"; + document.getElementById("url-result").value = "The URL was too short and somehow got lost on the way, please try generating a new one."; } } + function returnFailure(data, textStatus, jqXHR) { + document.getElementById("url-result").value = "Please enter a valid URL!"; + } + function copyToClipboard() { /* Get the text field */ var copyText = document.querySelector("#url-result"); diff --git a/shortenit/web.py b/shortenit/web.py index 6b62bee..2b8c226 100644 --- a/shortenit/web.py +++ b/shortenit/web.py @@ -1,49 +1,40 @@ import os import logging -import aiohttp_jinja2 -import jinja2 import trafaret -from aiohttp import web 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, loop, handler): + def __init__(self, handler, debug=False): self.logger = logging.getLogger(self.__class__.__name__) - self.loop = loop self.app = None self.host = None self.port = None self.handler = handler - self.router = None - self.loader = None + self.debug = debug def start_up(self): - self.loop.run_until_complete(self.init()) - web.run_app(self.app, host=self.host, port=self.port) + self.init() + self.app.run(host=self.host, port=self.port, debug=self.debug) - async def init(self): - self.app = web.Application(loop=self.loop) - templates = Path(__file__).absolute().parent.parent.joinpath('templates') - - self.loader = jinja2.FileSystemLoader(str(templates)) - self.logger.debug(str(templates)) - aiohttp_jinja2.setup(self.app, - loader=self.loader) + def init(self): + self.app = Flask(__name__) self.setup_routes() def setup_routes(self): - self.router = self.app.router - self.router.add_get('/', self.handler.index, - name='index') - self.router.add_post('/shortenit', self.handler.shortenit, - name='shortenit') - self.router.add_put('/pointers/favicon.ico', self.handler.favicon, - name='favicon') - self.router.add_get('/{identifier}', self.handler.redirect, - name='redirect') + 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', self.handler.short_redirect, + methods=['GET']) class SiteHandler: @@ -57,33 +48,31 @@ class SiteHandler: trafaret.Key('timestamp'): trafaret.Int }) - async def shortenit(self, request): - data = await request.json() - self.logger.debug(data) + def shortenit(self): + data = request.get_json() try: data = self.shortenit_load_format(data) except Exception as e: - self.logger.debug(e) - raise web.HTTPBadRequest() + self.logger.error(e) + return {}, 400 + self.logger.error(e) + abort(400) try: short_url = self.shorten_url( self.database, data['url'], data['timestamp']) except KeyError as e: - self.logger.debug(e) - raise web.HTTPBadRequest() + self.logger.error(e) + abort(400) self.logger.debug(short_url) - return web.json_response({"url": short_url}) + return {"url": short_url} - async def redirect(self, request): - identifier = request.match_info['identifier'] + 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: - raise web.HTTPNotFound() - raise web.HTTPFound(location=url) + abort(404) + return redirect(url) - async def favicon(self, request): - raise web.Response(text={}) - - @aiohttp_jinja2.template('index.html') - async def index(self, request): - return {} + def index(self): + return render_template('index.html')