]> prime8.dev >> repos - csc.git/commitdiff
Add sqlite database
authorDamian Myrda <monkey.damianek@gmail.com>
Tue, 30 Apr 2024 02:19:53 +0000 (21:19 -0500)
committerDamian Myrda <monkey.damianek@gmail.com>
Tue, 30 Apr 2024 02:19:53 +0000 (21:19 -0500)
README.md
database.db [new file with mode: 0644]
database.json
database.py
main.py
models/project.py
projects.py [deleted file]
schoology.py
templates/elements/projects.html

index d3570ef80f75fa7b5006307c8c3753df80f54ac9..59b38d8301ab14d108446247507b4be05fd2dd7c 100644 (file)
--- a/README.md
+++ b/README.md
@@ -1,18 +1,23 @@
 # Computer Science Club Website
+
 A website for Computer Science Club made during a mini-hackathon.
 
 ![home page](./assets/home.png)
 
 ## setup
+
 ### environment
+
 To setup the server environment, run `python -m venv .` in the root of the project. Then, execute `. ./bin/activate` and you should be in the virtual environment. Next, run `pip install flask schoolopy jsonpickle cachecontrol google-auth google_auth_oauthlib` to install all the dependencies. Now, `exit`.
 
 ### schoology
-In ```config.py```, change ```DOMAIN``` to the URL of the Schoology instance. In addition, change ```GROUP_ID``` to the ID of the Schoology group. This can be found by visiting the Schoology website and by navigating to the Schoology group. The group's ID should be right after the ```/group/...``` subdirectory of the domain. To get a Schoolopy API key and secret, goto `schoology.(PUT DOMAIN HERE).org/api`. There, you can manage your API credentials. You will need the key and secret to run the server.
+
+In `config.py`, change `DOMAIN` to the URL of the Schoology instance. In addition, change `GROUP_ID` to the ID of the Schoology group. This can be found by visiting the Schoology website and by navigating to the Schoology group. The group's ID should be right after the `/group/...` subdirectory of the domain. To get a Schoolopy API key and secret, goto `schoology.(PUT DOMAIN HERE).org/api`. There, you can manage your API credentials. You will need the key and secret to run the server.
 
 ### google
+
 To setup Google OAuth2, go [here](https://developers.google.com/identity/oauth2/web/guides/get-google-api-clientid) and follow the instructions. Copy the json into a file called `google_auth.json` in the root of the project. In `config.py`, change `REDIRECT_URL` to the URL you used when you set up the Google project. Make sure that the redirect URL is added as one of the "Authorized redirect URIs."
 
 ## running
-Now, you can execute `SCHOOLOGY_API_KEY="PUT KEY HERE" SCHOOLOGY_API_SECRET="PUT SECRET HERE" ./run.sh`.
 
+Now, you can execute `SCHOOLOGY_API_KEY="PUT KEY HERE" SCHOOLOGY_API_SECRET="PUT SECRET HERE" ./run.sh`.
diff --git a/database.db b/database.db
new file mode 100644 (file)
index 0000000..a3b1cf5
Binary files /dev/null and b/database.db differ
index e5868d1131c14204b11670ce9f4670abe17c865f..89638d363e8dd2e5abfe734375d05682e0a1d533 100644 (file)
@@ -6,8 +6,7 @@
       "name": "Computer Science Club Website",
       "description": "(this website)",
       "authors": ["Damian Myrda"],
-      "source": "https://github.com/moncheeta/computer_science_club.git",
-      "images": null
+      "source": "https://github.com/moncheeta/computer_science_club.git"
     }
   ]
 }
index 08bd2e23557ad4e94b8002e9d97abdba07457978..c0c1437086e487561fa816c902cfeba3d43f7edd 100644 (file)
@@ -1,32 +1,92 @@
-import os
-from jsonpickle import decode, encode
+from models import Project
+import jsonpickle as json
+import sqlite3
+import pickle
 
 
 class Data:
     projects = []
 
-    def __init__(self, projects):
+    def __init__(self, projects=[]):
         self.projects = projects
 
 
-class Database:
+class JSONDatabase:
+    def __init__(self):
+        self.projects = []
+        self.read()
+
     def read(self):
-        if not os.path.isfile("database.json"):
-            return Data([])
         with open("database.json", "r") as file:
-            return decode(file.read())
+            self.projects = json.decode(file.read()).projects
+        return self.projects
 
-    def write(self, data):
+    def write(self):
         with open("database.json", "w") as file:
-            file.write(encode(data))
+            file.write(json.encode(Data(self.projects)))
+
+    def add(self, project):
+        self.projects.append(project)
+        self.write()
+
+
+class SQLDatabase:
+    def __init__(self):
+        self.connection = sqlite3.connect("database.db", check_same_thread=False)
+        self.cursor = self.connection.cursor()
+        self.cursor.execute(
+            """CREATE TABLE IF NOT EXISTS projects (
+            name text NOT NULL,
+            description text,
+            authors text NOT NULL,
+            source text
+        )"""
+        )
+        self.write()
+        self.read()
+
+    def __del__(self):
+        self.connection.close()
+
+    def read(self):
+        self.projects = []
+        self.cursor.execute("SELECT * FROM projects")
+        for data in self.cursor.fetchall():
+            name = data[0]
+            description = data[1]
+            authors = pickle.loads(data[2])
+            source = data[3]
+            project = Project(name, description, authors, source)
+            self.projects.append(project)
+        return self.projects
+
+    def write(self):
+        self.connection.commit()
+
+    def add(self, project):
+        self.projects.append(project)
+        data = (
+            project.name,
+            project.description,
+            pickle.dumps(project.authors),
+            project.source,
+        )
+        self.cursor.execute("INSERT INTO projects VALUES (?, ?, ?, ?)", data)
+        self.write()
 
 
 class ProjectDatabase:
