1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
|
# -*- coding: utf-8 -*-
import sqlite3
#all the imports
from flask import Flask, request, session, g, redirect, url_for, \
abort, render_template, flash, _app_ctx_stack
import hashlib
# configuration
app = Flask(__name__)
app.config.from_envvar('CONF')
def connect_db():
return sqlite3.connect(app.config['DATABASE'])
def init_db():
"""Creates the database tables."""
with app.app_context():
db = get_db()
db.row_factory = sqlite3.Row
with app.open_resource('schema.sql') as f:
db.cursor().executescript(f.read())
db.commit()
def get_db():
"""Opens a new database connection if there is none yet for the
current application context.
"""
top = _app_ctx_stack.top
if not hasattr(top, 'sqlite_db'):
top.sqlite_db = sqlite3.connect(app.config['DATABASE'])
return top.sqlite_db
def query_db(query, args=(), one=False):
cur = get_db().execute(query, args)
rv = cur.fetchall()
cur.close()
return (rv[0] if rv else None) if one else rv
@app.teardown_appcontext
def close_db_connection(exception):
"""Closes the database again at the end of the request."""
top = _app_ctx_stack.top
if hasattr(top, 'sqlite_db'):
top.sqlite_db.close()
@app.route('/')
def main():
try:
if session['logged_in']:
return redirect(url_for('nouvelles'))
else:
return redirect(url_for('login'))
except KeyError:
return redirect(url_for('login'))
@app.route('/nouvelles')
def show_news():
pass
@app.route('/login', methods=['GET', 'POST'])
def login():
error = None
if request.method == 'POST':
#TODO: do something better, maybe scrypt
if query_db('select * from users where user = ? and password = ?',
(request.form['username'],
hashlib.md5(request.form['password']).hexdigest())):
session['logged_in'] = True
return redirect(url_for('nouvelles'))
else:
error = u'Utilisateur non enregistré'
return render_template('login.html', error=error)
if __name__=="__main__":
init_db()
app.run()
|