· 7 years ago · Nov 25, 2018, 05:48 AM
1#!/usr/bin/env python
2# -*- coding: utf-8 -*-
3
4from web import database
5from flask import Flask, render_template, abort, flash, redirect, url_for, request
6
7DATABASE = '/tmp/flaskr.db'
8SECRET_KEY = 'what'
9DEBUG = True
10
11app = Flask(__name__)
12app.config.from_object(__name__)
13
14conn = database(dbn='sqlite', db=DATABASE)
15
16@app.route('/')
17def index():
18 entries = conn.select('entries',
19 what='id, title, text',
20 limit=20,
21 order='id DESC')
22 return render_template('index.html', entries=entries)
23
24
25@app.route('/add', methods=['GET', 'POST'])
26def add():
27 if request.method == 'POST':
28 conn.insert('entries',
29 title=request.form['title'],
30 text=request.form['text'])
31 flash('a new entry')
32 return redirect(url_for('index'))
33 return render_template('add.html')
34
35
36@app.route('/entry/<int:entry_id>')
37def show_entry(entry_id):
38 entry = conn.select('entries',
39 what='id, title, text',
40 where='id = $id',
41 vars={'id': entry_id},
42 limit=1)
43 try:
44 return render_template('entry.html', entry=entry[0])
45 except IndexError:
46 return abort(404)
47
48
49def a():
50 q = """
51create table entries(
52id integer primary key autoincrement,
53title string not null,
54text string not null
55);
56"""
57
58if __name__ == '__main__':
59 app.run(debug=DEBUG)