Backend Category CRUD Functionalities
#main.py
import config
from flask import Flask
from controllers.index import Index
from controllers.login import Login
from controllers.dashboard.dashboard import Dashboard

app = Flask(__name__)
app.secret_key = config.vdict['secret_key']

Index.register(app, route_base='/')
Login.register(app, route_base='/login')
Dashboard.register(app, route_base='/dashboard')

if __name__ == '__main__':
  app.run(debug=True)
#controllers/category.py
import config, copy
from flask import render_template, session, redirect
from flask_classful import FlaskView, route
from controllers.dashboard.category import Category

class Dashboard(FlaskView):
  def __init__(self):
    self.cat = Category()

  @route('/')
  def index(self):
    vdict = copy.deepcopy(config.vdict)
    vdict['blog_title'] = 'ទំព័រ​គ្រប់គ្រង'

    if 'logged-in' in session:
      return render_template('dashboard/dashboard.html', data=vdict)
    else:
      return redirect('/login/')

  @route('/category/', methods=['GET', 'POST'])
  def category(self):
    return self.cat.get_post()

  @route('/category/delete/<category>')
  def delete(self, category):
    return self.cat.delete(category)

  @route('/category/edit/<category>')
  def edit(self, category):
    return self.cat.edit(category)
    
dashboard = Dashboard()
#controllers/dashboard/category.py
import config, copy, lib, datetime
from flask import render_template, request, session, redirect
from models.dashboard.categorydb import Categorydb

class Category():
  def __init__(self):
    self.categorydb = Categorydb()
    self.lib = lib.Lib()

  def get_post(self):
    vdict = copy.deepcopy(config.vdict)
    vdict['blog_title'] = 'បង្កើតប្រភេទមេរៀន'
    vdict['datetime'] = self.lib.get_timezone()
    vdict['categories'] = self.categorydb.select(vdict['dashboard_max_category'])
    vdict['thumbs'] = self.lib.get_thumbs(vdict['categories'], 2)

    if (request.method == "POST") and ('logged-in' in session):
      category = request.form['fcategory-title']
      if not category:
        category = 'unknown'
        
      content = request.form['fcontent']
      date = request.form['fcategory-date']
      time = request.form['fcategory-time']
      author = session['logged-in']

      try:
        date = datetime.datetime.strptime(date, "%d/%m/%Y")
      except ValueError:
        vdict['message'] = 'ទំរង់​កាលបរិច្ឆេទ​មិន​ត្រឹមត្រូវ!'
        return render_template('dashboard/category.html', data=vdict)

      try:
        time = datetime.datetime.strptime(time, "%H:%M:%S")
      except ValueError:
        vdict['message'] = 'ទំរង់​ពេល​វេលា​មិន​ត្រឹមត្រូវ!'
        return render_template('dashboard/category.html', data=vdict)

      self.categorydb.insert(category, content, date, time, author)
      vdict['categories'] = self.categorydb.select(vdict['dashboard_max_category'])
      vdict['thumbs'] = self.lib.get_thumbs(vdict['categories'], 2)

      return render_template('dashboard/category.html', data=vdict)

    else:
      if 'logged-in' in session:
        return render_template('dashboard/category.html', data=vdict)

      return render_template('login.html', data=vdict)

  def delete(self, category):
    if 'logged-in' in session:
      self.categorydb.delete(category)
      return redirect('/dashboard/category/')

    return render_template('login.html', data=vdict)

  def edit(self, category):
    if 'logged-in' in session:
      vdict = copy.deepcopy(config.vdict)
      vdict['blog_title'] = 'បង្កើតប្រភេទមេរៀន'
      vdict['categories'] = self.categorydb.select(vdict['dashboard_max_category'])
      vdict['thumbs'] = self.lib.get_thumbs(vdict['categories'], 2)
      category = self.categorydb.select(1, category)
      vdict['datetime'] = (category[3].strftime('%d/%m/%Y'), category[4].strftime('%H:%M:%S'))
      vdict['category'] = category

      return render_template('dashboard/category.html', data=vdict)

    return render_template('login.html', data=vdict)
#models/dashboard/userdb.py
import os, psycopg2

class Categorydb():
  def __init__(self):
    self.create_table()

  def set_conection(self):
    if 'DYNO' in os.environ:
      DATABASE_URL = os.environ['DATABASE_URL']
      self.conn = psycopg2.connect(DATABASE_URL, sslmode='require')
      self.cursor = self.conn.cursor()
    else: 
      self.conn = psycopg2.connect(
        database="postgres", 
        user="postgres", 
        password="sokhavuth", 
        host="localhost", 
        port="5432"
      )

      self.cursor = self.conn.cursor()

  def create_table(self):
    self.set_conection()
    
    SQL = '''CREATE TABLE IF NOT EXISTS CATEGORIES(
      ID SERIAL PRIMARY KEY,
      CATEGORY VARCHAR(320),
      CONTENT TEXT,
      CATDATE DATE,
      CATTIME TIME,
      AUTHOR VARCHAR(320)
    )'''

    self.cursor.execute(SQL)
    self.conn.commit()
    self.conn.close() 

  def insert(self, *category):
    self.set_conection()

    self.cursor.execute("SELECT CATEGORY FROM CATEGORIES WHERE CATEGORY = %s", (category[0],))
    result = self.cursor.fetchone()
    if not result:
      self.cursor.execute("INSERT INTO CATEGORIES (CATEGORY, CONTENT, CATDATE, CATTIME, AUTHOR) VALUES %s ", (category,))
    else:
      sql = "UPDATE CATEGORIES SET CATEGORY = %s, CONTENT = %s, CATDATE = %s, CATTIME = %s, AUTHOR = %s WHERE CATEGORY = '"+category[0]+"'"
      self.cursor.execute(sql, category)
  
    self.conn.commit()
    self.conn.close()

  def select(self, amount, category=''):
    self.set_conection()

    if category:
      SQL = "SELECT * FROM CATEGORIES WHERE CATEGORY = %s LIMIT 1"
      self.cursor.execute(SQL, (category,))
      result = self.cursor.fetchone()

    else:
      SQL = "SELECT * FROM CATEGORIES ORDER BY CATDATE DESC, CATTIME DESC LIMIT %s"
      self.cursor.execute(SQL, (amount,))
      result = self.cursor.fetchall()
    
    self.conn.close()
    return result

  def delete(self, category):
    self.set_conection()

    SQL = "DELETE FROM CATEGORIES WHERE CATEGORY = %s"

    self.cursor.execute(SQL, (category,))

    self.conn.commit()
    self.conn.close()

GitHub: "https://github.com/Sokhavuth/E-Learning
Heroku: https://khmerweb-elearning.herokuapp.com/