DEV Community

qiudaozhang
qiudaozhang

Posted on

masonite 模型-表-控制器 api编写流程

假设我们需要管理用户的api key ,api secret。

生成model

python craft model ApiKey
Enter fullscreen mode Exit fullscreen mode

在app/models,将会得到一个模型

""" ApiKey Model """

from masoniteorm.models import Model


class ApiKey(Model):
    """ApiKey Model"""

    pass
Enter fullscreen mode Exit fullscreen mode

我们填充一点需要的内容。

""" ApiKey Model """

from masoniteorm.models import Model
from masoniteorm.relationships import belongs_to


class ApiKey(Model):
    """ApiKey Model"""

    __table__ = 'api_keys'

    __fillable__ = ['id', 'api_key', 'api_secret', 'uid']

    # 它属于某个用户的,这里要定义一个反向关联的模型

    @belongs_to('uid', 'id')  # 第一个字段是api_keys的存储的值,第二个id代表了users表里面的id
    def user(self):
        from app.models.User import User
        return User
Enter fullscreen mode Exit fullscreen mode

生成迁移文件

python craft migration create_api_keys_table --create api_keys
Enter fullscreen mode Exit fullscreen mode

迁移文件

我们填充下字段的描述

"""CreateApiKeysTable Migration."""

from masoniteorm.migrations import Migration


class CreateApiKeysTable(Migration):
    def up(self):
        """
        Run the migrations.
        """
        with self.schema.create("api_keys") as table:
            table.increments("id")
            table.string("api_key").unique()
            table.string("api_secret").unique()
            table.integer("uid").unsigned()
            table.timestamps()

    def down(self):
        """
        Revert the migrations.
        """
        self.schema.drop("api_keys")
Enter fullscreen mode Exit fullscreen mode

执行迁移

python craft migrate
Enter fullscreen mode Exit fullscreen mode

创建一个控制器

接下来创建一个API Controller,测试我们的逻辑

python craft controller api/ApiKeyController -a
Enter fullscreen mode Exit fullscreen mode

接下来注册路由

routes/api.py

from masonite.routes import Route

ROUTES = [
  ...
    Route.api('apikeys', 'api.ApiKeyController')
]
Enter fullscreen mode Exit fullscreen mode

控制器代码改写

from masonite.authentication import Auth
from masonite.controllers import Controller
from masonite.request import Request
from masonite.views import View

from app.models.ApiKey import ApiKey


class ApiKeyController(Controller):
    def index(self, view: View):
        return view.render("")

    def show(self, view: View):
        return view.render("")

    def store(self, request: Request, auth: Auth):
        api_key = request.input("api_key")
        api_secret = request.input("api_secret")
        obj = ApiKey()
        obj.api_key = api_key
        obj.api_secret = api_secret
        obj.uid = auth.user().id
        obj.save()
        return {"code": 0, "message": "success"}

    def update(self, view: View):
        return view.render("")

    def destroy(self, view: View):
        return view.render("")
Enter fullscreen mode Exit fullscreen mode

测试

测试提交

数据库检查确认

数据库查看

确认无误,没问题,基本的逻辑就全走通了,剩下的根据需要添砖即可。

Top comments (0)