2011/08/01

CSV Import with Transmogrifier

假設你的欄位資料,都放在 mydata.csv 檔案裡,想要批次匯入來建立 MyContentType 內容,下列是主要的步驟範例。

以自製模組 mysite.migration 為例,它的 configure.zcml 內容範例如下:
<configure
xmlns="http://namespaces.zope.org/zope"
xmlns:five="http://namespaces.zope.org/five"
xmlns:i18n="http://namespaces.zope.org/i18n"
xmlns:genericsetup="http://namespaces.zope.org/genericsetup"
xmlns:transmogrifier="http://namespaces.plone.org/transmogrifier"
i18n_domain="mysite.migration">

<!-- Include zcml files of all required packages -->
<includeDependencies package="." />

<genericsetup:registerProfile
name="default"
title="mysite.migration"
directory="profiles/default"
description="MySite transmogrifier profile."
provides="Products.GenericSetup.interfaces.EXTENSION"
/>

<!-- Register Transmogrifier Profile -->
<include package="collective.transmogrifier" />
<include package="collective.transmogrifier" file="meta.zcml" />
<transmogrifier:registerConfig

name="mysite.migration.importFromCSV"
title="Import Content Data From CSV"
description="Transmogrifier config to import contents from CSV"
configuration="confs/import_from_csv.cfg"
/>

<!-- -*- extra stuff goes here -*- -->

</configure>

在 confs/import_from_csv.cfg 內容範例如下:
[transmogrifier]
pipeline =
csvsource
type-inserter
path-inserter
folders
constructor
schemaupdater
state-inserter
workflowupdater
reindexobject


[csvsource]
blueprint = collective.transmogrifier.sections.csvsource
filename = mysite.migration:data/mydata.csv

[type-inserter]
blueprint = collective.transmogrifier.sections.inserter
key = string:_type
value = string:MyContentType

[path-inserter]
blueprint = collective.transmogrifier.sections.inserter
key = string:_path
value = string:/myfolder/${item/id}

[folders]
blueprint = collective.transmogrifier.sections.folders

[constructor]
blueprint = collective.transmogrifier.sections.constructor

[schemaupdater]
blueprint = plone.app.transmogrifier.atschemaupdater

[state-inserter]
blueprint = collective.transmogrifier.sections.inserter
key = string:_transitions
value = string:publish

[workflowupdater]
blueprint = plone.app.transmogrifier.workflowupdater

[reindexobject]
blueprint = plone.app.transmogrifier.reindexobject

profiles/default/transmogrifier.txt 的內容範例如下:
# this file contains transmogrifier profile names to run
# on GenericSetup transmogrifier's step
mysite.migration.importFromCSV

以上模組檔案內容就緒後,在 buildout.cfg 加上:
[buildout]
...
develop =
src/mysite.migration

[instance]
...
eggs =
mysite.migration

執行 bin/buildout 之後,進入 ZMI 的 portal_setup 設定畫面,從 "Select Profile Or Snapshot" 下拉選單,點選 mysite.migration 項目,再點選 "Run transmogrifier pipeline" 項目,最後點選 "Import selected steps" 按鈕。

No comments: