Flaskr小实例的创建过程

1.创建文件目录

项目目录.png

2.数据库模式

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

3.应用程序设置代码

import os
import sqlite3
from flask import Flask, request, session, g, redirect, url_for, abort, \
    render_template, flash
app = Flask(__name__) # create the application instance :)
app.config.from_object(__name__) # load config from this file , flaskr.py
# Load default config and override config from an environment variable
app.config.update(dict(
    DATABASE=os.path.join(app.root_path, 'flaskr.db'),
    SECRET_KEY='development key',
    USERNAME='admin',
    PASSWORD='default'
))
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

4.作为包安装

# setup.py
from setuptools import setup
setup(
    name='flaskr',
    packages=['flaskr'],
    include_package_data=True,
    install_requires=[
        'flask',
    ],
)
# MANIFEST.in
graft flaskr/templates
graft flaskr/static
include flaskr/schema.sql
# flaskr/__init__.py
from .flaskr import app

5.数据库连接

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

6.创建数据库


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

操作记录.png

7.view视图

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


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

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

8.模板

#layout.html
<!doctype html>
    <title>Flaskr</title>
    <link rel=stylesheet type=text/css href="{{ url_for('static', filename='style.css') }}">
    <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 %}{% endblock %}
</div>
# show_entries.html
{% extends "layout.html" %}
{% block body %}
    {% if session.logged_in %}
        <form action="{{ url_for('add_entry') }}" method=post class=add-entry>
            <dl>
                <dt>Title:
                <dd><input type=text size=30 name=title>
                <dt>Text:
                <dd><textarea name=text rows=5 cols=40></textarea>
                <dd><input type=submit value=Share>
            </dl>
        </form>
    {% endif %}
    <ul class=entries>
        {% for entry in entries %}
            <li><h2>{{ entry.title }}</h2>{{ entry.text|safe }}
        {% else %}
            <li><em>Unbelievable. No entries here so far</em>
        {% endfor %}
    </ul>
{% endblock %}
# login.html
{% extends "layout.html" %}
{% block body %}
    <h2>Login</h2>
    {% if error %}<p class=error><strong>Error:</strong> {{ error }}{% endif %}
    <form action="{{ url_for('login') }}" method=post>
        <dl>
            <dt>Username:
            <dd><input type=text name=username>
            <dt>Password:
            <dd><input type=password name=password>
            <dd><input type=submit value=Login>
        </dl>
    </form>
{% endblock %}

9.样式控制

# style.css
body { font-family: sans-serif; background: #eee; }
a, h1, h2 { color: #377ba8; }
h1, h2 { font-family: 'Georgia', serif; margin: 0; }
h1 { border-bottom: 2px solid #eee; }
h2 { font-size: 1.2em; }
.page { margin: 2em auto; width: 35em; border: 5px solid #ccc;
padding: 0.8em; background: white; }
.entries { list-style: none; margin: 0; padding: 0; }
.entries li { margin: 0.8em 1.2em; }
.entries li h2 { margin-left: -1em; }
.add-entry { font-size: 0.9em; border-bottom: 1px solid #ccc; }
.add-entry dl { font-weight: bold; }
.metanav { text-align: right; font-size: 0.8em; padding: 0.3em;
margin-bottom: 1em; background: #fafafa; }
.flash { background: #cee5F5; padding: 0.5em;
border: 1px solid #aacbe2; }
.error { background: #f0d6d6; padding: 0.5em; }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。