[Zope] Saving property values to file

J. Cameron Cooper jccooper@rice.edu
Wed, 25 Jul 2001 10:15:41 -0500


>
>
>Sorry, but can you expand as I am not sure as how this is done.
>
What a rendered object returns is a string. Usually that string is sent 
to the web server, but it can also be put to other purposes. You could, 
for instance, give it to another method to save to a file. Just so 
happens that the most lightweight thing that can deal with the host 
filesystem is an External Method.

Your External Method will look something like:

in a file called extSaveFile.py in the Extensions directory:

file='DEFAULT_FILE"  # substitute a valid file on your system here
def saveFile(file=file,contents="Default contents: error"):
   fsave = open(file,'w')
   fsave.write(contents)
   fsave.close()
   return

Then create an external method with

id=extSaveFile
title=Save file to host system
function=extSaveFile
method=saveFile

Then have a Python Script that does

torender='dtmldoc'  # what to render and save
filepath='/tmp/csv'    # where to save
str = container[torender](container,container.REQUEST)  # this renders it
container.extSaveFile(file=filepath,contents=str)  # calls the external 
method to do the saving work
return "Object " + torender + " saved to " + filepath   # or return 
something else, like another DTML doc

So all you have to do to save is call the PythonScript. You might even 
give it parameters to specify file or whatever.

Say, someone want to put this in the ZopeLabs cookbook for me? I haven't 
an account.

Notes: I have not fully tested this. But it should be close. See the 
Python Library Reference on python.org (section 2.1.7.9) for the 
fileobject API.
Also, it is a major security risk to allow writing of an arbitrary file. 
Lock it down tight, or code in a specific directory and only take file 
names to write to.

>Also how do I create the dtml method so that it lists each record on one
>line sequentially, so that each additional record is started on a new line?
>
HTML may not care about line breaks, but DTML does. Although usually 
used for HTML, it doens't have to be. DTML can generate arbitrary text 
files. A CSV file is real, real easy. Usually one looks something like:

"one","two","three"
"i","am","here"

So if you have a list of objects with properties, you would do something 
like this in DTML:

<dtml-in listofwhatever>
"<dtml-var firstprop>","<dtml-var secprop>","<dtml-var thirdprop>"
</dtml-in>

That's all. No headers or footers of whatever, since that'll put HTML in 
your pretty CSV file. And remember that whitespace formatting within the 
in loop will be preserved, so it all has to be on the same line.

>If possible can you add couple of simple examples
>
Well, the above should take care of that.

            --jcc
        (expoundment)