Натройте базу данных. Настройте отображение постов бллога.
This commit is contained in:
parent
9142a02425
commit
315f926700
26
app.py
26
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('/<int:post_id>')
|
||||
def post(post_id):
|
||||
post = get_post(post_id)
|
||||
return render_template('post.html', post=post)
|
||||
|
||||
|
|
|
|||
Binary file not shown.
|
|
@ -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()
|
||||
|
|
@ -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
|
||||
);
|
||||
|
|
@ -2,5 +2,12 @@
|
|||
|
||||
{% block content %}
|
||||
<h1>{% block title %} Welcome to FlaskBlog {% endblock %}</h1>
|
||||
{% for post in posts %}
|
||||
<a href="{{ url_for('post', post_id=post['id']) }}">
|
||||
<h2>{{ post['title'] }}</h2>
|
||||
</a>
|
||||
<span class="badge text-bg-primary">{{ post['created'] }}</span>
|
||||
<hr>
|
||||
{% endfor %}
|
||||
{% endblock %}
|
||||
|
||||
|
|
|
|||
|
|
@ -0,0 +1,7 @@
|
|||
{% extends 'base.html' %}
|
||||
|
||||
{% block content %}
|
||||
<h2>{% block title %} {{ post['title'] }} {% endblock %}</h2>
|
||||
<p>{{ post['content'] }}</p>
|
||||
<span class="badge text-bg-primary">{{ post['created'] }}</span>
|
||||
{% endblock %}
|
||||
Loading…
Reference in New Issue