-->

Save file to plone site using python

2019-08-12 00:58发布

问题:

I am generating an xml file in python, I need to save it to my plone site but am unsure how to.

def generate_sitemap_index_file(self, sites):
    """ Generate a google sitemap index file
    """
    root = ET.Element("sitemapindex")

    for site in sites:
        sitemap = ET.SubElement(root, "sitemap")
        loc = ET.SubElement(sitemap, "loc")
        loc.text = self.aq_parent.absolute_url() + "/googlesitemap/" + site

    ET.ElementTree(root).write("sitemap_index.xml")

This function saves the file into my zinstance folder, but zope isn't aware of it.

回答1:

You can create a content object called File in Plone. See: http://docs.plone.org/external/plone.api/docs/content.html#create-content

Here an untestet example to give you a guess:

# -*- coding: utf-8 -*-

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

portal = app["Plone"]  # Plone is your Plone site in Zope root
setSite(portal)

container = portal
# create the file object:
file_obj = api.content.create(                          
    container, 'File', 
    id='sitemap_index.xml',                             
    title='sitemap_index.xml', 
    safe_id=True
)               

# attache the file to the file object:
file_obj.file = NamedBlobFile(                          
    data=your_file_handle,                                  
    contentType='application/xml',                   
    filename='sitemap_index.xml',            
)  
transaction.commit()

Make sure you have added plone.api in your buildout.cfg eggs part! This script you can run from commandline:

./bin/instance run your_script.py

But as a side note, you can let Plone build you a sitemap_index.xml.gz, just enable it in site_setup > main.



回答2:

I'm unsure you really need to see this file as a Plone content. Probably you simply need to expose the file when calling http://something/sitemap_index.xml

You can simply add it as a Zope File from ZMI (in this way the file will be available, but will not be a CMS content) or publish it using Apache/NGIX in front of Plone.