diff --git a/app.py b/app.py index 0a6c573..3032501 100644 --- a/app.py +++ b/app.py @@ -1,8 +1,32 @@ +import sqlite3 from flask import Flask, render_template +from werkzeug.exceptions import abort + +def get_db_connection(): + conn = sqlite3.connect('database.db') + conn.row_factory = sqlite3.Row + return conn + +def get_post(post_id): + conn = get_db_connection() + post = conn.execute('SELECT * FROM posts WHERE id = ?', + (post_id,)).fetchone() + conn.close() + if post is None: + abort(404) + return post app = Flask(__name__) @app.route('/') def index(): - return render_template('index.html') + conn = get_db_connection() + posts = conn.execute('SELECT * FROM posts').fetchall() + conn.close() + return render_template('index.html', posts=posts) + +@app.route('/') +def post(post_id): + post = get_post(post_id) + return render_template('post.html', post=post) diff --git a/database.db b/database.db new file mode 100644 index 0000000..622742a Binary files /dev/null and b/database.db differ diff --git a/init_db.py b/init_db.py new file mode 100644 index 0000000..b2afd00 --- /dev/null +++ b/init_db.py @@ -0,0 +1,20 @@ +import sqlite3 + +connection = sqlite3.connect('database.db') + + +with open('schema.sql') as f: + connection.executescript(f.read()) + +cur = connection.cursor() + +cur.execute("INSERT INTO posts (title, content) VALUES (?, ?)", + ('First Post', 'Content for the first post') + ) + +cur.execute("INSERT INTO posts (title, content) VALUES (?, ?)", + ('Second Post', 'Content for the second post') + ) + +connection.commit() +connection.close() diff --git a/schema.sql b/schema.sql new file mode 100644 index 0000000..1f1ce54 --- /dev/null +++ b/schema.sql @@ -0,0 +1,8 @@ +DROP TABLE IF EXISTS posts; + +CREATE TABLE posts ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + created TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + title TEXT NOT NULL, + content TEXT NOT NULL +); diff --git a/templates/index.html b/templates/index.html index 8553659..08769cf 100644 --- a/templates/index.html +++ b/templates/index.html @@ -2,5 +2,12 @@ {% block content %}

{% block title %} Welcome to FlaskBlog {% endblock %}

+ {% for post in posts %} + +

{{ post['title'] }}

+
+ {{ post['created'] }} +
+ {% endfor %} {% endblock %} diff --git a/templates/post.html b/templates/post.html new file mode 100644 index 0000000..fea2712 --- /dev/null +++ b/templates/post.html @@ -0,0 +1,7 @@ +{% extends 'base.html' %} + +{% block content %} +

{% block title %} {{ post['title'] }} {% endblock %}

+

{{ post['content'] }}

+ {{ post['created'] }} +{% endblock %}