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.

79 lines
2.5 KiB

import os
import logging
import aiohttp_jinja2
import jinja2
import trafaret as t
from aiohttp import web
from pathlib import Path
class Web:
def __init__(self, loop, handler):
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
def start_up(self):
self.loop.run_until_complete(self.init())
web.run_app(self.app, host=self.host, port=self.port)
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)
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_get('/{identifier}', self.handler.redirect,
name='redirect')
class SiteHandler:
def __init__(self, database, shorten_url, lenghten_url):
self.logger = logging.getLogger(self.__class__.__name__)
self.database = database
self.shorten_url = shorten_url
self.lenghten_url = lenghten_url
self.shortenit_load_format = t.Dict({
t.Key('url'): t.URL,
t.Key('timestamp'): t.Int
})
async def shortenit(self, request):
data = await request.json()
self.logger.debug(data)
try:
data = self.shortenit_load_format(data)
except t.DataError:
raise web.HTTPBadRequest('URL is not valid')
short_url = self.shorten_url(self.database, data['url'], data['timestamp'])
self.logger.debug(short_url)
return web.json_response({"url": short_url})
async def redirect(self, request):
identifier = request.match_info['identifier']
url = self.lenghten_url(self.database, identifier)
if not url:
raise web.HTTPNotFound()
return web.HTTPFound(location=url)
@aiohttp_jinja2.template('index.html')
async def index(self, request):
return {}