[Flask] Problems with a flask tutorial

Andreas Dorfner andreas.dorfner at stud.hs-regensburg.de
Wed Apr 6 01:53:50 EDT 2016


Hi all,

to save the data in a database, I'm trying to use flask. For my first steps with flask, I'm working with the following online tutorial:

http://flask.pocoo.org/docs/0.10/tutorial/dbinit/

The web server on Beaglebone Black (with running Debian on it) is still working, but I have problems with "Step3: Creating the Database". By doing the online tutorial step by step, normally it should be possible to create a database by starting up a Python shell and import and call a function like that:

Running a python shell:
root at beaglebone:~/flaskr# python

  >>> from flaskr import init_db
  >>> init_db()

By doing so, I get the following error message:

Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    File "flaskr.py", line 28, in init_db
      with closing(connect_db()) as db:
    File "flaskr.py", line 23, in connect_db
      return sqlite3.connect(app.config['DATABASE'])
KeyError: 'DATABASE'

Does anybody have an idea why I get this error?
Attached you can find the source code and the database schema.

Many thanks for your help.
Andreas




---
Diese E-Mail wurde von Avast Antivirus-Software auf Viren geprüft.
https://www.avast.com/antivirus
-------------- next part --------------
#all the imports
import sqlite3
from flask import Flask, request, session, g, redirect, url_for, \
     abort, render_template, flash
from contextlib import closing

# configuration
DATABASE = '/temp/flaskr.db'
DEBUG = True
SECRET_KEY = 'development key'
USERNAME = 'admin'
PASSWORD = 'default'
#---------------------------------------------------------------------------

# create our little application :)
app = Flask(__name__)
app.config.from_envvar('FLASKR_SETTINGS', silent=True)
#app.config.from_object(__name__)
#---------------------------------------------------------------------------

#connects to the specific database
def connect_db():
    return sqlite3.connect(app.config['DATABASE'])
#---------------------------------------------------------------------------

#initializes the database
def init_db():
   with closing(connect_db()) as db:
        with app.open_resource('schema.sql', mode='r') as f:
            db.cursor().executescript(f.read())
        db.commit()
#---------------------------------------------------------------------------

#Run the file as a standalone application on IP address 192.168.7.2 (BBB)
#at Port 5000.			
if __name__ == '__main__':
	app.run(host = '192.168.7.2')
#---------------------------------------------------------------------------

#open the database before each request
#@app.before_request
#def before_request():
#    g.db = connect_db()
#---------------------------------------------------------------------------

#shut down the database afterwards
#@app.teardown_request
#def teardown_request(exception):
#    db = getattr(g, 'db', None)
#    if db is not None:
#        db.close()
#---------------------------------------------------------------------------

#That function pass the entries as dicts to the show_entries.html template
#and return the broadcasted one.
#@app.route('/')
#def show_entries():
#    cur = g.db.execute('select title, text from entries order by id desc')
#    entries = [dict(title=row[0], text=row[1]) for row in cur.fetchall()]
#    return render_template('show_entries.html', entries=entries)
#---------------------------------------------------------------------------

#This view lets the user add new entries if they are logged in. There is a check 
#here if the user is logged in as well.
#@app.route('/add', methods=['POST'])
#def add_entry():
#    if not session.get('logged_in'):
#        abort(401)
#    g.db.execute('insert into entries (title, text) values (?, ?)',
#                 [request.form['title'], request.form['text']])
#    g.db.commit()
#    flash('New entry was successfully posted')
#    return redirect(url_for('show_entries'))
#---------------------------------------------------------------------------
	
#Login function
#@app.route('/login', methods=['GET', 'POST'])
#def login():
#    error = None
#    if request.method == 'POST':
#        if request.form['username'] != app.config['USERNAME']:
#            error = 'Invalid username'
#        elif request.form['password'] != app.config['PASSWORD']:
#            error = 'Invalid password'
#        else:
#            session['logged_in'] = True
#            flash('You were logged in')
#            return redirect(url_for('show_entries'))
#    return render_template('login.html', error=error)
#---------------------------------------------------------------------------

#Logout function
#@app.route('/logout')
#def logout():
#    session.pop('logged_in', None)
#    flash('You were logged out')
#    return redirect(url_for('show_entries'))
#---------------------------------------------------------------------------


-------------- next part --------------
drop table if exists entries;
create table entries (
  id integer primary key autoincrement,
  title text not null,
  text text not null
);


More information about the Flask mailing list