|
| 1 | +""" |
| 2 | + Message Board |
| 3 | + ~~~~~~~~~~~~~ |
| 4 | +
|
| 5 | + A simple message board application written with Flask and sqlite3. |
| 6 | + Since it's a small application, I have not use SQLAlchemy and wtf. |
| 7 | +
|
| 8 | + :copyright: (c) 2015 by proteam@gmail.com. |
| 9 | + :license: BSD. |
| 10 | +""" |
| 11 | +import os |
| 12 | +import sqlite3 |
| 13 | +from datetime import datetime |
| 14 | +from flask import Flask, g, request, render_template, flash |
| 15 | + |
| 16 | +app = Flask(__name__) |
| 17 | + |
| 18 | +# configuration |
| 19 | +app.config.update(dict( |
| 20 | + DATABASE = os.path.join(app.root_path, 'db.sqlite3'), |
| 21 | + SECRET_KEY = 'secret key' |
| 22 | +)) |
| 23 | + |
| 24 | +app.config.from_object(__name__) |
| 25 | + |
| 26 | + |
| 27 | +def connect_db(): |
| 28 | + """Connectts to the specific database.""" |
| 29 | + return sqlite3.connect(app.config['DATABASE']) |
| 30 | + |
| 31 | + |
| 32 | +def get_db(): |
| 33 | + db = getattr(g, '_database', None) |
| 34 | + if db is None: |
| 35 | + db = g._database = connect_db() |
| 36 | + return db |
| 37 | + |
| 38 | + |
| 39 | +def init_db(): |
| 40 | + """Initalizes the database. |
| 41 | +
|
| 42 | + >>> from run import init_db |
| 43 | + >>> init_db() |
| 44 | + """ |
| 45 | + with app.app_context(): |
| 46 | + db = get_db() |
| 47 | + with app.open_resource('schema.sql', mode='r') as f: |
| 48 | + db.cursor().executescript(f.read()) |
| 49 | + db.commit() |
| 50 | + |
| 51 | + |
| 52 | +@app.before_request |
| 53 | +def before_request(): |
| 54 | + g.db = connect_db() |
| 55 | + |
| 56 | + |
| 57 | +@app.teardown_request |
| 58 | +def teardown_request(exception): |
| 59 | + db = getattr(g, 'db', None) |
| 60 | + if db is not None: |
| 61 | + db.close() |
| 62 | + g.db.close() |
| 63 | + |
| 64 | + |
| 65 | +@app.route('/', methods=['GET', 'POST']) |
| 66 | +def index(): |
| 67 | + if request.method == 'POST': |
| 68 | + username = request.form['username'] |
| 69 | + message = request.form['message'] |
| 70 | + time = datetime.now() |
| 71 | + if username and message: |
| 72 | + g.db.execute( |
| 73 | + 'insert into message_board (username, message, time) values (?, ?, ?)', |
| 74 | + [username, message, time] |
| 75 | + ) |
| 76 | + g.db.commit() |
| 77 | + flash('Your meassage was successfully posted.') |
| 78 | + else: |
| 79 | + flash('Username or message can not be blank.') |
| 80 | + cur = g.db.execute('select username, message, time \ |
| 81 | + from message_board order by time desc') |
| 82 | + posts = [dict(username=row[0], message=row[1], time=row[2]) \ |
| 83 | + for row in cur.fetchall()] |
| 84 | + return render_template('index.html', posts=posts) |
| 85 | + |
| 86 | + |
| 87 | +if __name__ == '__main__': |
| 88 | + import doctest |
| 89 | + doctest.testmod() |
| 90 | + app.run(debug=True) |
0 commit comments