server.py 2.33 KB
Newer Older
1
#!/bin/python
2
3
from flask import Flask, render_template, g
import mysql.connector
4
import sqlite3
5
import os
6

7
app = Flask(__name__)
8
config = app.config
9
10
11
12
config['DB_SCHEMA'] = 'db_schema.sql'
config['DB_DATA'] = 'db_example.sql'
config['SQLITE_INIT_SCHEMA'] = False
config['SQLITE_INIT_DATA'] = False
13
config.from_pyfile('config.py')
14

15
16
17
18
19
20
21
22
23
24
25
if config['DB_ENGINE'] == 'sqlite':
	created = not os.path.exists(config['SQLITE_DB'])
	db = sqlite3.connect(config['SQLITE_DB'])
	cur = db.cursor()
	if config['SQLITE_INIT_SCHEMA']:
		cur.executescript(open(config['DB_SCHEMA']).read())
	if config['SQLITE_INIT_DATA'] and created:
		cur.executescript(open(config['DB_DATA']).read())
	db.commit()
	db.close()

26
27
28
29
30
31
32
33
34
35
# Row wrapper for sqlite
def dict_factory(cursor, row):
	d = {}
	for idx, col in enumerate(cursor.description):
		if type(row[idx]) == str:
			d[col[0].split('.')[-1]] = row[idx].replace('\\n','\n')
		else:
			d[col[0].split('.')[-1]] = row[idx]
	return d

36
def query(operation, *params):
37
	if config['DB_ENGINE'] == 'mysql':
38
		if 'db' not in g or not g.db.is_connected():
39
			g.db = mysql.connector.connect(user=config['MYSQL_USER'], password=config['MYSQL_PASSWD'], host=config['MYSQL_HOST'], database=config['MYSQL_DB'])
40
41
42
		cur = g.db.cursor(dictionary=True)
		cur.execute(operation.replace('?', '%s'), params)
		return cur.fetchall()
43
	elif config['DB_ENGINE'] == 'sqlite':
44
		if 'db' not in g or not g.db.is_connected():
45
			g.db = sqlite3.connect(config['SQLITE_DB'])
46
47
48
49
			g.db.row_factory = dict_factory
		cur = g.db.cursor()
		cur.execute(operation, params)
		return cur.fetchall()
50

51
52
@app.route('/')
def index():
53
	return render_template('index.html', latestvideos=query('''
54
				SELECT lectures.*, max(videos.time_updated) AS lastvidtime, courses.short, courses.downloadable, courses.title AS coursetitle
55
56
57
				FROM lectures
				LEFT JOIN videos ON (videos.lecture_id = lectures.id)
				LEFT JOIN courses on (courses.id = lectures.course_id)
58
				WHERE (? OR (courses.visible AND courses.listed AND lectures.visible AND videos.visible))
59
60
61
62
				GROUP BY videos.lecture_id
				ORDER BY lastvidtime DESC
				LIMIT 5
			''', False))
63

Andreas Valder's avatar
Andreas Valder committed
64
65
@app.route('/videos')
def videos():
66
	return render_template('videos.html')
Andreas Valder's avatar
Andreas Valder committed
67
68
69

@app.route('/faq')
def faq():
70
	return render_template('faq.html')
Andreas Valder's avatar
Andreas Valder committed
71

Andreas Valder's avatar
Andreas Valder committed
72
73
74
75
@app.route('/play')
def play():
	return render_template('play.html',  active_page='play')

76
77
if __name__ == '__main__':
	app.run()