+    def __init__(self):
+        self.database = SQLDatabase()
+
     def read(self):
-        projects = []
-        for project in Database().read().projects:
-            projects.append(project)
-        return projects
+        return self.database.read()
+
+    def write(self):
+        self.database.write()
+
+    def add(self, project):
+        self.database.add(project)
+
 
-    def write(self, projects):
-        Database().write(Data(projects))
+database = ProjectDatabase()
diff --git a/main.py b/main.py
index 21718fd88d5aa7dd33d7404b381899127fd8d5dd..c2498e2e0bb3630c61ccac58900b81eb2532f543 100644 (file)
--- a/main.py
+++ b/main.py
@@ -7,7 +7,7 @@ sys.path.append(os.path.join(PROJECT_DIR, "projects.py"))
 sys.path.append(os.path.join(PROJECT_DIR, "schoology.py"))
 from config import REDIRECT_URL
 from models import Project
-from database import ProjectDatabase
+from database import database
 from schoology import group
 from flask import Flask, request, redirect, abort, render_template, session
 from cachecontrol import CacheControl
@@ -45,15 +45,16 @@ def add_project():
             return abort(401)
         name = request.form["name"].rstrip()
         description = request.form["description"].rstrip()
+        if description == "":
+            description = None
         authors = request.form["authors"]
         for author in authors:
             author = author.rstrip()
         source = request.form["source"].rstrip()
         if source == "":
             source = None
-        images = request.files.get("images")
-        group.projects.append(Project(name, description, [authors], source, images))
-        ProjectDatabase().write(group.projects)
+        project = Project(name, description, [authors], source)
+        database.add(project)
         return redirect("/projects")
     return render_template(
         "projects.html", group=group, create=True, account=session.get("name")
index 348496686948bb02c064e9eb80d32ca50a714d6f..06f90ec2e0a3c1ed1b4eed56bb11dc99d702a2af 100644 (file)
@@ -3,11 +3,9 @@ class Project:
     description = ""
     authors = []
     source = None
-    images = None
 
-    def __init__(self, name, description, authors, source=None, images=None):
+    def __init__(self, name, description, authors, source=None):
         self.name = name
         self.description = description
         self.authors = authors
         self.source = source
-        self.images = images
diff --git a/projects.py b/projects.py
deleted file mode 100644 (file)
index 6074ee9..0000000
+++ /dev/null
@@ -1,19 +0,0 @@
-from models import Project
-from database import Database, Data
-
-
-class ProjectDatabase:
-    def read(self):
-        projects = []
-        for project in Database().read()["projects"]:
-            name = project.get("name")
-            description = project.get("description")
-            authors = project.get("authors")
-            source = project.get("source")
-            images = project.get("images")
-            projects.append(Project(name, description, authors, source, images))
-        return projects
-
-    def write(self, projects):
-        with open("database.json", "w") as file:
-            file.write(encode(Data(projects)))
index 7715362e90495d926f3f0ec367a743caa7fb15de..0b409b6ef9c2db25c69dbe1e39e1e7d963dfb88f 100644 (file)
@@ -2,7 +2,7 @@ import os
 from datetime import datetime
 from config import DOMAIN, GROUP_ID
 from models import Group, Event, Update, Discussion, Member
-from database import ProjectDatabase
+from database import database
 from schoolopy import Schoology, Auth
 
 
@@ -68,7 +68,7 @@ class SchoologyAPI:
         events = self.events()
         updates = self.updates()
         discussions = self.discussions()
-        projects = ProjectDatabase().read()
+        projects = database.read()
         members = self.members()
         return Group(name, description, events, updates, discussions, projects, members)
 
index c86dca609843ac1a5ee3de67f6049d1afacd683d..4c6067d0272ffd7d34b1765b8cc7e5a3d1460dac 100644 (file)
@@ -1,7 +1,8 @@
 {% import "elements/authors.html" as authors %} {% macro view(project) -%}
 <h2>{{ project.name }}</h2>
+{% if project.description %}
 <p>{{ project.description }}</p>
-{% if project.source %}
+{% endif %} {% if project.source %}
 <a target="_blank" href="{{ project.source }}">Source Code</a>
 <br />
 {% endif %} {{ authors.list(project.authors) }} {% if project.images %} {% for
@@ -21,7 +22,7 @@ project in projects %}
     <input name="name" id="name" required />
     <br />
     <label for="description">Description:</label>
-    <textarea name="description" id="description" required></textarea>
+    <textarea name="description" id="description"></textarea>
     <br />
     <label for="authors">Authors:</label>
     <input name="authors" id="authors" required />
@@ -29,9 +30,6 @@ project in projects %}
     <label for="source">Source:</label>
     <input name="source" id="source" />
     <br />
-    <label for="images">Images:</label>
-    <input name="images" id="images" type="file" accept="image/*" multiple />
-    <br />
     <input type="submit" value="Add" />
   </form>
 </center>