#flask学习笔记-09:留言板(二)

Step 5: 视图函数

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执行过程就是这个样子,前面加载模块就不写了,基本就是这么一个过程。

>>> 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模板里。

2.添加新条目

@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.登录

@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.注销

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

flaskr.py 完整代码

#!/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)

以上后端都写完了,下一篇主要是创建一个小前端。

你可能感兴趣的:(学习笔记)