要显示来自自定义帖子类别的所有帖子,通常需要以下几个步骤:
假设我们使用的是一个简单的SQL数据库,并且有一个名为posts
的表和一个名为categories
的表,它们通过外键关联。
CREATE TABLE categories (
id INT PRIMARY KEY,
name VARCHAR(255) NOT NULL
);
CREATE TABLE posts (
id INT PRIMARY KEY,
title VARCHAR(255) NOT NULL,
content TEXT,
category_id INT,
FOREIGN KEY (category_id) REFERENCES categories(id)
);
from flask import Flask, jsonify
import sqlite3
app = Flask(__name__)
def db_connection():
conn = None
try:
conn = sqlite3.connect('database.db')
except sqlite3.error as e:
print(e)
return conn
@app.route('/posts/<int:category_id>', methods=['GET'])
def get_posts_by_category(category_id):
conn = db_connection()
cursor = conn.cursor()
cursor.execute("SELECT * FROM posts WHERE category_id=?", (category_id,))
posts = cursor.fetchall()
conn.close()
return jsonify(posts)
if __name__ == '__main__':
app.run(debug=True)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Posts by Category</title>
</head>
<body>
<h1>Posts in Category</h1>
<div id="posts"></div>
<script>
async function fetchPosts(categoryId) {
const response = await fetch(`/posts/${categoryId}`);
const posts = await response.json();
const postsDiv = document.getElementById('posts');
postsDiv.innerHTML = '';
posts.forEach(post => {
const postElement = document.createElement('div');
postElement.innerHTML = `<h2>${post.title}</h2><p>${post.content}</p>`;
postsDiv.appendChild(postElement);
});
}
// Example usage: fetch posts for category with ID 1
fetchPosts(1);
</script>
</body>
</html>
通过上述步骤和代码示例,可以有效地从自定义帖子类别中检索并显示所有相关帖子。
领取专属 10元无门槛券
手把手带您无忧上云