seed 體驗
首先在專案裡可以看到 masonite 預設準備的一個 seeder,位於 masapp/databases/seeds/user_table_seeder.py
,這個 seeder.py 是這樣寫的:
from orator.seeds import Seeder
from app.User import User
from config.factories import factory
class UserTableSeeder(Seeder):
def run(self):
factory(User, 50).create()
可以看到這個 seeder 引入了 masapp/config/factories.py
模組的 factory
類:
from orator.orm import Factory
from app.User import User
factory = Factory()
def users_factory(faker):
return {
'name': faker.name(),
'email': faker.email(),
'password': '$2b$12$WMgb5Re1NqUr.uSRfQmPQeeGWudk/8/aNbVMpD1dR.Et83vfL8WAu', # == 'secret'
}
factory.register(User, users_factory)
現在可以使用命令播種資料了:
(env) $ craft seed:run
自制 seeder
準備一個模型和資料表:
(env) $ craft model Todo
(env) $ craft migration create_todos_table --create todos
對這個新的 migration 資料表檔案 masapp/databases/migrations/2020_06_07_114541_create_todos_table.py
進行新增欄位的編寫:
table.string('name')
table.text('description')
table.integer('user_id').unsigned()
table.foreign('user_id').references('id').on('users')
首先在 masapp/config/factories.py
這個工廠模組中新增:
from app.Todo import Todo
import random
def todos_factory(faker):
return {
'name': faker.name(),
'description': faker.paragraph(),
'user_id': random.randint(1, 50)
}
factoru.register(Todo, todos_factory)
然後生成 masapp/databases/seeds/todo_table_seeder.py
:
(env) $ craft seed Todo
from orator.seeds import Seeder
class TodoTableSeeder(Seeder):
def run(self):
pass
對這個 seeder 進行一些設定:
from orator.seeds import Seeder
from app.Todo import Todo
from config.factories import factory
class TodoTableSeeder(Seeder):
def run(self):
factory(Todo, 50).create()
把原來的 masapp/databases/seeds/database_seeder.py
:
from orator.seeds import Seeder
from .user_table_seeder import UserTableSeeder
class DatabaseSeeder(Seeder):
def run(self):
self.call(UserTableSeeder)
新增新編寫的 seeder:
from orator.seeds import Seeder
from .user_table_seeder import UserTableSeeder
from .todo_table_seeder import UserTableSeeder
class DatabaseSeeder(Seeder):
def run(self):
self.call(UserTableSeeder)
self.call(TodoTableSeeder)
之後可以回滾遷移:
(env) $ craft migrate:refresh -s
本作品採用《CC 協議》,轉載必須註明作者和本文連結