flaskr小应用的搭建

今天学习flask,文档中有一个flaskr的小应用,学习实现。
首先,按以下格式创建目录

/flaskr
    /static
    /templates

在flaskr文件夹下放入命名为schema.sql的数据库文件,内容如下,

drop table if exists entries;
create table entries (
  id integer primary key autoincrement,
  title string not null,
  text string not null
);

在flaskr文件夹下,编辑flaskr.py,内容如下,

# all the imports
import sqlite3
from flask import Flask, request, session, g, redirect, url_for, \
     abort, render_template, flash

# configuration
DATABASE = '/tmp/flaskr.db'
DEBUG = True
SECRET_KEY = 'development key'
USERNAME = 'admin'
PASSWORD = 'default'

并初始化,

# create our little application :)
app = Flask(__name__)
app.config.from_object(__name__)
app.config.from_envvar('FLASKR_SETTINGS', silent=True)

接下来,就可以写一些功能模块了,连接数据库,

def connect_db():
    """Connects to the specific database."""
    rv = sqlite3.connect(app.config['DATABASE'])
    rv.row_factory = sqlite3.Row
    return rv

def get_db():
    if not hasattr(g,'sqlite_db'):
        g.sqlite_db = connect_db()
    return g.sqlite_db

def close_db(error):
    if hasattr(g,'sqlite_db'):
        g.sqlite_db.close()


def init_db():
    with app.app_context():
        db = get_db()
        with app.open_resource('schema.sql',mode='r') as f:
            db.cursor().executescript(f.read())
        db.commit()

然后,运行开启服务器,

if __name__ == '__main__':
    app.run()

接下来,就可以对连接的数据库进行数据的操作了,
查看数据,

@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',method=['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'))

以上,功能模块就写好了 。

接下来,需要实现模板模块
先在template目录中新建,layout.html,写入

<!doctype html>
<title>Flaskr</title>
<link rel=stylesheet type=text/css  href="{{url_for('static',filename='style.ccc')}}">
<div class=page>
    <h1>Flaskr</h1>
    <div class=metanav>
        {% if not session.logged_in %}
        <a href = "{{url_for(login)}}">log in</a>
        {% else %}
        <a href = "{{url_for('logout')}}">log out</a>
        {% endif %}
    </div>
    {% for message in get_flashed_messages() %}
    <div class=flash>{{message}}</div>
    {% endfor %}
    {% block body %}{% endlock %}
</div>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值