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

引言

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

环境准备

安装依赖

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

收起

bash

pip install flask mysql-connector-python

数据库设置

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

收起

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 成功构建了一个简单的博客系统。该系统包含用户注册、登录、文章创建和文章列表展示等基本功能。在实际应用中,你可以进一步完善系统,例如添加文章编辑、删除功能,优化前端界面等。

相关推荐
Ciderw6 分钟前
MySQL日志undo log、redo log和binlog详解
数据库·c++·redis·后端·mysql·面试·golang
~Yogi28 分钟前
新版Tomcat MySQL IDEA 安装配置过程遇到的问题
mysql·tomcat·intellij-idea
明月清风徐徐1 小时前
Miniconda + VSCode 的Python环境搭建
ide·vscode·python
隔壁老王1561 小时前
tidb实时同步到mysql
数据库·mysql·tidb
笨鸟笃行1 小时前
爬虫第七篇数据爬取及解析
开发语言·爬虫·python
java1234_小锋1 小时前
一周学会Flask3 Python Web开发-response响应格式
开发语言·python·flask·flask3
大数据追光猿1 小时前
Python中的Flask深入认知&搭建前端页面?
前端·css·python·前端框架·flask·html5
java1234_小锋1 小时前
一周学会Flask3 Python Web开发-flask3模块化blueprint配置
开发语言·python·flask·flask3
莫忘初心丶1 小时前
python flask 使用教程 快速搭建一个 Web 应用
前端·python·flask
听封1 小时前
✨ 索引有哪些缺点以及具体有哪些索引类型
数据库·mysql