使用plone.api创建文件的脚本Python在设置文件时出现错误WrongType

时间:2016-07-13 12:23:03

标签: python file plone

逗人,

我正在创建一个脚本python来批量上传Plone站点中的文件,安装是UnifiedInstaller Plone 4.3.10。

此脚本读取txt,此txt与分号分隔,在新创建的项目中设置文件时出现错误。

Bellow the Script。

from zope.site.hooks import setSite
from plone.namedfile.file import NamedBlobFile
from plone import api
import transaction
import csv

portal = app['Plone']
setSite(portal)
container = portal['PROCESSOS']

with open('CARGA/C008_0002.txt', 'rb') as csvfile:
    reader = csv.DictReader(csvfile, delimiter=';', quotechar='|')
    for row in reader:
        pdf_id = 'P'+str(row['IMAGEM']).strip('Pasta Geral\\ ')
        file_obj = api.content.create(                          
            container, 'File',
            title=str(row['INTERESSADO']),
            id=pdf_id,
            description=str(row['CNPJ / CPF'])+' '+str(row['ASSUNTO']),
            safe_id=True
        )
        pdf_path = 'INMEQ/'+str(row['IMAGEM']).replace("\\", "/")
        print(pdf_path)
        file_obj.file = NamedBlobFile(
            data=open(pdf_path, 'r').read(),
            contentType='application/pdf',
            filename=str(file_obj.id),
        )
        print('Created: '+row['NDOPROCESSO']+'.')

transaction.commit()

当脚本设置文件时,会出现错误“WrongType”。见verbose bellow。

Traceback (most recent call last):
  File "<console>", line 18, in <module>
  File "/home/jaf/plone4310/buildout-cache/eggs/plone.namedfile-3.0.9-py2.7.egg/plone/namedfile/file.py", line 384, in __init__
    self.filename = filename
  File "/home/jaf/plone4310/buildout-cache/eggs/zope.schema-4.2.2-py2.7.egg/zope/schema/fieldproperty.py", line 52, in __set__
    field.validate(value)
  File "/home/jaf/plone4310/buildout-cache/eggs/zope.schema-4.2.2-py2.7.egg/zope/schema/_bootstrapfields.py", line 182, in validate
    self._validate(value)
  File "/home/jaf/plone4310/buildout-cache/eggs/zope.schema-4.2.2-py2.7.egg/zope/schema/_bootstrapfields.py", line 309, in _validate
    super(MinMaxLen, self)._validate(value)
  File "/home/jaf/plone4310/buildout-cache/eggs/zope.schema-4.2.2-py2.7.egg/zope/schema/_bootstrapfields.py", line 209, in _validate
    raise WrongType(value, self._type, self.__name__)
WrongType: ('processo-al-1.pdf', <type 'unicode'>, 'filename')

感谢您的关注!

- JulianoAraújo

1 个答案:

答案 0 :(得分:6)

您需要将文件名作为unicode传递。

file_obj.file = NamedBlobFile(
    data=open(pdf_path, 'r').read(),
    contentType='application/pdf',
    filename=unicode(file_obj.id),  # needs to be unicode
)

plone.namedfile docu中的更多信息 - &gt; https://github.com/plone/plone.namedfile/blob/36014d67c3befacfe3a058f1d3d99a6a4352a31f/plone/namedfile/usage.rst