Use db_query() function to get entries from db
[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 from contextlib import closing
9 import locale
10 locale.setlocale(locale.LC_ALL, '')
11
12 DATABASE = '/tmp/cavote.db'
13 SECRET_KEY = '{J@uRKO,xO-PK7B,jF?>iHbxLasF9s#zjOoy=+:'
14 DEBUG = True
15 USERNAME = 'admin'
16 PASSWORD = 'admin'
17
18 app = Flask(__name__)
19 app.config.from_object(__name__)
20
21 def connect_db():
22 return sqlite3.connect(app.config['DATABASE'])
23
24 @app.before_request
25 def before_request():
26 g.db = connect_db()
27
28 @app.teardown_request
29 def teardown_request(exception):
30 g.db.close()
31
32 @app.route('/')
33 def home():
34 return render_template('index.html')
35
36 def query_db(query, args=(), one=False):
37 cur = g.db.execute(query, args)
38 rv = [dict((cur.description[idx][0], value)
39 for idx, value in enumerate(row)) for row in cur.fetchall()]
40 return (rv[0] if rv else None) if one else rv
41
42 def init_db():
43 with closing(connect_db()) as db:
44 with app.open_resource('schema.sql') as f:
45 db.cursor().executescript(f.read())
46 db.commit()
47
48 #----------------
49 # Login / Logout
50
51 def valid_login(username, password):
52 return username == app.config['USERNAME'] and password == app.config['PASSWORD']
53
54 @app.route('/login', methods=['GET', 'POST'])
55 def login():
56 error = None
57 if request.method == 'POST':
58 if valid_login(request.form['username'], request.form['password']):
59 session['username'] = request.form['username']
60 if session['username'] == 'admin':
61 session['is_admin'] = True
62 flash('You were logged in')
63 return redirect(url_for('home'))
64 else:
65 error = "Invalid username/password"
66 return render_template('login.html', error=error)
67
68 @app.route('/logout')
69 def logout():
70 session.pop('username', None)
71 session.pop('is_admin', None)
72 flash('You were logged out')
73 return redirect(url_for('home'))
74
75 #---------------
76 # User settings
77 @app.route('/user/settings/<username>')
78 def show_settings(username):
79 if username != session['username']:
80 abort(401)
81
82
83 #------------
84 # User admin
85
86
87 #------------
88 # Votes list
89
90 @app.route('/votes/<votes>')
91 def show_votes(votes):
92 today = date.today()
93 if votes == 'all':
94 votes = query_db('select title, description, date_begin, date_end from votes order by id desc')
95 elif votes == 'archive':
96 votes = query_db('select title, description, date_begin, date_end from votes where date_end < (?) order by id desc', [today])
97 elif votes == 'current':
98 votes = query_db('select title, description, date_begin, date_end from votes where date_end >= (?) order by id desc', [today])
99 else:
100 abort(404)
101 return render_template('show_votes.html', votes=votes)
102
103 #-------------
104 # Votes admin
105
106 @app.route('/votes/admin/new')
107 def new_vote():
108 if not session.get('is_admin'):
109 abort(401)
110 return render_template('new_vote.html')
111
112 @app.route('/votes/admin/add', methods=['POST'])
113 def add_vote():
114 if not session.get('is_admin'):
115 abort(401)
116 date_begin = date.today()
117 date_end = date.today() + timedelta(days=int(request.form['days']))
118 transparent = 0
119 public = 0
120 multiplechoice = 0
121 if 'transparent' in request.form.keys():
122 transparent = 1
123 if 'public' in request.form.keys():
124 public = 1
125 if 'multiplechoice' in request.form.keys():
126 multiplechoice = 1
127 g.db.execute('insert into votes (title, description, date_begin, date_end, is_transparent, is_public, is_multiplechoice) values (?, ?, ?, ?, ?, ?, ?)',
128 [request.form['title'], request.form['description'], date_begin, date_end, transparent, public, multiplechoice])
129 g.db.commit()
130 flash('New entry was successfully posted')
131 return redirect(url_for('home'))
132
133 #------
134 # Main
135
136 if __name__ == '__main__':
137 app.run()
138