from aiohttp import web import aiosqlite import asyncio import random import sys PORT, DATABASE = sys.argv[1:] app = web.Application(client_max_size=32*1024**2) routes = web.RouteTableDef() async def get_pair(db): while True: csr = await db.execute("SELECT * FROM queue") row = await csr.fetchone() await csr.close() iteration = None if row: m1, m2, iteration = row else: filenames = [ x[0] for x in await db.execute_fetchall("SELECT filename FROM files", ()) ] m1, m2 = tuple(sorted(random.sample(filenames, 2))) csr = await db.execute("SELECT 1 FROM ratings WHERE meme1 = ? AND meme2 = ?", (m1, m2)) if not await csr.fetchone(): return m1, m2, iteration @routes.get("/") async def index(request): meme1, meme2, iteration = await get_pair(request.app["db"]) return web.Response(text=f"""

Meme Rating

""", content_type="text/html") @routes.post("/rate") async def rate(request): db = request.app["db"] post = await request.post() meme1 = post["meme1"] meme2 = post["meme2"] iteration = post["iteration"] rating = post["rating"] await db.execute("INSERT INTO ratings (meme1, meme2, rating, iteration) VALUES (?, ?, ?, ?)", (meme1, meme2, rating, iteration)) await db.execute("DELETE FROM queue WHERE meme1 = ? AND meme2 = ?", (meme1, meme2)) await db.commit() return web.HTTPFound("/") async def main(): app["db"] = await aiosqlite.connect(DATABASE) await app["db"].executescript(""" CREATE TABLE IF NOT EXISTS ratings ( meme1 TEXT NOT NULL, meme2 TEXT NOT NULL, rating TEXT NOT NULL, iteration TEXT, UNIQUE (meme1, meme2) ); CREATE TABLE IF NOT EXISTS queue ( meme1 TEXT NOT NULL, meme2 TEXT NOT NULL, iteration TEXT NOT NULL, UNIQUE (meme1, meme2, iteration) ); """) app.router.add_routes(routes) app.router.add_static("/memes/", "./images") print("Ready") runner = web.AppRunner(app) await runner.setup() site = web.TCPSite(runner, "", int(PORT)) await site.start() if __name__ == "__main__": loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) loop.run_until_complete(main()) loop.run_forever()