引言
在互联网时代,博客是人们分享知识、记录生活的重要平台。借助 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 数据库的连接。
收起
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()
用户注册接口
收起
@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
用户登录接口
收起
@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
创建博客文章接口
收起
@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
获取所有博客文章接口
收起
@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 应用
收起
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 成功构建了一个简单的博客系统。该系统包含用户注册、登录、文章创建和文章列表展示等基本功能。在实际应用中,你可以进一步完善系统,例如添加文章编辑、删除功能,优化前端界面等。