from flask import Flask from . import db from . import auth from . import blog
defcreate_app(test_config=None): # create and configure the app app = Flask(__name__, instance_relative_config=True) app.config.from_mapping( SECRET_KEY='dev', DATABASE=os.path.join(app.instance_path, 'flaskr.sqlite'), )
if test_config isNone: # load the instance config, if it exists, when not testing app.config.from_pyfile('config.py', silent=True) else: # load the test config if passed in app.config.from_mapping(test_config)
> set FLASK_APP=flaskr > set FLASK_ENV=development > flask run
成功会输出
1 2 3 4 5 6 7
* Serving Flask app 'flaskr' (lazy loading) * Environment: development * Debug mode: on * Running on http://127.0.0.1:5000 (Press CTRL+C to quit) * Restarting with stat * Debugger is active! * Debugger PIN: 714-187-162
import click from flask import current_app, g from flask.cli import with_appcontext
definit_db(): db = get_db()
with current_app.open_resource('schema.sql') as f: db.executescript(f.read().decode('utf8'))
@click.command('init-db') @with_appcontext definit_db_command(): """Clear the existing data and create new tables.""" init_db() click.echo('Initialized the database.')
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) );
from flask import ( Blueprint, flash, g, redirect, render_template, request, url_for ) from werkzeug.exceptions import abort
from flaskr.auth import login_required from flaskr.db import get_db
bp = Blueprint('blog', __name__)
@bp.route('/') defindex(): db = get_db() posts = db.execute( 'SELECT p.id, title, body, created, author_id, username' ' FROM post p JOIN user u ON p.author_id = u.id' ' ORDER BY created DESC' ).fetchall() return render_template('blog/index.html', posts=posts)
@bp.route('/create', methods=('GET', 'POST')) @login_required defcreate(): if request.method == 'POST': title = request.form['title'] body = request.form['body'] error = None
ifnot title: error = 'Title is required.'
if error isnotNone: flash(error) else: db = get_db() db.execute( 'INSERT INTO post (title, body, author_id)' ' VALUES (?, ?, ?)', (title, body, g.user['id']) ) db.commit() return redirect(url_for('blog.index'))
return render_template('blog/create.html')
defget_post(id, check_author=True): post = get_db().execute( 'SELECT p.id, title, body, created, author_id, username' ' FROM post p JOIN user u ON p.author_id = u.id' ' WHERE p.id = ?', (id,) ).fetchone()
if post isNone: abort(404, f"Post id {id} doesn't exist.")
if check_author and post['author_id'] != g.user['id']: abort(403)
return post
@bp.route('/<int:id>/update', methods=('GET', 'POST')) @login_required defupdate(id): post = get_post(id)
if request.method == 'POST': title = request.form['title'] body = request.form['body'] error = None
ifnot title: error = 'Title is required.'
if error isnotNone: flash(error) else: db = get_db() db.execute( 'UPDATE post SET title = ?, body = ?' ' WHERE id = ?', (title, body, id) ) db.commit() return redirect(url_for('blog.index'))
@bp.route('/<int:id>/delete', methods=('POST',)) @login_required defdelete(id): get_post(id) db = get_db() db.execute('DELETE FROM post WHERE id = ?', (id,)) db.commit() return redirect(url_for('blog.index'))