Skip to content

Commit

Permalink
database now using sqlalchemy
Browse files Browse the repository at this point in the history
  • Loading branch information
AuxiliumCDNG committed Dec 29, 2021
1 parent 60cea9a commit 6104e4c
Show file tree
Hide file tree
Showing 12 changed files with 241 additions and 287 deletions.
2 changes: 1 addition & 1 deletion crossdomain.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,4 +57,4 @@ def wrapped_function(*args, **kwargs):

f.provide_automatic_options = False
return update_wrapper(wrapped_function, f)
return decorator
return decorator
27 changes: 0 additions & 27 deletions globals.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
import mysql.connector.cursor
from dbutils.pooled_db import PooledDB
from flask import Flask

from statics import config
Expand All @@ -8,29 +6,4 @@
app.config['TEMPLATES_AUTO_RELOAD'] = True
app.secret_key = config.secret_key

"""
pymysql.threadsafety = 3
mysql = pymysql.connect(
host=config.DB.host,
port=config.DB.port,
user=config.DB.user,
password=config.DB.password,
db=config.DB.db,
charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor
)
"""

connection_pool = PooledDB(mysql.connector, 5,
host=config.DB.host,
port=config.DB.port,
user=config.DB.user,
password=config.DB.password,
db=config.DB.db,
buffered=True
)

connection_pool.connection().cursor().execute("SET NAMES utf8mb4")

cut_objects = {}
6 changes: 1 addition & 5 deletions main.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
from flask_scss import Scss

import globals
from globals import app
from routes import user
from routes.api_create import api_create
Expand Down Expand Up @@ -38,7 +37,4 @@ def add_header(r):
Scss(app, static_dir="public/materialize", asset_dir="sass/materialize", load_paths=["sass/materialize/components", "sass/materialize/components/forms"])

if __name__ == "__main__":
try:
app.run("0.0.0.0", config.port)
except KeyboardInterrupt:
globals.connection_pool.close()
app.run("0.0.0.0", config.port)
21 changes: 10 additions & 11 deletions routes/api_comments.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,11 @@
import json
import time

import flask
from flask import Blueprint, request
from flask_login import login_required, current_user

from crossdomain import crossdomain
from globals import connection_pool, app, cut_objects
from statics import config
from globals import app
from statics import db
from statics.helpers import permissions_checker

api_moderate = Blueprint("api_comment", __name__)
Expand All @@ -20,13 +18,14 @@ def comment():
content = request.args["content"]

if permissions_checker(current_user, "interact", "comment", content_id):
with connection_pool.connection() as con, con.cursor(dictionary=True) as cursor:
cursor.execute(f"SELECT * FROM `{config.Instance.instance}_content` WHERE `id`='{content_id}'")
old = cursor.fetchone()
session = db.factory()
old = session.query(db.Content).filter_by(id=content_id)[0]

old["permissions"] = json.loads(old["permissions"])
old["permissions"][current_user.email] = "all"
query = (content_id, "comment", old["permissions"], content)
cursor.execute(f"INSERT INTO `{config.Instance.instance}_content` (`location`, `type`, `permissions`, `content`) VALUES (%s, %s, %s, %s)", query)
permissions = old.permissions
permissions[current_user.email] = "all"

session.add(db.Content(location=content_id, type="comment", permissions=permissions, content=content))
session.commit()
session.close()
else:
return {"error": "missing permissions"}, 403
28 changes: 6 additions & 22 deletions routes/api_create.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import json

import flask
from flask import Blueprint, request
from flask_login import login_required, current_user

from crossdomain import crossdomain
from globals import connection_pool, app
from globals import app
from statics import config
from statics import db
from statics.helpers import permissions_checker

api_create = Blueprint("api_create", __name__)
Expand All @@ -26,26 +26,10 @@ def create_content():
elif permission:
data = {"name": request.args["name"], "location": request.args["location"], "type": request.args["type"]}

with connection_pool.connection() as con, con.cursor(dictionary=True) as cursor:
# ---------------------- category gets created ----------------------
if request.args["type"] == "category":
cursor.execute(f"""INSERT INTO {config.Instance.instance}_content (name, location, type, permissions) VALUES ('{data['name']}', '{data['location']}', '{data['type']}', '{json.dumps({current_user.email: 'all'})}')""")
# ---------------------- thread gets created ----------------------
elif request.args["type"] == "thread":
data["content"] = request.args["content"]

default_permissions = '{"%s": "all"}' % current_user.email
query = (data['name'], data['location'], data['type'], data["content"], default_permissions)
print("inserting data: ", query)
cursor.execute(f"INSERT INTO `{config.Instance.instance}_content` (name, location, type, content, permissions) VALUES (%s, %s, %s, %s, %s)", query)
else:
return {"error": "Unknown Type"}, 400

dest = str(cursor.lastrowid) # get destination to redirect the client to
print(dest)

con.commit()
con.close()
session = db.factory()
session.add(db.Content(name=data["name"], location=data["location"], type=data["type"], permissions={current_user.email: 'all'}))
session.commit()
session.close()

