Натройте базу данных. Настройте отображение постов бллога.

This commit is contained in:
igor 2026-01-27 09:26:01 +00:00
parent 9142a02425
commit 315f926700
6 changed files with 67 additions and 1 deletions

26
app.py
View File

@ -1,8 +1,32 @@
import sqlite3
from flask import Flask, render_template 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 = Flask(__name__)
@app.route('/') @app.route('/')
def index(): 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)

BIN
database.db Normal file

Binary file not shown.

20
init_db.py Normal file
View File

@ -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()

8
schema.sql Normal file
View File

@ -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
);

View File

@ -2,5 +2,12 @@
{% block content %} {% block content %}
<h1>{% block title %} Welcome to FlaskBlog {% endblock %}</h1> <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 %} {% endblock %}

7
templates/post.html Normal file
View File

@ -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 %}