aboutsummaryrefslogtreecommitdiff
path: root/src/controller.py
diff options
context:
space:
mode:
authorJoris2024-06-02 14:38:13 +0200
committerJoris2024-06-02 14:38:22 +0200
commit1019ea1ed341e3a7769c046aa0be5764789360b6 (patch)
tree1a0d8a4f00cff252d661c42fc23ed4c19795da6f /src/controller.py
parente8da9790dc6d55cd2e8883322cdf9a7bf5b4f5b7 (diff)
Migrate to Rust and Hyper
With sanic, downloading a file locally is around ten times slower than with Rust and hyper. Maybe `pypy` could have helped, but I didn’t succeed to set it up quickly with the dependencies.
Diffstat (limited to 'src/controller.py')
-rw-r--r--src/controller.py58
1 files changed, 0 insertions, 58 deletions
diff --git a/src/controller.py b/src/controller.py
deleted file mode 100644
index 351d0bc..0000000
--- a/src/controller.py
+++ /dev/null
@@ -1,58 +0,0 @@
-import io
-import logging
-import os
-import sanic
-import sqlite3
-import tempfile
-
-import db
-import templates
-import utils
-
-conn = sqlite3.connect('db.sqlite3')
-files_directory = 'files'
-authorized_key = os.environ['KEY']
-
-def index():
- return sanic.html(templates.index)
-
-async def upload(request):
- key = request.headers.get('X-Key')
- if not key == authorized_key:
- sanic.log.logging.info('Unauthorized to upload file: wrong key')
- return sanic.text('Unauthorized', status = 401)
- else:
- sanic.log.logging.info('Uploading file')
- content_length = int(request.headers.get('content-length'))
- filename = utils.sanitize_filename(request.headers.get('X-FileName'))
- expiration = request.headers.get('X-Expiration')
-
- with tempfile.NamedTemporaryFile(delete = False) as tmp:
- while data := await request.stream.read():
- tmp.write(data)
-
- sanic.log.logging.info('File uploaded')
- file_id = db.insert_file(conn, filename, expiration, content_length)
- os.makedirs(files_directory, exist_ok=True)
- os.rename(tmp.name, os.path.join(files_directory, file_id))
-
- return sanic.text(file_id)
-
-async def file(file_id: str, download: bool):
- res = db.get_file(conn, file_id)
- if res is None:
- self._serve_str(templates.not_found, 404, 'text/html')
- else:
- filename, expires, content_length = res
- disk_path = os.path.join(files_directory, file_id)
- if download:
- return await sanic.response.file_stream(
- disk_path,
- chunk_size = io.DEFAULT_BUFFER_SIZE,
- headers = {
- 'Content-Disposition': f'attachment; filename={filename}',
- 'Content-Length': content_length
- }
- )
- else:
- return sanic.html(templates.file_page(file_id, filename, expires))