1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
| import sqlite3, os from datetime import datetime
from flask import Flask from flask import render_template, request, redirect from flask import g
DATABASE = "guestbook.db"
app = Flask(__name__)
def get_db(): db = getattr(g, '_database', None) if db is None: db = g._database = sqlite3.connect(DATABASE) return db
@app.teardown_appcontext def close_connection(exception): db = getattr(g, '_database', None) if db is not None: db.close()
def init_db(): db = get_db() db.cursor().execute("""CREATE TABLE GUESTBOOK( USERNAME TEXT NOT NULL, COMMENT TEXT NOT NULL, CREATEAT TEXT NOT NULL); """) db.commit()
def load_data(): cur = get_db().execute("SELECT * from GUESTBOOK") rv = cur.fetchall() cur.close()
return rv
def save_data(name, comment, create_at): db = get_db() cur = db.cursor().execute( "INSERT INTO GUESTBOOK (USERNAME,COMMENT,CREATEAT) VALUES (?,?,?)", (name, comment, create_at)) cur.close() db.commit()
@app.route('/') def index():
if not os.path.exists(DATABASE): init_db()
greeting_list = load_data() return render_template('index.html', greeting_list=greeting_list)
@app.route('/post', methods=['POST']) def post(): name = request.form['name'] comment = request.form['comment'] create_at = datetime.now()
save_data(name, comment, create_at)
return redirect('/')
if __name__ == '__main__': app.run('127.0.0.1', port='5000', debug=True)
|