Masonite 熟悉步驟小記錄 (一、路由篇)

Galois發表於2020-06-06
$ 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 協議》,轉載必須註明作者和本文連結
不要試圖用百米衝刺的方法完成馬拉松比賽。

相關文章