#flask學習筆記-09:留言板(二)

Step 5: 視圖函數html

1.顯示條目前端

@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)

看看這裏發生了什麼,當請求/時,咱們去執行了一句查詢命令。在python shell執行過程就是這個樣子,前面加載模塊就不寫了,基本就是這麼一個過程。python

>>> cur = connect_db().execute('select title, text from entries order by id desc')
>>> for row in cur.fetchall():
...     type(row)
... 
<type 'tuple'>
<type 'tuple'>
<type 'tuple'>
>>> entries = [dict(title=row[0], text=row[1]) for row in cur.fetchall()]
>>> for i in entries:
...     print " title:%s text:%s" %(i['title'], i['text'])
... 
 title:zabbix是最好的監控軟件 text:不服來辯~!
 title:你好呀? text:哇哈哈哈哈。。
 title:hello text:my name is LOL

從數據庫中讀取 titletext 字段。 id 最大的記錄(最新的條目)在最上面。從指針返回的記錄集是一個包含 select 語句查詢結果的元組。而後把cur這個結果組成一個字典列表。能夠試着打印這個字典。,最後把這些從數據庫的值代入到show_entries.html模板裏。sql

2.添加新條目shell

@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'))

同上,經過POST接收到title和text的內容並插入到數據庫裏,而後提交。數據庫

3.登陸flask

@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)

接收username,password 與config.py配置文件裏的用戶名和密碼進行判斷。後端

4.註銷session

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

flaskr.py 完整代碼app

#!/root/.pyenv/versions/app/bin/python
import sqlite3
from contextlib import closing
from flask import Flask, request, session, g, redirect, url_for, abort, render_template, flash

app = Flask(__name__)
app.config.from_object('config')


def init_db():
    with closing(connect_db()) as db:
        with app.open_resource('schema.sql') as f:
            db.cursor().executescript(f.read())
        db.commit()


def connect_db():
        return sqlite3.connect(app.config['DATABASE'])


@app.before_request
def before_request():
    g.db = connect_db()


@app.teardown_request
def teardown_request(exception):
    g.db.close()


@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)


@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'))


@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)


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

if __name__ == "__main__":
    app.run(host='0.0.0.0', port=80)

以上後端都寫完了,下一篇主要是建立一個小前端。

相關文章
相關標籤/搜索