Merge pull request #72 from stijndcl/flask-backend

Create basics for backend server, + small fixes
This commit is contained in:
Stijn De Clercq 2021-06-19 22:29:32 +02:00 committed by GitHub
commit a310d1696c
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
23 changed files with 357 additions and 97 deletions

View file

@ -127,3 +127,55 @@ def add_alias(command: str, alias: str):
cursor.execute("INSERT INTO custom_command_aliases(command, alias) VALUES(%s, %s)", (command_id, alias,))
connection.commit()
def get_all():
"""
Return a list of all registered custom commands
"""
connection = utils.connect()
cursor = connection.cursor()
cursor.execute("SELECT * FROM custom_commands")
commands = cursor.fetchall()
ret = []
# Create a list of all entries
for command in commands:
dic = {"id": command[0], "name": command[1], "response": command[2]}
# Find and add aliases
cursor.execute("SELECT id, alias FROM custom_command_aliases WHERE command = %s", (command[0],))
aliases = cursor.fetchall()
if aliases:
dic["aliases"] = list(map(lambda x: {"id": x[0], "alias": x[1]}, aliases))
ret.append(dic)
return ret
def get_by_id(command_id: int):
"""
Return a command that matches a given id
"""
connection = utils.connect()
cursor = connection.cursor()
cursor.execute("SELECT * FROM custom_commands WHERE id = %s", (command_id,))
command = cursor.fetchone()
# Nothing found
if not command:
return None
dic = {"id": command[0], "name": command[1], "response": command[2]}
cursor.execute("SELECT id, alias FROM custom_command_aliases WHERE command = %s", (command_id,))
aliases = cursor.fetchall()
if aliases:
dic["aliases"] = list(map(lambda x: {"id": x[0], "alias": x[1]}, aliases))
return dic

View file

@ -1,6 +1,5 @@
import psycopg2
import json
import os
from settings import DB_HOST, DB_NAME, DB_USERNAME, DB_PASSWORD
connection = None
@ -17,15 +16,11 @@ def connect():
def create_connection():
global connection
dir_path = os.path.dirname(os.path.realpath(__file__))
with open(os.path.join(dir_path, "../../files/database.json"), "r") as fp:
db = json.load(fp)
connection = psycopg2.connect(
host=db["host"],
database=db["database"],
user=db["username"],
password=db["password"]
host=DB_HOST,
database=DB_NAME,
user=DB_USERNAME,
password=DB_PASSWORD
)