From 4e5241484596a94a8ace37f7f276480aa0d47ecb Mon Sep 17 00:00:00 2001 From: iou1name Date: Wed, 2 Oct 2019 18:44:06 -0400 Subject: [PATCH] second commit --- saddle.py | 58 ++++++++++++++++++++++++++++++++++++++++++- templates/index.html | 6 +++++ templates/result.html | 23 +++++++++++++++++ 3 files changed, 86 insertions(+), 1 deletion(-) create mode 100644 templates/result.html diff --git a/saddle.py b/saddle.py index 516c56c..d418d42 100644 --- a/saddle.py +++ b/saddle.py @@ -2,6 +2,10 @@ """ A file hosting service similar to Pomf and Uguu but without the public nature. """ +import os +import string +import random + from aiohttp import web import jinja2 import aiohttp_jinja2 @@ -17,9 +21,61 @@ routes = web.RouteTableDef() @routes.get('/', name='index') +@routes.post('/', name='index') async def index(request): """The index page.""" - return render_template("index.html", request, locals()) + if request.method == 'GET': + return render_template("index.html", request, locals()) + data = await request.post() + files = [] + for filefield in data.getall('files'): + files.append(handle_filefield(filefield)) + + files_insert = [] + for file in files: + t = (request.cookies.get('userid'), file[0], file[1], 'DEFAUlT') + async with request.app['pool'] as conn: + await conn.executemany( + "INSERT INTO upload (user_id, id, filename, expiration_date) " + "VALUES ($1, $2, $3, $4)", + files_insert) + urls = [config.upload_url + f[1] for f in files] + return render_template("result.html", request, locals()) + + +def handle_filefield(filefield, rand_name=True): + """Handles a posted file.""" + filename = safe_filename(filefield.filename) + if not filename: + rand_name = True + prefix = get_rand_chars() + if rand_name: + filename = prefix + os.path.splitext(filename)[1] + else: + filename = prefix + '_' + filename + + with open(os.path.join(config.upload_dir, filename), 'wb') as file: + file.write(filefield.file.read()) + + t = (prefix, filename) + return t + + +def safe_filename(filename=''): + """Sanitizes the given filename.""" + safe_char = string.ascii_letters + string.digits + '._ ' + filename = ''.join([c for c in filename if c in safe_char]) + filename = filename.strip('._ ') + return filename + + +def get_rand_chars(n=8): + """Returns `n` number of random ASCII characters.""" + chars = [] + for _ in range(n): + char = random.choice(string.ascii_letters + string.digits) + chars.append(char) + return "".join(chars) async def init_app(): diff --git a/templates/index.html b/templates/index.html index 2b2c58c..90f75e0 100644 --- a/templates/index.html +++ b/templates/index.html @@ -11,6 +11,12 @@

Saddle

+
+
+ + +
+
diff --git a/templates/result.html b/templates/result.html new file mode 100644 index 0000000..79caf17 --- /dev/null +++ b/templates/result.html @@ -0,0 +1,23 @@ + + + + Saddle - Results + + + + + +
+

Saddle

+
+
+
+
    + {% for url in urls %} +
  • {{ url }}
  • + {% endfor %} +
+
+
+ +