天天看点

Python:masonite初体验TodoList

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

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

主要是ORM很棒,区别于

Python 生态 Django 等的ORM,和PHP的 laravel 很像,简单高效

一、环境配置

环境

Python 3.4+
masonite 2.2.26
masonite-cli 2.2.2      

安装

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

二、新建一个项目

# 1、新建项目
craft new project_name
cd project_name

# 2、安装依赖
craft install  

# 3、启动服务
craft serve         

访问:

http://127.0.0.1:8000/

出现欢迎界面

三、示例1:Hello World

1、创建控制器

$ craft controller Index      

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"
         

2、配置路由

routes/web.py

"""Web Routes."""

from masonite.routes import Get, Post

ROUTES = [
    Get('/', 'IndexController@show'),
]
      

masonite默认会自动重启服务

再次访问

显示: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      

2、创建迁移文件

$ craft migration create_todolist_table --create todolist      

设置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')
      

迁移数据, 建表

$ 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 Model


class TodoList(Model):
    """TodoList Model."""
    # 查询数据库的时候会在类名后加s,所以自定义表名
    __table__ = "todolist"

    # 要写入的字段
    __fillable__ = ['title', 'complete_time']
      

4、创建模板

$ craft view index
$ craft view detail      

其中模板引擎使用的是 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>

      

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>      

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("/")
      

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'),
]
      

7、界面展示

Python:masonite初体验TodoList

参考文章

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