@app.route('/login', methods=['POST', 'GET']) deflogin(): error = None if request.method == 'POST': if valid_login(request.form['username'],request.form['password']): return log_the_user_in(request.form['username']) else: error = 'Invalid username/password' # the code below is executed if the request method # was GET or the credentials were invalid return render_template('login.html', error=error)
#flaskr/schema.sql DROPTABLE IF EXISTSuser; DROPTABLE IF EXISTS post;
CREATETABLEuser ( id INTEGERPRIMARY KEY AUTOINCREMENT, username TEXT UNIQUENOTNULL, password TEXT NOTNULL );
CREATETABLE post ( id INTEGERPRIMARY KEY AUTOINCREMENT, author_id INTEGERNOTNULL, created TIMESTAMPNOTNULLDEFAULTCURRENT_TIMESTAMP, title TEXT NOTNULL, body TEXT NOTNULL, FOREIGN KEY (author_id) REFERENCESuser (id) );
运行
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#flaskr/db.py definit_db(): db = get_db()
with current_app.open_resource('schema.sql') as f: db.executescript(f.read().decode('utf8'))
@click.command('init-db') definit_db_command(): """Clear the existing data and create new tables.""" init_db() click.echo('Initialized the database.')