Python:masonite初体验TodoList
发布日期:2021-07-01 06:08:14
浏览次数:3
分类:技术文章
本文共 5190 字,大约阅读时间需要 17 分钟。
文档:
初次体验框架,感觉里边提供了丰富的命令行工具可以快速开发,
主要是ORM很棒,区别于Python生态Django等的ORM,和PHP的laravel很像,简单高效一、环境配置
环境
Python 3.4+masonite 2.2.26masonite-cli 2.2.2
安装
$ pip install masonite-cli$ craft # 查看帮助
二、新建一个项目
# 1、新建项目craft new project_namecd project_name# 2、安装依赖craft install # 3、启动服务craft serve
访问:
出现欢迎界面三、示例1:Hello World
1、创建控制器
$ craft controller Index
app/http/controllers/IndexController.py
"""A IndexController Module."""from masonite.request import Requestfrom masonite.view import Viewfrom masonite.controllers import Controllerclass IndexController(Controller): """IndexController Controller Class.""" def __init__(self, request: Request): """IndexController Initializer Arguments: request {masonite.request.Request} -- The Masonite Request class. """ self.request = request def show(self, view: View): return "Hello world"
2、配置路由
routes/web.py
"""Web Routes."""from masonite.routes import Get, PostROUTES = [ Get('/', 'IndexController@show'),]
masonite默认会自动重启服务
再次访问 http://127.0.0.1:8000/显示:Hello world
示例2:新建TODOLIST项目
1、配置数据库,使用sqlite
.env
DB_CONNECTION=sqliteDB_HOST=127.0.0.1DB_PORT=3306DB_DATABASE=data.dbDB_USERNAME=rootDB_PASSWORD=rootDB_LOG=True
2、创建迁移文件
$ craft migration create_todolist_table --create todolist
设置3个字段:id,title,complete_time
databases/migrations/create_todolist_table.pyfrom orator.migrations import Migrationclass CreateTodolistTable(Migration): def up(self): """ Run the migrations. """ with self.schema.create('todolist') as table: table.increments('id') table.string('title') table.datetime('complete_time').nullable() # 可以为null table.timestamps() def down(self): """ Revert the migrations. """ self.schema.drop('todolist')
迁移数据, 建表
$ craft migrate
查看建表语句
CREATE TABLE "todolist" ( "id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, "title" VARCHAR NOT NULL, "complete_time" DATETIME NULL, "created_at" DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL, "updated_at" DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL);
可以看到默认多加了2个字段:created_at,updated_at
3、创建Model
$ craft model TodoList
稍作修改
app/TodoList.py"""TodoList Model."""from config.database import Modelclass TodoList(Model): """TodoList Model.""" # 查询数据库的时候会在类名后加s,所以自定义表名 __table__ = "todolist" # 要写入的字段 __fillable__ = ['title', 'complete_time']
4、创建模板
$ craft view index$ craft view detail
其中模板引擎使用的是 Jinja2
resources/templates/index.html
TODO LIST
序号 | 任务 | 完成时间 | 编辑 | 删除 | |
{ { row.id }} | { { row.title }} | {% if row.complete_time %}{ { row.complete_time }} | {% else %}{% endif %} |
resources/templates/edit.html
5、编写对应的控制器方法
"""A IndexController Module."""from masonite.request import Requestfrom masonite.view import Viewfrom masonite.controllers import Controllerfrom app.TodoList import TodoListfrom datetime import datetimeclass IndexController(Controller): """IndexController Controller Class.""" def __init__(self, request: Request, view: View): """IndexController Initializer Arguments: request {masonite.request.Request} -- The Masonite Request class. """ self.request = request self.view = view def index(self): rows = TodoList.all() return self.view.render('index', { "rows": rows}) def save(self): uid = self.request.input("id") title = self.request.input("title") if uid: TodoList.where('id', '=', uid).update({ 'title': title}) else: TodoList.create(title=title) return self.request.redirect("/") def detail(self): uid = self.request.param("id") row = TodoList.find(uid) return self.view.render('edit', { "row": row}) def delete(self): uid = self.request.param("id") TodoList.find(uid).delete() return self.request.redirect("/") def complete(self): uid = self.request.param("id") current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S") TodoList.where('id', '=', uid).update({ 'complete_time': current_time}) return self.request.redirect("/") def truncate(self): TodoList.truncate() return self.request.redirect("/")
6、配置路由文件
"""Web Routes."""from masonite.routes import Get, PostROUTES = [ Get('/', 'IndexController@index'), Get('/add', 'IndexController@detail'), Get('/edit/@id', 'IndexController@detail'), Get('/delete/@id', 'IndexController@delete'), Get('/complete/@id', 'IndexController@complete'), Get('/truncate', 'IndexController@truncate'), Post('/save', 'IndexController@save'),]
7、界面展示
参考文章
转载地址:https://pengshiyu.blog.csdn.net/article/details/103216204 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!
发表评论
最新留言
感谢大佬
[***.8.128.20]2024年05月06日 02时03分30秒
关于作者
喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
python写的本地搜索小工具0.9
2019-05-09
远程访问和文件传输介绍
2019-05-09
vi 突然显示空格的颜色
2019-05-09
利用linux处理网络流量数据
2019-05-09
putty的复制和粘贴
2019-05-09
tar 由于前面延迟的错误而退出
2021-07-12
linux subversion 的几个命令
2021-07-12
[转]通过RSS订阅、邮件转发自动同步多个Blog
2021-07-12
数字证书
2021-07-12
vim 与vi的兼容性问题
2019-05-09
用vim编python程序
2019-05-09
【转】Winxp下 gvim 编程环境搭建
2019-05-09
用python3.0 和vim配合检查文件中文的编码
2019-05-09
开机自动打开windows共享
2019-05-09
163提供开源操作系统的镜像
2019-05-09
svn update 碰到编码问题无法更新
2019-05-09
用密钥登录linux服务器
2019-05-09
Sqlserver在删数据库时提示正在使用
2019-05-09
bash 脚本
2019-05-09
sqlserver 2008 服务没法启动
2019-05-09