在pycharm中做个增删查改的网页系统出来,手动模拟一些数据出来进行可视化图表展示的代码
时间: 2025-07-05 12:00:03 浏览: 3
### 创建具有CRUD功能的Web应用程序
为了在PyCharm中创建一个具备增删查改(CRUD)功能的Web应用,并实现数据可视化,可以采用Flask作为Web框架[^1]。此过程涉及多个方面的工作,包括但不限于设置项目环境、定义模型类、配置数据库连接以及编写视图函数来处理HTTP请求。
#### 安装必要的库
首先,在命令行工具里输入如下指令安装所需的Python包:
```bash
pip install flask sqlalchemy pandas matplotlib seaborn
```
这些软件包分别用于构建Web服务器、管理关系型数据库中的对象映射、读取CSV文件和其他表格形式的数据源,还有绘制图表以支持数据分析工作流。
#### 初始化 Flask 应用程序
下面是一个简单的例子展示怎样初始化一个新的Flask app实例:
```python
from flask import Flask, render_template, request, redirect, url_for
app = Flask(__name__)
```
这段代码片段展示了如何导入`flask`模块并创建了一个名为`app`的新Flask web server实例。
#### 配置SQLAlchemy ORM 和 MySQL 数据库链接
接着要做的就是通过SQLAlchemy ORM (Object Relational Mapper) 来简化对MySQL的操作。这里假设已经有一个运行着的服务端口为3306且用户名/密码均为root@localhost 的本地MySQL服务正在等待连接。
```python
import os
basedir = os.path.abspath(os.path.dirname(__file__))
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:password@localhost/mydatabase'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
```
上述脚本设置了指向特定位置下的SQLite数据库路径;对于生产环境中更推荐使用像PostgreSQL 或者 MySQL这样的外部DBMS替代默认内嵌式的sqlite引擎[^2]。
#### 设计表单对应的Model 类
现在让我们继续定义一些代表我们想要存储的信息类型的类——即所谓的“models”。例如,如果目标是建立博客平台,则可能需要考虑Article model 如下所示:
```python
class Article(db.Model):
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(80), nullable=False)
content = db.Column(db.Text(), nullable=False)
def __repr__(self):
return f'<Article "{self.title}">'
```
此处定义了一张article 表格及其字段属性,其中id 是主键而title 和content 则分别是标题和正文内容列名。
#### 实现 CRUD 操作接口
接下来的部分会介绍具体的方法去完成基本记录级别的操作:Create(新增)、Read (查询)、Update(更新) 及 Delete(删除)。以下是几个简单示例说明了每种情况应该怎么做:
##### 新建文章
当用户提交新帖子时触发该方法保存至数据库中:
```python
@app.route('/add', methods=['POST'])
def add_article():
article = Article(title=request.form.get('title'), content=request.form.get('content'))
try:
db.session.add(article)
db.session.commit()
flash('New entry was successfully posted')
except Exception as e:
db.session.rollback()
raise e
finally:
db.session.close()
return redirect(url_for('index'))
```
##### 显示所有文章列表
每当访问主页的时候都会调用这个路由获取全部的文章条目显示给前端页面看:
```python
@app.route('/')
def index():
articles = Article.query.all()
return render_template('index.html', articles=articles)
```
##### 更新指定ID的文章详情页
编辑某篇文章后点击保存按钮就会执行这里的逻辑修改对应记录里的值:
```python
@app.route("/update/<int:id>",methods=["GET","POST"])
def update(id):
article = Article.query.filter_by(id=id).first_or_404()
if request.method == "POST":
form_title = request.form["title"]
form_content = request.form["content"]
article.title=form_title
article.content=form_content
try:
db.session.merge(article)
db.session.commit()
except IntegrityError:
db.session.rollback()
return redirect("/")
return render_template("edit.html", article=article)
```
##### 删除选定的文章项
最后一种情形是在确认无误之后彻底移除不再需要的内容单元:
```python
@app.route("/delete/<int:id>")
def delete(id):
article_to_delete = Article.query.get_or_404(id)
try:
db.session.delete(article_to_delete )
db.session.commit()
except :
db.session.rollback()
return redirect("/")
```
以上四个部分共同构成了完整的RESTful API风格API设计模式的一部分。
#### 添加数据可视化组件
为了让网站更加生动有趣还可以加入统计图形或报表等功能增强用户体验感。比如利用matplotlib/seaborn等第三方绘图库生成柱状图、折线图等形式直观呈现各类指标变化趋势。
```python
import matplotlib.pyplot as plt
import numpy as np
import io
import base64
@app.route('/plot.png')
def plot_png():
fig = create_figure()
output = io.BytesIO()
FigureCanvas(fig).print_png(output)
response = make_response(output.getvalue())
response.mimetype = 'image/png'
return response
def create_figure():
fig, ax = plt.subplots(figsize=(7, 5))
xs = range(len(Article.query.all()))
ys = [len(x.content.split()) for x in Article.query.all()]
ax.bar(xs, ys)
return fig
```
在这个案例里面create_figure 函数负责计算每个文档长度并将它们画成直方图样式返回给浏览器渲染出来。
阅读全文
相关推荐

















