Python:masonite初体验TodoList

网友投稿 1220 2022-05-30

文档:https://docs.masoniteproject.com/

初次体验框架,感觉里边提供了丰富的命令行工具可以快速开发,

主要是ORM很棒,区别于Python生态Django等的ORM,和PHP的laravel很像,简单高效

一、环境配置

环境

Python 3.4+ masonite 2.2.26 masonite-cli 2.2.2

1

2

3

安装

$ pip install masonite-cli $ craft # 查看帮助

1

2

3

二、新建一个项目

# 1、新建项目 craft new project_name cd project_name # 2、安装依赖 craft install # 3、启动服务 craft serve

1

2

3

4

5

6

7

8

9

访问:http://127.0.0.1:8000/

出现欢迎界面

三、示例1:hello world

1、创建控制器

$ craft controller Index

1

app/http/controllers/IndexController.py

"""A IndexController Module.""" from masonite.request import Request from masonite.view import View from masonite.controllers import Controller class 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"

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

2、配置路由

routes/web.py

"""Web Routes.""" from masonite.routes import Get, Post ROUTES = [ Get('/', 'IndexController@show'), ]

1

2

3

4

5

6

7

8

masonite默认会自动重启服务

再次访问 http://127.0.0.1:8000/

显示:Hello world

示例2:新建TODOLIST项目

1、配置数据库,使用sqlite

.env

DB_CONNECTION=sqlite DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=data.db DB_USERNAME=root DB_PASSWORD=root DB_LOG=True

1

2

3

4

5

6

7

2、创建迁移文件

$ craft migration create_todolist_table --create todolist

1

设置3个字段:id,title,complete_time

databases/migrations/create_todolist_table.py

from orator.migrations import Migration class 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')

1

Python:masonite初体验TodoList

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

迁移数据, 建表

$ craft migrate

1

查看建表语句

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 );

1

2

3

4

5

6

7

可以看到默认多加了2个字段:created_at,updated_at

3、创建Model

$ craft model TodoList

1

稍作修改

app/TodoList.py

"""TodoList Model.""" from config.database import Model class TodoList(Model): """TodoList Model.""" # 查询数据库的时候会在类名后加s,所以自定义表名 __table__ = "todolist" # 要写入的字段 __fillable__ = ['title', 'complete_time']

1

2

3

4

5

6

7

8

9

10

11

12

13

4、创建模板

$ craft view index $ craft view detail

1

2

其中模板引擎使用的是 Jinja2

resources/templates/index.html

TODO LIST

{% for row in rows %} {% if row.complete_time %} {% else %} {% endif %} {% endfor %}
序号 任务 完成时间 编辑 删除
{{ row.id }} {{ row.title }} {{ row.complete_time }}

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

resources/templates/edit.html

{{ csrf_field }}

1

2

3

4

5

6

7

8

9

10

5、编写对应的控制器方法

"""A IndexController Module.""" from masonite.request import Request from masonite.view import View from masonite.controllers import Controller from app.TodoList import TodoList from datetime import datetime class 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("/")

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

6、配置路由文件

"""Web Routes.""" from masonite.routes import Get, Post ROUTES = [ 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'), ]

1

2

3

4

5

6

7

8

9

10

11

12

13

14

7、界面展示

参考文章

https://docs.masoniteproject.com/creating-a-blog

Python

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:HBase实用技巧:一种全量+增量数据的迁移方法
下一篇:ApiPost V3 如何设置一个变量?
相关文章