add deadlines
[cavote.git] / main.py
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
3
4 from flask import Flask, request, session, g, redirect, url_for, abort, \
5 render_template, flash
6 import sqlite3
7 from datetime import date, timedelta
8
9 DATABASE = '/tmp/cavote.db'
10 SECRET_KEY = '{J@uRKO,xO-PK7B,jF?>iHbxLasF9s#zjOoy=+:'
11 DEBUG = True
12 USERNAME = 'admin'
13 PASSWORD = 'admin'
14
15 app = Flask(__name__)
16 app.config.from_object(__name__)
17
18 def connect_db():
19 return sqlite3.connect(app.config['DATABASE'])
20
21 @app.before_request
22 def before_request():
23 g.db = connect_db()
24
25 @app.teardown_request
26 def teardown_request(exception):
27 g.db.close()
28
29 @app.route('/admin/votes')
30 def show_votes():
31 cur = g.db.execute('select title, description, date from votes order by id desc')
32 votes = [dict(title=row[0], description=row[1], date=row[2]) for row in cur.fetchall()]
33 return render_template('show_votes.html', votes=votes)
34
35 @app.route('/admin/vote/add', methods=['POST'])
36 def add_vote():
37 if not session.get('logged_in'):
38 abort(401)
39 g.db.execute('insert into votes (title, description, date) values (?, ?, ?)',
40 [request.form['title'], request.form['description'], date.today() + timedelta(days=60)])
41 g.db.commit()
42 flash('New entry was successfully posted')
43 return redirect(url_for('show_votes'))
44
45 @app.route('/login', methods=['GET', 'POST'])
46 def login():
47 error = None
48 if request.method == 'POST':
49 if request.form['username'] != app.config['USERNAME']:
50 error = 'Invalid username'
51 elif request.form['password'] != app.config['PASSWORD']:
52 error = 'Invalid password'
53 else:
54 session['logged_in'] = True
55 flash('You were logged in')
56 return redirect(url_for('show_votes'))
57 return render_template('login.html', error=error)
58
59 @app.route('/logout')
60 def logout():
61 session.pop('logged_in', None)
62 flash('You were logged out')
63 return redirect(url_for('show_votes'))
64
65
66
67 if __name__ == '__main__':
68 app.run()
69
70