Masonite 熟悉步骤小记录 (一、路由篇)

安装篇(Mac)

$ cd ~/Code/
$ mkdir masapp
$ cd masapp
$ python3 -m venv env
$ source ./env/bin/activate
(env) $ pip3 install -U pip
(env) $ pip3 install masonite-cli
(env) $ craft new masapp .
(env) $ craft install
(env) $ craft serve [-p 8080]

craft new project_name --version 1.6 创建指定版本的 masonite 框架。

直接执行 craft 可以看到有很多子命令可以用:

Masonite Version: 2.3.9

Usage:
  command [options] [arguments]

Options:
  -h, --help                      Display this help message
  -q, --quiet                     Do not output any message
  -V, --version                   Display this application version
      --ansi                      Force ANSI output
      --no-ansi                   Disable ANSI output
  -n, --no-interaction            Do not ask any interactive question
  -v|vv|vvv, --verbose[=VERBOSE]  Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug

Available commands:
  auth              Creates an authentication system.
  command           Creates a new command.
  controller        Creates a controller.
  down              Puts the server in a maintenance state.
  help              Displays help for a command
  info              Displays environment info for debugging.
  install           Installs all of Masonite's dependencies
  job               Creates a new Job.
  key               Generate a new key.
  list              Lists commands
  mailable          Creates a new Mailable.
  middleware        Creates a middleware.
  migrate           Run migrations.
  migration         Makes a new migration.
  model             Creates a model.
  new               Creates a new Masonite project
  preset            Swap the front-end scaffolding for the application
  provider          Creates a new Service Provider.
  publish           Publishes a Service Provider
  rule              Creates a new Rule.
  seed              Create a seeder to seed a database.
  serve             Run the Masonite server.
  test              Creates a new test case.
  tinker            Run a python shell with the container pre-loaded.
  up                Brings the server out of maintenance state.
  view              Creates a view.
 migrate
  migrate:refresh   Migrate refresh.
  migrate:reset     Migrate reset.
  migrate:rollback  Migrate Rollback.
  migrate:status    Migrate status.
 model
  model:docstring   Generate a model docstring based on a table definition
 queue
  queue:table       Create migration files for the queue feature
  queue:work        Start the queue worker
 rule
  rule:enclosure    Creates a new rule enclosure.
 seed
  seed:run          Run seed for database.
 show
  show:routes       List out all routes of the application.

如果想进一步查看某个子命令的参数说明可以使用 craft help ...,其中 ... 代表想查看的命令详情,比如查看 serve 命令详情:

$ (env) $ craft help serve

MVC 目录结构

masapp/routes/web.py

from masonite.routes import Get, Post

ROUTES = [
    Get('/', 'WelcomeController@show').name('welcome'),
]

可以看到有个路由列表 ROUTES,里面有一项 Get('/', 'WelcomeController@show').name('welcome'),里面的 WelcomeController@show 对应于 masapp/app/http/controllers/WelcomeController.py 里面的 show 函数。后面的 .name() 是对这条路由参数命名。
masapp/app/http/controllers/WelcomeController.py

from masonite.view import View
from masonite.request import Request
from masonite.controllers import Controller

class WelcomeController(Controller):

    def show(self, view: View, request: Request):
        return view.render('welcome')

如果要增加路由,那就在 masapp/routes/web.py 中的 ROUTES 列表中增加路由项:

from masonite.routes import Get, Post

ROUTES = [
    Get().route('/', 'WelcomeController@show').name('welcome'),
    # 新增
    Post().route('/store', 'WelcomeController@store').name('welcome'),
]

如果嫌以上语法太冗余的话,可以 from masonite.helpers.routes import get, post 后写简单点:

from masonite.routes import Get, Post
from masonite.helpers.routes import get, post

ROUTES = [
    get('/', 'WelcomeController@show').name('welcome'),
    post('/store', 'WelcomeController@store').name('welcome'),
]

也可以在路由上放置 Middleware,中文喜欢说这是中间件:

get('/', 'WelcomeController@show').name('welcome').middleware('auth')

中间件模块在 masapp/config/middleware.py

from masonite.middleware import ResponseMiddleware, MaintenanceModeMiddleware, GuardMiddleware

from app.http.middleware.AuthenticationMiddleware import \
    AuthenticationMiddleware
from app.http.middleware.CsrfMiddleware import CsrfMiddleware
from app.http.middleware.LoadUserMiddleware import LoadUserMiddleware
from app.http.middleware.VerifyEmailMiddleware import VerifyEmailMiddleware

HTTP_MIDDLEWARE = [
    LoadUserMiddleware,
    CsrfMiddleware,
    ResponseMiddleware,
    MaintenanceModeMiddleware,
]

ROUTE_MIDDLEWARE = {
    'auth': AuthenticationMiddleware,
    'verified': VerifyEmailMiddleware,
    'guard': GuardMiddleware,
}

可以看到有个字典 ROUTE_MIDDLEWARE 里面存放了几个开箱即用的路由中间件,其中 'auth' 的值是 AuthenticationMiddleware,这是身份验证中间件,位于:masapp/app/http/middleware/AuthenticationMiddleware.py

路由写多了会比较冗余,路由的写法可以用群组模式:

from masonite.routes import Get, Post, RouteGroup
from masonite.helpers.routes import get, post

ROUTES = [
    RouteGroup([
        get('/', 'WelcomeController@show').name('welcome'),
        post('/store', 'WelcomeController@store').name('posts'),
    ], middleware=['auth'], name='blog.')
]

其中:

RouteGroup([
        get('/', 'WelcomeController@show').name('welcome'),
        post('/store', 'WelcomeController@store').name('posts'),
    ], middleware=['auth'], name='blog.')

相当于:

ROUTES = [
    get('/', 'WelcomeController@show').name('blog.welcome').middleware('auth'),
    post('/store', 'WelcomeController@store').name('blog.posts').middleware('auth'),

路由列表可以这样查看:

(env) $ craft show:routes

如果比较有强迫症可以在引入 RouteGroup 时起个别名 from masonite.routes import Get, Post, RouteGroup as group
这样就可以写成:

group([
        get('/', 'WelcomeController@show').name('welcome'),
        post('/store', 'WelcomeController@store').name('posts'),
    ], middleware=['auth'], name='blog.')
本作品采用《CC 协议》,转载必须注明作者和本文链接

不要试图用百米冲刺的方法完成马拉松比赛。

本帖由 Galois 于 2周前 加精
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

请勿发布不友善或者负能量的内容。与人为善,比聪明更重要!