内容管理系统(CMS)是一种让非技术用户能够轻松创建、编辑、管理内容的应用程序。Flask 是一个轻量级的 Web 应用框架,非常适合用于构建快速且灵活的 Web 应用。在本篇文章中,我们将从零开始,使用 Flask 框架来创建一个简单的 CMS。
准备工作
在开始之前,请确保你已经安装了 Python 和 Flask。你可以通过以下命令来安装 Flask:
pip install flask
步骤 1:创建项目结构
首先,创建一个新的目录来存放你的项目文件。在这个目录中,我们将创建以下文件和文件夹:
my_cms/
|-- app.py
|-- templates/
| |-- base.html
| |-- index.html
| |-- edit.html
|-- static/
| |-- css/
| |-- js/
步骤 2:编写 Flask 应用
在 app.py 文件中,我们将编写 Flask 应用的基本代码:
from flask import Flask, render_template, request, redirect, url_for
app = Flask(__name__)
# 存储文章列表
articles = [
{'title': 'Hello World', 'content': 'This is a sample article.'},
{'title': 'Welcome to My CMS', 'content': 'Welcome to your new content management system.'}
]
@app.route('/')
def index():
return render_template('index.html', articles=articles)
@app.route('/edit/<int:article_id>', methods=['GET', 'POST'])
def edit(article_id):
if request.method == 'POST':
# 更新文章
articles[article_id]['title'] = request.form['title']
articles[article_id]['content'] = request.form['content']
return redirect(url_for('index'))
return render_template('edit.html', article_id=article_id)
if __name__ == '__main__':
app.run(debug=True)
步骤 3:创建模板
在 templates 文件夹中,我们将创建以下模板文件:
base.html:这是所有页面的基础模板。index.html:显示文章列表的页面。edit.html:编辑文章内容的页面。
以下是一个简单的 base.html 示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>{{ title }}</title>
<link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}">
</head>
<body>
<header>
<h1>{{ title }}</h1>
</header>
<main>
{% block content %}
{% endblock %}
</main>
<footer>
<p>Content Management System</p>
</footer>
</body>
</html>
接下来,创建 index.html 和 edit.html 模板:
<!-- index.html -->
{% extends "base.html" %}
{% block content %}
<h2>Articles</h2>
<ul>
{% for article in articles %}
<li>
<h3>{{ article.title }}</h3>
<p>{{ article.content }}</p>
<a href="{{ url_for('edit', article_id=loop.index0) }}">Edit</a>
</li>
{% endfor %}
</ul>
{% endblock %}
<!-- edit.html -->
{% extends "base.html" %}
{% block content %}
<h2>Edit Article</h2>
<form method="post">
<label for="title">Title:</label>
<input type="text" id="title" name="title" value="{{ article.title }}">
<br>
<label for="content">Content:</label>
<textarea id="content" name="content">{{ article.content }}</textarea>
<br>
<input type="submit" value="Save">
</form>
{% endblock %}
步骤 4:运行应用
现在,你已经完成了基本的 CMS 应用。运行 app.py 文件,然后打开浏览器访问 http://127.0.0.1:5000/。你应该能看到文章列表和编辑链接。
通过这个简单的例子,你已经掌握了使用 Flask 框架创建内容管理系统的基础。你可以根据自己的需求扩展这个应用,添加更多的功能,如用户认证、文章分类等。祝你好运!
