当前位置:   article > 正文

Python:masonite初体验TodoList_masonite python

masonite python

文档: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
  • 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


<h1>TODO LIST</h1>

<a href="/add"><button>添加</button></a>
<a href="/truncate"><button>清空</button></a>

<table border="1">
    <thead>
    <tr>
        <td>序号</td>
        <td>任务</td>
        <td>完成时间</td>
        <td>编辑</td>
        <td>删除</td>
    </tr>
    </thead>

    <tbody>
    {% for row in rows %}
        <tr>
            <td>{{ row.id }} </td>
            <td>{{ row.title }} </td>
            {% if row.complete_time %}
                <td>{{ row.complete_time }}</td>
            {% else %}
                <td>
                <a href="/complete/{{ row.id }}">
                <button>完成</button>
            </a>
                </td>
            {% endif %}

            <td><a href="/edit/{{ row.id }}">
                <button>修改</button>
            </a></td>
            <td><a href="/delete/{{ row.id }}">
                <button>删除</button>
            </a></td>
        </tr>
    {% endfor %}
    </tbody>
</table>


  • 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

<form action="/save" method="post">
    {{ csrf_field }}

    <input type="hidden" name="id" id="title" value="{{ row.id }}">

    <label for="title"></label>
    <input type="text" name="title" id="title" value="{{ row.title }}">

    <input type="submit" value="提交">
</form>
  • 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

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/羊村懒王/article/detail/135010
推荐阅读
相关标签
  

闽ICP备14008679号