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

news/2025/2/21 6:01:23/

引言

在互联网时代,博客是人们分享知识、记录生活的重要平台。借助 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, jsonifyapp = 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": "用户名和密码不能为空"}), 400try:cursor.execute("INSERT INTO users (username, password) VALUES (%s, %s)", (username, password))db.commit()return jsonify({"message": "注册成功"}), 201except 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]}), 200else: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 不能为空"}), 400try:cursor.execute("INSERT INTO posts (title, content, user_id) VALUES (%s, %s, %s)", (title, content, user_id))db.commit()return jsonify({"message": "文章创建成功"}), 201except 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.ppmy.cn/news/1573813.html

相关文章

前端web安全

一、黑盒扫描和白盒扫描 白盒扫描和黑盒扫描都是针对网络安全和应用程序安全的常用测试方法。 1、白盒扫描指的是测试人员具有关于系统内部结构和代码的全部或部分信息&#xff0c;是基于源代码的安全检测方法&#xff0c;它可以对源代码进行深度分析&#xff0c;从而发现潜在…

python解析url参数

python解析url参数 方法一&#xff1a;使用urllib.parse库中的parse_qs函数方法二&#xff1a;使用urllib.parse库中的parse_qsl函数方法三&#xff1a;使用urllib.parse库中的urlsplit函数和parse_qs函数 在Python中&#xff0c;可以使用urllib.parse库来解析URL参数 方法一&a…

罗格科技发布全球首款税务智能合规终端“罗拉DeepTax双引擎AI一体机”

——开启企业级税务智能管理新时代&#xff0c;迈入零部署、AI与场景深度融合新范式 罗格科技于2025年2月18日正式推出全球首款深度集成税务合规与强推理能力的“罗拉DeepTax双引擎AI一体机&#xff08;LoLR DeepTax Dual Engine AI Appliance&#xff09;”。该产品通过融合自…

《动手学机器人学》笔记

目录 0.介绍1.概述&#xff5c;空间位置、姿态的描述&#xff08;33&#xff09;&#xff5c;《动手学机器人学》2.&#xff08;2&#xff09;-Robotics Toolbox①&#xff08;V10.4&#xff09;3.齐次坐标与变换矩阵4.一般形式的旋转变换矩阵5.&#xff08;轴角法&#xff09;…

Jenkins上无法查看已成功生成的Junit报告

如果你已确认 JUnit 报告在工作空间中被成功生成&#xff0c;但在 Jenkins 构建页面上却看不到 "Test Result" 或 "Test Report" 的链接&#xff0c;这通常意味着 Jenkins 没有正确地配置用来处理和显示这些报告的步骤。这里有几个可能的原因和解决方法&am…

【异步编程解析】

文章目录 FutureTask分析FutureTask介绍FutureTask应用FutureTask源码分析 CompletableFutureCompletableFuture介绍场景应用源码分析 FutureTask分析 FutureTask介绍 FutureTask 是 Java 并发包 (java.util.concurrent) 中的一个 可取消的异步计算任务&#xff0c;它实现了 …

在高流量下保持WordPress网站的稳定和高效运行

随着流量的不断增加&#xff0c;网站的稳定和高效运行变得越来越重要&#xff0c;特别是使用WordPress搭建的网站。流量过高时&#xff0c;网站加载可能会变慢&#xff0c;甚至崩溃&#xff0c;直接影响用户体验和网站正常运营。因此&#xff0c;我们需要采取一些有效的措施&am…

华为固态电池引发的思索

华为固态电池真牛&#xff01; 超长续航&#xff1a;单次充电即可行驶3000公里 极速充电&#xff1a;五分钟内充满80% 极致安全&#xff1a;不可燃、不漏液 长寿命设计&#xff1a;循环寿命达10000次以上 如上是华为电池展示的优势项&#xff0c;每一条都让我们心动不已。…