from setuptools import setup
setup(
name='flaskr',
packages=['flaskr'],
include_package_data=True,
install_requires=[
'flask',
],
)
graft flaskr/templates
graft flaskr/static
include flaskr/schema.sql
from .flaskr import app
pip install --editable .
export FLASK_APP=flaskr
export FLASK_DEBUG=true
flask run
step 4.database connections
建立一個數據庫的連接
def get_db():
"""Opens a new database connection if there is none yet for the
current application context.
"""
if not hasattr(g, 'sqlite_db'):
g.sqlite_db = connect_db()
return g.sqlite_db
@app.teardown_appcontext
def close_db(error):
"""Closes the database again at the end of the request."""
if hasattr(g, 'sqlite_db'):
g.sqlite_db.close()
step 5.creating the database
flasKr是一個由數據庫系統驅動的應用程式
所以我們需要一個模式來告訴它如何儲存資訊
sqlite3 /tmp/flaskr.db < schema.sql
def init_db():
db = get_db()
with app.open_resource('schema.sql', mode='r') as f:
db.cursor().executescript(f.read())
db.commit()
@app.cli.command('initdb')
def initdb_command():
"""Initializes the database."""
init_db()
print('Initialized the database.')
flask initdb
Initialized the database.
step 6.the view functions
建立完數據庫並確定可以使用後,需要一些視圖功能
需要以下四個:
show entries 顯示條目
顯示所有數據庫裡面所儲存的資訊
@app.route('/')
def show_entries():
db = get_db()
cur = db.execute('select title, text from entries order by id desc')
entries = cur.fetchall()
return render_template('show_entries.html', entries=entries)
add new entry 新增條目
讓登入的使用者可以新增條目
@app.route('/add', methods=['POST'])
def add_entry():
if not session.get('logged_in'):
abort(401)
db = get_db()
db.execute('insert into entries (title, text) values (?, ?)',
[request.form['title'], request.form['text']])
db.commit()
flash('New entry was successfully posted')
return redirect(url_for('show_entries'))