From 0561deb1b4bdbf905ae56650e541a73965d439ed Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?S=C3=A9bastien=20Thuret?= Date: Sat, 9 Oct 2021 11:44:00 +0200 Subject: [PATCH] Save suggestions in a database --- .gitignore | 1 + app/app.py | 8 +++++++- app/suggestions.py | 31 +++++++++++++++++++++++++++++++ 3 files changed, 39 insertions(+), 1 deletion(-) create mode 100644 app/suggestions.py diff --git a/.gitignore b/.gitignore index 256d239..4c46265 100644 --- a/.gitignore +++ b/.gitignore @@ -131,3 +131,4 @@ installed_models/ # Misc api_keys.db +suggestions.db \ No newline at end of file diff --git a/app/app.py b/app/app.py index ea69d43..f63348a 100644 --- a/app/app.py +++ b/app/app.py @@ -9,6 +9,7 @@ from app import flood from app.language import detect_languages, transliterate from .api_keys import Database +from .suggestions import Database as SuggestionsDatabase from translatehtml import translate_html @@ -617,7 +618,12 @@ def create_app(args): @app.route("/suggest", methods=["POST"]) @limiter.exempt def suggest(): - # TODO: + q = request.values.get("q") + s = request.values.get("s") + source_lang = request.values.get("source") + target_lang = request.values.get("target") + + SuggestionsDatabase().add(q, s, source_lang, target_lang) return jsonify({"success": True}) SWAGGER_URL = "/docs" # URL for exposing Swagger UI (without trailing '/') diff --git a/app/suggestions.py b/app/suggestions.py new file mode 100644 index 0000000..28b943a --- /dev/null +++ b/app/suggestions.py @@ -0,0 +1,31 @@ +import sqlite3 +import uuid + +from expiringdict import ExpiringDict + +DEFAULT_DB_PATH = "suggestions.db" + + +class Database: + def __init__(self, db_path=DEFAULT_DB_PATH, max_cache_len=1000, max_cache_age=30): + self.db_path = db_path + self.cache = ExpiringDict(max_len=max_cache_len, max_age_seconds=max_cache_age) + + # Make sure to do data synchronization on writes! + self.c = sqlite3.connect(db_path, check_same_thread=False) + self.c.execute( + """CREATE TABLE IF NOT EXISTS suggestions ( + "q" TEXT NOT NULL, + "s" TEXT NOT NULL, + "source" TEXT NOT NULL, + "target" TEXT NOT NULL + );""" + ) + + def add(self, q, s, source, target): + self.c.execute( + "INSERT INTO suggestions (q, s, source, target) VALUES (?, ?, ?, ?)", + (q, s, source, target), + ) + self.c.commit() + return True