1.数据库配置
#configuration
current_dir = os.getcwd()
DATABASE = current_dir + "\weibo.db"
DEBUG = True
SECRET_KEY = secret_key
USERNAME = 'admin'
PASSWORD = '010110'
2.部分内容的初始化加载
#create our little application
app = Flask(__name__)
app.config.from_object(__name__)
def init_db():
with closing(connect_db()) as db:
with app.open_resource('schema.sql', mode='r') 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):
db = getattr(g, 'db', None)
if db is not None:
db.close()
g.db.close()
3.路由定义
@app.route('/')
@app.route('/add', methods=['POST'])
4.视图函数
@app.route('/')
def show_entries():
cur = g.db.execute('select title, text from entries order by 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'))
====================================================================================
初次了解flask框架,如有不足请多多指教