Skip to content
Snippets Groups Projects
Commit 2f30dbde authored by fcrisafulli-dev's avatar fcrisafulli-dev
Browse files

backend post implementation

parent 804c5167
No related branches found
No related tags found
No related merge requests found
No preview for this file type
File added
No preview for this file type
{"Users": 5, "Collections": 1}
\ No newline at end of file
{"Users": 0, "Collections": 4}
\ No newline at end of file
......@@ -9,7 +9,7 @@ class CrisisEventsDatabase:
def get_next_collection_id() -> int:
raise "Not Implemented"
def create_collection(collection_id: int, user_id: int):
def create_collection(self,user_id: int, collection_name:str):
"""
Returns the collection data if the `user_id` matches in the corresponding `collection_id` entry.
......@@ -40,4 +40,11 @@ class CrisisEventsDatabase:
The list returned is in the format:
"""
raise "Not Implemented"
def get_sample_of_collections(self):
raise "Not Implemented"
def get_info(self) -> str:
"Returns data about this database"
raise "Not Implemented"
\ No newline at end of file
File added
......@@ -48,7 +48,7 @@ class SqliteDatabaseAPI(database_api.CrisisEventsDatabase):
return next
def create_new_collection(self,user_id: int, collection_name:str):
def create_collection(self,user_id: int, collection_name:str):
connection, cur = self._connect()
collection_id = self.get_next_collection_id()
cur.execute("INSERT INTO event_collections VALUES (?, ?, ?, ?, ?)", (collection_id,user_id,"{}","summary",collection_name,))
......@@ -70,7 +70,14 @@ class SqliteDatabaseAPI(database_api.CrisisEventsDatabase):
self._disconnect(connection, cur)
# return result
def init_database(self, reset = False):
def get_sample_of_collections(self):
connection, cur = self._connect()
cur.execute("SELECT * FROM event_collections LIMIT 10;")
result = cur.fetchall()
self._disconnect(connection, cur)
return result
def initialize(self, reset = False):
#try to delete the databse and all relevant data
# try:
......@@ -93,18 +100,21 @@ class SqliteDatabaseAPI(database_api.CrisisEventsDatabase):
json.dump(metadata,f)
self._disconnect(connection, cur)
def get_info(self) -> str:
return "SQLITE Backend"
IMPLEMENTATION = SqliteDatabaseAPI
if __name__ == "__main__":
crisis_db = SqliteDatabaseAPI()
crisis_db.init_database()
crisis_db.initialize()
print(crisis_db.get_next_user_id())
print(crisis_db.get_next_user_id())
print(crisis_db.get_next_user_id())
print(crisis_db.get_next_user_id())
user_id = crisis_db.get_next_user_id()
collection_id = crisis_db.create_new_collection(user_id,"My collection")
collection_id = crisis_db.create_collection(user_id,"My collection")
print(crisis_db.get_collection(0,4))
......
from flask import Flask, request, abort
from database_api import CrisisEventsDatabase
from runtime_import import runtime_import
app = Flask(__name__)
database:CrisisEventsDatabase = None
@app.route('/webhook', methods=['POST'])
def webhook():
#this function is terrible, oh well!
def database_debug_view():
db_html = ""
for collection in database.get_sample_of_collections():
db_html += f"<br/><code>{collection}<code/>"
return f"""
<html>
<head></head>
<body>
<p>This service uses {database.get_info()} as its database</p>
<p>Warning: if there are any '<' or '>' or '/' or '\\' in the database: this will break! </p>
<br/>
{db_html}
</body>
</html>
"""
@app.route('/database_service', methods=['POST','GET'])
def database_service():
if request.method == 'POST':
print(request.json)
try:
if request.json["command"] == "create_collection":
print("Creating collection")
database.create_collection(0,request.json["data"]["collection_name"])
else:
print("Invalid command")
abort(400)
except KeyError:
print("Got poorly formatted request")
abort(400)
return '', 200
elif request.method == 'GET':
return database_debug_view(), 200
else:
abort(400)
if __name__ == '__main__':
database = runtime_import("database_implementation/")[0].IMPLEMENTATION()
database.initialize()
database.create_collection(0,"First Collection")
database.create_collection(0,"Second Collection")
database.create_collection(0,"Third Collection")
app.run()
\ No newline at end of file
import requests
# Specify the API URL we want to send our JSON to
url = 'http://127.0.0.1:5000/webhook'
url = 'http://127.0.0.1:5000/database_service'
# Specify the appropriate header for the POST request
headers = {'Content-type': 'application/json'}
# Specify the JSON data we want to send
data = '{"title": "foo", "body": "bar", "userId": 1}'
data = '{"command": "create_collection", "data": {"collection_name":"SENT FROM POST title"}}'
response = requests.post(url, headers=headers, data=data)
\ No newline at end of file
response = requests.post(url, headers=headers, data=data)
print(response.text,response.status_code)
\ No newline at end of file
import os
import sys
import importlib
from types import ModuleType
def runtime_import(path: str) -> "list[ModuleType]":
files = os.listdir(path)
py_files = [f for f in files if f.endswith(".py")]
print(f"Importing modules from: {path} {py_files}")
py_files.sort()
sys.path.append(path)
modules_found = []
for py_file in py_files:
modules_found.append(importlib.import_module(py_file[:-3]))
return modules_found
if __name__ == "__main__":
db_implementations = runtime_import("database_implementation/")
implementation_class = db_implementations[0].IMPLEMENTATION
db = implementation_class()
print(type(db))
\ No newline at end of file
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment