#main.py import config from flask import Flask, redirect from controllers.index import Index from controllers.login import Login from controllers.category import Category app = Flask(__name__) app.secret_key = config.vdict['secret_key'] Index.register(app, route_base='/') Login.register(app, route_base='/login') Category.register(app, route_base='/category') if __name__ == '__main__': app.run(debug=True)
#controllers/category.py import config, copy, lib, datetime from flask import render_template, request, session, redirect from flask_classful import FlaskView, route from models.categorydb import Categorydb class Category(FlaskView): def __init__(self): self.categorydb = Categorydb() self.lib = lib.Lib() @route('/', methods=['GET', 'POST']) def category(self): vdict = copy.deepcopy(config.vdict) vdict['blog_title'] = 'បង្កើតប្រភេទមេរៀន' vdict['datetime'] = self.lib.get_timezone() if request.method == "POST": 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) 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)
#models/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("INSERT INTO CATEGORIES (CATEGORY, CONTENT, CATDATE, CATTIME, AUTHOR) VALUES %s ", (category,)) self.conn.commit() self.conn.close() def select(self, amount): self.set_conection() SQL = "SELECT * FROM CATEGORIES LIMIT %s" self.cursor.execute(SQL, (amount,)) result = self.cursor.fetchall() self.conn.close() return result
GitHub: "https://github.com/Sokhavuth/E-Learning
Heroku: https://khmerweb-elearning.herokuapp.com/