# -*- 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()