From ec4a034581e6ec86eca60a27ae47c6c12a086b16 Mon Sep 17 00:00:00 2001 From: iou1name Date: Wed, 6 Nov 2019 13:09:07 -0500 Subject: [PATCH] expiration dates work --- saddle.py | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/saddle.py b/saddle.py index 0a1d915..48460bd 100644 --- a/saddle.py +++ b/saddle.py @@ -6,6 +6,7 @@ import os import time import string import random +import asyncio import datetime from aiohttp import web @@ -180,11 +181,46 @@ def download_file(url, timeout=10, max_file_size=config.client_max_size): return (fname, temp) +async def cleaner(app): + """Removes files marked for deletion.""" + async with app['pool'].acquire() as conn: + expired = await conn.fetch( + "SELECT * FROM upload WHERE expiration_date < NOW()") + if not expired: + return + for record in expired: + os.remove(os.path.join(config.upload_dir, record['filename'])) + await conn.executemany( + "DELETE FROM upload WHERE id = $1", + [(record['id'],) for record in expired]) + + +async def cleaner_loop(app): + """Loops cleaner() continuously until shutdown.""" + try: + while True: + await cleaner(app) + await asyncio.sleep(60) + except asyncio.CancelledError: + return + + +async def start_background_tasks(app): + app['cleaner'] = asyncio.create_task(cleaner_loop(app)) + + +async def cleanup_background_tasks(app): + app['cleaner'].cancel() + await app['cleaner'] + + async def init_app(): """Initializes the application.""" app = web.Application(middlewares=[buckler_aiohttp.buckler_session]) aiohttp_jinja2.setup(app, loader=jinja2.FileSystemLoader('templates')) app['pool'] = await asyncpg.create_pool(**config.db) + app.on_startup.append(start_background_tasks) + app.on_cleanup.append(cleanup_background_tasks) async with app['pool'].acquire() as conn: with open('saddle.sql', 'r') as file: