基于 Flask 与 MySQL 构建简单的博客系统

news/2025/2/21 5:28:57

引言

在互联网时代,博客是人们分享知识、记录生活的重要平台。借助 Python 的 Flask 框架与 MySQL 数据库,我们可以快速搭建一个简单的博客系统。本文将详细介绍如何从零开始构建这样一个系统,涵盖环境搭建、数据库设计、后端接口实现以及前端页面展示等方面。

环境准备

安装依赖

首先,我们需要安装 Flask 和 MySQL 驱动。在命令行中运行以下命令:

收起

bash

pip install flask mysql-connector-python

数据库设置

假设你已经安装了 MySQL 数据库,创建一个名为 blog_db 的数据库,并在其中创建两个表:users 和 posts

收起

sql

-- 创建数据库
CREATE DATABASE blog_db;

-- 使用数据库
USE blog_db;

-- 创建用户表
CREATE TABLE users (
    id INT AUTO_INCREMENT PRIMARY KEY,
    username VARCHAR(50) NOT NULL UNIQUE,
    password VARCHAR(255) NOT NULL
);

-- 创建博客文章表
CREATE TABLE posts (
    id INT AUTO_INCREMENT PRIMARY KEY,
    title VARCHAR(200) NOT NULL,
    content TEXT NOT NULL,
    user_id INT NOT NULL,
    FOREIGN KEY (user_id) REFERENCES users(id)
);

后端实现(Flask)

数据库连接

创建一个 app.py 文件,首先实现与 MySQL 数据库的连接。

收起

python

import mysql.connector
from flask import Flask, request, jsonify

app = Flask(__name__)

# 数据库连接配置
db = mysql.connector.connect(
    host="localhost",
    user="your_username",
    password="your_password",
    database="blog_db"
)

cursor = db.cursor()

用户注册接口

收起

python

@app.route('/register', methods=['POST'])
def register():
    data = request.get_json()
    username = data.get('username')
    password = data.get('password')

    if not username or not password:
        return jsonify({"message": "用户名和密码不能为空"}), 400

    try:
        cursor.execute("INSERT INTO users (username, password) VALUES (%s, %s)", (username, password))
        db.commit()
        return jsonify({"message": "注册成功"}), 201
    except mysql.connector.IntegrityError:
        return jsonify({"message": "用户名已存在"}), 409

用户登录接口

收起

python

@app.route('/login', methods=['POST'])
def login():
    data = request.get_json()
    username = data.get('username')
    password = data.get('password')

    cursor.execute("SELECT id FROM users WHERE username = %s AND password = %s", (username, password))
    user = cursor.fetchone()

    if user:
        return jsonify({"message": "登录成功", "user_id": user[0]}), 200
    else:
        return jsonify({"message": "用户名或密码错误"}), 401

创建博客文章接口

收起

python

@app.route('/posts', methods=['POST'])
def create_post():
    data = request.get_json()
    title = data.get('title')
    content = data.get('content')
    user_id = data.get('user_id')

    if not title or not content or not user_id:
        return jsonify({"message": "标题、内容和用户 ID 不能为空"}), 400

    try:
        cursor.execute("INSERT INTO posts (title, content, user_id) VALUES (%s, %s, %s)", (title, content, user_id))
        db.commit()
        return jsonify({"message": "文章创建成功"}), 201
    except Exception as e:
        return jsonify({"message": f"创建文章失败: {str(e)}"}), 500

获取所有博客文章接口

收起

python

@app.route('/posts', methods=['GET'])
def get_all_posts():
    cursor.execute("SELECT posts.id, posts.title, posts.content, users.username FROM posts JOIN users ON posts.user_id = users.id")
    posts = cursor.fetchall()

    post_list = []
    for post in posts:
        post_dict = {
            "id": post[0],
            "title": post[1],
            "content": post[2],
            "author": post[3]
        }
        post_list.append(post_dict)

    return jsonify(post_list), 200

运行 Flask 应用

收起

python

if __name__ == '__main__':
    app.run(debug=True)

前端实现(简单示例)

创建一个 index.html 文件,使用 HTML、CSS 和 JavaScript 实现一个简单的前端界面,与后端接口进行交互。

收起

html

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>简单博客系统</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 20px;
        }

        form {
            margin-bottom: 20px;
        }

        input,
        textarea {
            display: block;
            margin-bottom: 10px;
            width: 300px;
        }
    </style>
</head>

<body>
    <h1>注册</h1>
    <form id="registerForm">
        <input type="text" id="registerUsername" placeholder="用户名">
        <input type="password" id="registerPassword" placeholder="密码">
        <button type="submit">注册</button>
    </form>

    <h1>登录</h1>
    <form id="loginForm">
        <input type="text" id="loginUsername" placeholder="用户名">
        <input type="password" id="loginPassword" placeholder="密码">
        <button type="submit">登录</button>
    </form>

    <h1>创建文章</h1>
    <form id="createPostForm">
        <input type="text" id="postTitle" placeholder="文章标题">
        <textarea id="postContent" placeholder="文章内容"></textarea>
        <input type="hidden" id="userId">
        <button type="submit">发布文章</button>
    </form>

    <h1>文章列表</h1>
    <div id="postList"></div>

    <script>
        // 注册功能
        document.getElementById('registerForm').addEventListener('submit', function (e) {
            e.preventDefault();
            const username = document.getElementById('registerUsername').value;
            const password = document.getElementById('registerPassword').value;

            fetch('/register', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ username, password })
            })
              .then(response => response.json())
              .then(data => alert(data.message));
        });

        // 登录功能
        document.getElementById('loginForm').addEventListener('submit', function (e) {
            e.preventDefault();
            const username = document.getElementById('loginUsername').value;
            const password = document.getElementById('loginPassword').value;

            fetch('/login', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ username, password })
            })
              .then(response => response.json())
              .then(data => {
                    if (data.message === '登录成功') {
                        document.getElementById('userId').value = data.user_id;
                    }
                    alert(data.message);
                });
        });

        // 创建文章功能
        document.getElementById('createPostForm').addEventListener('submit', function (e) {
            e.preventDefault();
            const title = document.getElementById('postTitle').value;
            const content = document.getElementById('postContent').value;
            const userId = document.getElementById('userId').value;

            fetch('/posts', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ title, content, user_id: userId })
            })
              .then(response => response.json())
              .then(data => alert(data.message));
        });

        // 获取文章列表功能
        function getPosts() {
            fetch('/posts')
              .then(response => response.json())
              .then(posts => {
                    const postList = document.getElementById('postList');
                    postList.innerHTML = '';
                    posts.forEach(post => {
                        const postDiv = document.createElement('div');
                        postDiv.innerHTML = `<h2>${post.title}</h2><p>作者: ${post.author}</p><p>${post.content}</p>`;
                        postList.appendChild(postDiv);
                    });
                });
        }

        getPosts();
    </script>
</body>

</html>

总结

通过上述步骤,我们基于 Flask 和 MySQL 成功构建了一个简单的博客系统。该系统包含用户注册、登录、文章创建和文章列表展示等基本功能。在实际应用中,你可以进一步完善系统,例如添加文章编辑、删除功能,优化前端界面等。


http://www.niftyadmin.cn/n/5860221.html

相关文章

.NET8入门:13.ASP.NET Core MVC

ASP.NET Core MVC是一种十分经典的软件设计模式架构&#xff0c;接下来我们来了解一下MVC在ASP.NET8中的一些基础概念。 MVC架构 MVC架构主要包含以下三层&#xff1a; M&#xff08;Model&#xff09;&#xff1a;模型层&#xff0c;其职责为UI显示以及业务逻辑或操作所需要…

Debezium 报错:“The db history topic is missing” 的处理方法

Debezium 报错:“The db history topic is missing” 的处理方法 一、引言 在使用 Debezium 进行数据同步时,可能会遇到一个常见的错误:“The db history topic is missing”。这个错误表明 Debezium 无法找到或访问其数据库历史记录主题(db history topic),这通常是由…

[特殊字符]边缘计算课程资料整理|从零到实战全攻略[特殊字符]

文末联系&#xff0c;获取整套视频教程资料和课件资料 &#x1f4da;边缘计算课程资料整理&#xff5c;从零到实战全攻略&#x1f680; &#x1f4a1;「基础入门篇」打牢根基 1️⃣ 第1章&#xff1a;边缘计算就在身边&#x1f50d; &#x1f449;&#x1f3fb; 消费电子/智慧…

第3章 3.3日志 .NET Core日志 NLog使用教程

3.3.1 .NET Core日志基本使用 书中介绍了把日志输出到控制台的使用方式&#xff1a; 安装 Microsoft.Extensions.Logging 和 Microsoft.Extensions.Logging.Console 日志记录代码&#xff1a; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.…

数仓搭建(hive):DM搭建(数据集市层)

DM层 数据集市层 &#xff08;Data Mart&#xff09; 粒度上卷&#xff08;Roll-up&#xff09;: 指的是沿着维度层次向上聚合汇总数据&#xff0c;从细粒度到粗粒度观察数据的操作。 示例 数仓的上一层DWS的是按日汇总 DM层基于DWS层主题日宽表上卷统计出按年,月,周的数…

简识MQ之Kafka、ActiveMQ、RabbitMQ、RocketMQ传递机制

四种主流消息队列&#xff08;Kafka、ActiveMQ、RabbitMQ、RocketMQ&#xff09;的生产者与消费者传递信息的机制说明&#xff0c;以及实际使用中的注意事项和示例&#xff1a; 1. Apache Kafka 传递机制 模型&#xff1a;基于 发布-订阅模型&#xff0c;生产者向 主题&#…

AI IDE 使用体验及 AI 感受

近期感觉身边所有的人或事&#xff0c;全部都陷入到了 AI 焦虑中&#xff0c;从去年一年的 AI 猎奇&#xff0c;变成了 AI 好牛&#xff0c;但是与我有关吗&#xff1f;不行&#xff0c;必须强行与我有关的节奏&#xff0c;时代的发展正倒逼着我们去改变自己的工作范式&#xf…

DeepSeek私有化专家 | 云轴科技ZStack入选IDC中国生成式AI市场概览

DeepSeek 火爆全球AI生态圈&#xff0c;并引发企业用户大量私有化部署需求。 国际数据公司IDC近日发文《DeepSeek爆火的背后&#xff0c;大模型/生成式AI市场生态潜在影响引人关注》&#xff0c;认为中国市场DeepSeekAI模型的推出在大模型/生成式AI市场上引起了轰动&#xff0c…