return {"message": "success"}, 201
else:
Expand Down
98 changes: 49 additions & 49 deletions routes/api_get.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import json

import flask
from flask import Blueprint, request, render_template, jsonify
from flask import Blueprint, request, jsonify
from flask_login import login_required, current_user

from crossdomain import crossdomain
from globals import connection_pool, app
from statics import config
from globals import app
from statics import db
from statics.helpers import permissions_checker

api_get = Blueprint("api_get", __name__)
Expand All @@ -17,68 +17,67 @@
def get_content():
location = request.args["location"]

with connection_pool.connection() as con, con.cursor(dictionary=True) as cursor:
q = f"SELECT `id`, `name` FROM {config.Instance.instance}_content WHERE `id`='{location}'"
cursor.execute(q)
res = cursor.fetchone()
if res is None:
return flask.abort(flask.Response(response="Location not found", status=404))
session = db.factory()

if not permissions_checker(current_user, "view", "all", location):
return flask.abort(flask.Response(response="No permission to view this location", status=906))
res = session.query(db.Content).filter_by(id=location).first()
if res is None:
return flask.abort(flask.Response(response="Location not found", status=404))

q = f"SELECT `id`, `name`, `location`, `type` FROM {config.Instance.instance}_content WHERE `location`='{location}'"
cursor.execute(q)
content = cursor.fetchall()
if not permissions_checker(current_user, "view", "all", location):
return flask.abort(flask.Response(response="No permission to view this location", status=906))

q = f"SELECT * FROM {config.Instance.instance}_content WHERE `id`='{location}'"
cursor.execute(q)
current = cursor.fetchone()
content = session.query(db.Content).filter_by(location=location).all()
_current = session.query(db.Content).filter_by(id=location).first()

con.close()
current = _current

if current is not None:
try:
current["permissions"] = json.loads(current["permissions"])[current_user.email]
current.permissions = current.permissions[current_user.email]
except KeyError:
current["permissions"] = {}

################## DONE FETCHING DATA ###################
current.permissions = {}

################## DONE FETCHING DATA ##################
if isinstance(content, tuple): # content is empty
return content

if content == False: # do NOT change to if not content!
return {"error": "location not found"}, 404

if "breadcrumb" in request.args:
with connection_pool.connection() as con, con.cursor(dictionary=True) as cursor:
data = []
################## UPDATING CONTENT IF VERSION ID IS SPECIFIED ##################
if "version" in request.args.keys():
version = session.query(db.Versions).filter_by(id=request.args["verions"]).first()

cursor.execute(f"SELECT id, name, location FROM {config.Instance.instance}_content WHERE `id`='{request.args['location']}'")
res = cursor.fetchone()
data.append(res)
while res["id"] != 0:
cursor.execute(f"SELECT id, name, location FROM {config.Instance.instance}_content WHERE `id`='{res['location']}'")
res = cursor.fetchone()
data.append(res)
if str(current["id"]) != str(version["content_id"]):
return {"error": "version ID not found for this post!"}, 409
current["name"] = version["name"]
current["content"] = version["content"]

if None in data:
data.remove(None)
session.close()

# data = [element for element in data if element["id"] != 0] # Filter out root entry, which is already in the page
################## PARSE SQLA OBJECTS TO JSON ##################
return jsonify(
{
"current": {c.name: str(getattr(current, c.name)) for c in current.__table__.columns},
"contents": [{c.name: str(getattr(x, c.name)) for c in x.__table__.columns if c.name in ["id", "type", "name"]} for x in content]
}
)

if "version" in request.args.keys():
with connection_pool.connection() as con, con.cursor(dictionary=True) as cursor:
cursor.execute(f"SELECT * FROM {config.Instance.instance}_versions WHERE `id`='{request.args['version']}'")
version = cursor.fetchone()
if str(current["id"]) != str(version["content_id"]):
return {"error": "version ID not found for this post!"}, 409
current["name"] = version["name"]
current["content"] = version["content"]
con.close()

return jsonify({"current": current, "contents": content})
@crossdomain(origin="*", current_app=app)
@api_get.route("/api/content/breadcrumb/")
@login_required
def breadcrumb():
data = []
session = db.factory()

res = session.query(db.Content).filter_by(id=request.args["location"]).first()
data.append(res)
while res["id"] != 0:
res = session.query(db.Content).filter_by(id=res["location"]).first()
data.append(res)

if None in data:
data.remove(None)

@crossdomain(origin="*", current_app=app)
@api_get.route("/api/content/versions/")
Expand All @@ -89,8 +88,9 @@ def versions():
if not permissions_checker(current_user, "view", "all", location):
return {"error": "missing permissions"}, 403

with connection_pool.connection() as con, con.cursor(dictionary=True) as cursor:
cursor.execute(f"SELECT * FROM {config.Instance.instance}_versions WHERE `content_id`='{location}' ORDER BY `id` DESC")
res = cursor.fetchall()
session = db.factory()

res = session.query(db.Versions).filter_by(content_id=location).order_by(db.Versions.id)
res = reversed(res)

return jsonify(res)
Loading

0 comments on commit 6104e4c

Please sign in to comment.