我的第七个项目:做一个web版记事本
点击上方蓝色字体,关注程序员zhenguo
之前项目:
项目环境
Python版本是3.7.2
主要基于
flask
开发这个web版记事本,ORM框架选择flask_sqlalchemy
,from flask import Flask, render_template, url_for, request, redirect
from flask_sqlalchemy import SQLAlchemy
基于
sqlite
的数据库文末和源码一起提供下载,无需安装。项目功能
直接启动
app.py
,然后就能看到下面的web界面:基本功能支持添加记事任务,更新和删除记事任务,并且全部硬存到sqlite数据库中,下次启动直接加载已有记录。
实现框架
两个
html
页面,模板引擎使用jinja
,一个css
文件;flask
后端;sqlite
数据库。文件目录结构,如下所示:
核心代码
核心代码主要包括
app.py
,index.html
两个文件。配置
app.py
模块,通过下面配置,建连了sqlite数据库和flask
后端。app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///notes.db"
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
db = SQLAlchemy(app)
业务实体类Todo
Todo
类继承了db.Model
:classTodo(db.Model):
id = db.Column(db.Integer, primary_key=True)
content = db.Column(db.String(200), nullable=False)
completed = db.Column(db.Integer, default=0)
pub_date = db.Column(db.DateTime, nullable=False, default=datetime.now())
以此与sqlite数据库的表
todo
建立映射,其中todo
表的字段和记录,如下所示:首页加载
首页加载路由对应的处理函数,如下所示:
@app.route("/", methods=["POST", "GET"])
defindex():
if request.method == "POST":
# 处理添加任务
task_content = request.form["task"]
if task_content == '':
return redirect("/")
new_task = Todo(content=task_content)
try:
db.session.add(new_task)
db.session.commit()
return redirect("/")
except:
return"加载首页有问题"
else:
tasks = Todo.query.order_by(Todo.pub_date).all()
return render_template("index.html", tasks=tasks)
首页加载请求时,
method
等于GET
,走到else
,根据pub_date
排序记录,并渲染到html
页面中。当页面加载出来后,输入任务描述,并点击
添加任务
时,也会路由到上面index
函数,只不过method
等于POST
:对应
index.html
页面中表单method="post"
,如下第一行所示:
<form action="" method="post">
<div class="form-group">
{% iftask_updated %}
<inputtype="text" name="task" id="task" value="{{ task_updated.content }}" class="form-control-sm">
<inputtype="submit" value="更新任务" class="btnbtn-info">
{% else %}
<inputtype="text" name="task" id="task" placeholder="添加任务描述,不能为空">
<inputtype="submit" value="添加任务" class="btnbtn-primary" class="form-control-sm">
{% endif %}
</div>
</form>
增删记录
增删记录的路由分别为:
/delete/<int:id>
/update/<int:id>
响应路由的函数在此不再展开,大家想要完整代码的去下载。
项目测试
截止2021年1月19日,测试未发现bug。
完整代码下载
上面完整py代码文件,可以在我的公众号后台回复:c,之前的所有项目代码也都在这个文件夹里:
不用打赏,点个赞或在看
就心满意足了
阅读原文 最新评论
推荐文章
作者最新文章
你可能感兴趣的文章
Copyright Disclaimer: The copyright of contents (including texts, images, videos and audios) posted above belong to the User who shared or the third-party website which the User shared from. If you found your copyright have been infringed, please send a DMCA takedown notice to [email protected]. For more detail of the source, please click on the button "Read Original Post" below. For other communications, please send to [email protected].
版权声明:以上内容为用户推荐收藏至CareerEngine平台,其内容(含文字、图片、视频、音频等)及知识版权均属用户或用户转发自的第三方网站,如涉嫌侵权,请通知[email protected]进行信息删除。如需查看信息来源,请点击“查看原文”。如需洽谈其它事宜,请联系[email protected]。
版权声明:以上内容为用户推荐收藏至CareerEngine平台,其内容(含文字、图片、视频、音频等)及知识版权均属用户或用户转发自的第三方网站,如涉嫌侵权,请通知[email protected]进行信息删除。如需查看信息来源,请点击“查看原文”。如需洽谈其它事宜,请联系[email protected]。