You are not logged in Log in Join
You are here: Home » Zope Documentation » Books » The Zope Book Releases » The Zope Book (2.5 Edition) » Appendix B: API Reference

Log in
Name

Password

 
Previous Page Up one Level Next Page Appendix B: API Reference Comments On/Off Table of Contents

Appendix B: API Reference

This reference describes the interfaces to the most common set of basic Zope objects. This reference is useful while writing DTML, Perl, and Python scripts that create and manipulate Zope objects.

Anonymous User - June 20, 2002 6:55 pm:
 This section needs a Table of Contents too.
Anonymous User - June 26, 2002 1:43 pm:
 The reference describes nearly nothing when you don't know the solution! 
 Examples are absolutely necessary.
Anonymous User - July 12, 2002 3:32 pm:
 i agree.
Anonymous User - July 14, 2002 5:21 am:
 Strongly disagree.  This is a reference, not a tutorial or explanatory text.
Anonymous User - Aug. 20, 2002 11:13 pm:
 A reference doesn't contain explanatory text?
Anonymous User - Aug. 31, 2002 11:20 am:
 Do any of these classes inherit anything from anything else?
 Why is ZClass absent?
Anonymous User - Oct. 10, 2002 10:12 am:
 Since many of the API objects/methods have no examples elsewhere in
 The Zope Book, it would be helpful to have at least one example of
 each here. If there were a single chapter of the book containing an
 organized API tutorial for all of these, the reference could remain
 a reference with no examples!
Anonymous User - Jan. 17, 2003 8:43 am:
Examples are needed. People who hate them should be able to disable them, just like comments. Everybody wins.
Anonymous User - Jan. 22, 2003 4:57 pm:
 hi
Anonymous User - Aug. 6, 2003 10:47 am:
 Theese are python classes described below, but I could not find any reference, how they are used from python
 scripts. Which objects have theese methods? What are the relations of Zope classes and standard Zope API
objects? Also examples would answere most questions, but the best thing would be some text about basic theory
 of theese things, maybe in a separate section!
 For example: How can I use the AuthenticatedUser.has_role() in a script? I would expect to find this in the
 Zope book.
Anonymous User - Aug. 7, 2003 7:02 am:
 How the hell do i use any of these things in python scripts?
cawb - Aug. 7, 2003 11:51 am:
 from AccessControl import ClassSecurityInfo, getSecrurityManager
 from Products.PageTemplates.PageTemplateFile import PageTemplateFile
 Normally you would use them during the creation of Zope Products, and the class attributes and methods would
 be available in the instances which you generate in the ZMI. Perhaps you should read the Zope Developers
 Guide before you explode?
 And login so we can provide advice directly, or join the mailing list.

module AccessControl

AccessControl: Security functions and classes

The functions and classes in this module are available to Python-based Scripts and Page Templates.

class SecurityManager

A security manager provides methods for checking access and managing executable context and policies

calledByExecutable(self)

Return a boolean value indicating if this context was called by an executable.

permission
Always available

validate(accessed=None, container=None, name=None, value=None, roles=None)

Validate access.

Arguments:

accessed
the object that was being accessed
container
the object the value was found in
name
The name used to access the value
value
The value retrieved though the access.
roles
The roles of the object if already known.

The arguments may be provided as keyword arguments. Some of these arguments may be omitted, however, the policy may reject access in some cases when arguments are omitted. It is best to provide all the values possible.

Anonymous User - Dec. 17, 2002 6:42 am:
 In writing a custom User Folder what should one do?
 Inherit from UserFolder and override the validate method or 
 use SecurityManager.validate()?
Anonymous User - Dec. 17, 2002 10:08 am:
 You typically don't want to override validate unless you need to do something very special.

permission
Always available

checkPermission(self, permission, object)

Check whether the security context allows the given permission on the given object.

permission
Always available

getUser(self)

Get the current authenticated user. See the AuthenticatedUser class.

permission
Always available

validateValue(self, value, roles=None)

Convenience for common case of simple value validation.

permission
Always available

def getSecurityManager()

Returns the security manager. See the SecurityManager class.

Anonymous User - June 20, 2002 6:56 pm:
 Examples?

module AuthenticatedUser

class AuthenticatedUser

This interface needs to be supported by objects that are returned by user validation and used for access control.

Anonymous User - July 12, 2002 3:32 pm:
 i don't seem to be able to access these methods from DTML...
 example?
Anonymous User - Sep. 16, 2002 6:27 am:
 for eg:
 <dtml-var "AUTHENTICATED_USER.getId()">returns zope user id
 <dtml-var "AUTHENTICATED_USER.getUserName()">return user name
 <dtml-var "AUTHENTICATED_USER.has_role('Manager')"> returned 1
 <dtml-var "AUTHENTICATED_USER.getRoles()"> returned 'Manager','Authenticated'
 <dtml-var "AUTHENTICATED_USER.getRolesInContext('folder_name')"> 'Manager','Authenticated'
 <dtml-var "AUTHENTICATED_USER.getDomains()"> returned empty ()
Anonymous User - Oct. 3, 2002 9:26 am:
 But the class is named AuthenticatedUser.  Why is it referenced with a different
 spelling (i.e. AUTHENTICATED_USER)?
Anonymous User - Oct. 10, 2002 10:05 am:
Presumably AUTHENTICATED_USER is the property of the HTML request object (i.e., REQUEST), which might be made
 clearer in the statement above about "supported by objects that are returned by user validation..."?
mcdonc - Nov. 19, 2002 2:34 am:
 See http://www.zope.org/Members/michel/Projects/Interfaces/DTMLSecurityAPI for the DTML security API.

getUserName()

Return the name of a user

Permission
Always available

getId()

Get the ID of the user. The ID can be used from Python to get the user from the user's UserDatabase.

Anonymous User - Nov. 7, 2002 8:35 am:
 Why I can get the user from the user's UserDatabase??? Why method I use?
 Tks...

Permission
Always available

has_role(roles, object=None)

Return true if the user has at least one role from a list of roles, optionally in the context of an object.

Permission
Always available

getRoles()

Return a list of the user's roles.

Permission
Always available

has_permission(permission, object)

Return true if the user has a permission on an object.

Permission
Always available

getRolesInContext(object)

Return the list of roles assigned to the user, including local roles assigned in context of an object.

Anonymous User - Jan. 21, 2003 8:17 am:
 what API function we must use to inspect proxy roles?

Permission
Always available

getDomains()

Return the list of domain restrictions for a user.

Permission
Always available

module DTMLDocument

class DTMLDocument(ObjectManagerItem, PropertyManager)

A DTML Document is a Zope object that contains and executes DTML code. It is useful to represent web pages.

manage_edit(data, title)

Change the DTML Document, replacing its contents with data and changing its title.

The data argument may be a file object or a string.

Permission
Change DTML Documents

document_src()

Returns the unrendered source text of the DTML Document.

Permission
View management screens

__call__(client=None, REQUEST={}, RESPONSE=None, **kw)

Calling a DTMLDocument causes the Document to interpret the DTML code that it contains. The method returns the result of the interpretation, which can be any kind of object.

To accomplish its task, DTML Document often needs to resolve various names into objects. For example, when the code &lt;dtml-var spam&gt; is executed, the DTML engine tries to resolve the name spam.

In order to resolve names, the Document must be passed a namespace to look them up in. This can be done several ways:

  • By passing a client object -- If the argument client is passed, then names are looked up as attributes on the argument.
  • By passing a REQUEST mapping -- If the argument REQUEST is passed, then names are looked up as items on the argument. If the object is not a mapping, an TypeError will be raised when a name lookup is attempted.
  • By passing keyword arguments -- names and their values can be passed as keyword arguments to the Document.

The namespace given to a DTML Document is the composite of these three methods. You can pass any number of them or none at all. Names are looked up first in the keyword arguments, then in the client, and finally in the mapping.

A DTMLDocument implicitly pass itself as a client argument in addition to the specified client, so names are looked up in the DTMLDocument itself.

Passing in a namespace to a DTML Document is often referred to as providing the Document with a context.

DTML Documents can be called three ways.

From DTML

A DTML Document can be called from another DTML Method or Document:


<dtml-var standard_html_header>
  <dtml-var aDTMLDocument>
<dtml-var standard_html_footer>

In this example, the Document aDTMLDocument is being called from another DTML object by name. The calling method passes the value this as the client argument and the current DTML namespace as the REQUEST argument. The above is identical to this following usage in a DTML Python expression:


<dtml-var standard_html_header>
  <dtml-var "aDTMLDocument(_.None, _)">
<dtml-var standard_html_footer>

From Python

Products, External Methods, and Scripts can call a DTML Document in the same way as calling a DTML Document from a Python expression in DTML; as shown in the previous example.

Anonymous User - Nov. 17, 2002 5:35 am:
 I think it would be much clearer to simply add a new example here, rather than refer to the previous
 (non-python) one

By the Publisher

When the URL of a DTML Document is fetched from Zope, the DTML Document is called by the publisher. The REQUEST object is passed as the second argument to the Document.

Permission
View

get_size()

Returns the size of the unrendered source text of the DTML Document in bytes.

Anonymous User - June 20, 2002 8:06 am:
 manage_addDocument should be manage_addDTMLDocument! if you use manage_addDocument, you�ll get a DTML
 Method...
Anonymous User - Jan. 10, 2003 9:40 am:
 manage_addDocument creates a DTML Method. manage_addDTMLDocument creates a DTML document. This has been
 pointed out 6 months ago, and still no change in Zope Book.

Permission
View

ObjectManager Constructor

manage_addDocument(id, title)

Add a DTML Document to the current ObjectManager

module DTMLMethod

class DTMLMethod(ObjectManagerItem)

A DTML Method is a Zope object that contains and executes DTML code. It can act as a template to display other objects. It can also hold small pieces of content which are inserted into other DTML Documents or DTML Methods.

The DTML Method's id is available via the document_id variable and the title is available via the document_title variable.

manage_edit(data, title)

Change the DTML Method, replacing its contents with data and changing its title.

The data argument may be a file object or a string.

Permission
Change DTML Methods

document_src()

Returns the unrendered source text of the DTML Method.

Permission
View management screens

__call__(client=None, REQUEST={}, **kw)

Calling a DTMLMethod causes the Method to interpret the DTML code that it contains. The method returns the result of the interpretation, which can be any kind of object.

To accomplish its task, DTML Method often needs to resolve various names into objects. For example, when the code &lt;dtml-var spam&gt; is executed, the DTML engine tries to resolve the name spam.

In order to resolve names, the Method must be passed a namespace to look them up in. This can be done several ways:

  • By passing a client object -- If the argument client is passed, then names are looked up as attributes on the argument.
  • By passing a REQUEST mapping -- If the argument REQUEST is passed, then names are looked up as items on the argument. If the object is not a mapping, an TypeError will be raised when a name lookup is attempted.
  • By passing keyword arguments -- names and their values can be passed as keyword arguments to the Method.

The namespace given to a DTML Method is the composite of these three methods. You can pass any number of them or none at all. Names will be looked up first in the keyword argument, next in the client and finally in the mapping.

Unlike DTMLDocuments, DTMLMethods do not look up names in their own instance dictionary.

Passing in a namespace to a DTML Method is often referred to as providing the Method with a context.

DTML Methods can be called three ways:

From DTML

A DTML Method can be called from another DTML Method or Document:


<dtml-var standard_html_header>
  <dtml-var aDTMLMethod>
<dtml-var standard_html_footer>

In this example, the Method aDTMLMethod is being called from another DTML object by name. The calling method passes the value this as the client argument and the current DTML namespace as the REQUEST argument. The above is identical to this following usage in a DTML Python expression:


<dtml-var standard_html_header>
  <dtml-var "aDTMLMethod(_.None, _)">
<dtml-var standard_html_footer>

From Python

Products, External Methods, and Scripts can call a DTML Method in the same way as calling a DTML Method from a Python expression in DTML; as shown in the previous example.

jmunoz - Sep. 20, 2002 1:04 pm:
 Could you give an example?
jmunoz - Sep. 20, 2002 1:27 pm:
 For example a good python script is:

 print container.test_dtml(client=container)
 return printed

By the Publisher

When the URL of a DTML Method is fetched from Zope, the DTML Method is called by the publisher. The REQUEST object is passed as the second argument to the Method.

Permission
View

get_size()

Returns the size of the unrendered source text of the DTML Method in bytes.

Permission
View

ObjectManager Constructor

manage_addDTMLMethod(id, title)

Add a DTML Method to the current ObjectManager

module DateTime

class DateTime

The DateTime object provides an interface for working with dates and times in various formats. DateTime also provides methods for calendar operations, date and time arithmetic and formatting.

DateTime objects represent instants in time and provide interfaces for controlling its representation without affecting the absolute value of the object.

DateTime objects may be created from a wide variety of string or numeric data, or may be computed from other DateTime objects. DateTimes support the ability to convert their representations to many major timezones, as well as the ability to create a DateTime object in the context of a given timezone.

DateTime objects provide partial numerical behavior:

  • Two date-time objects can be subtracted to obtain a time, in days between the two.
  • A date-time object and a positive or negative number may be added to obtain a new date-time object that is the given number of days later than the input date-time object.
  • A positive or negative number and a date-time object may be added to obtain a new date-time object that is the given number of days later than the input date-time object.
  • A positive or negative number may be subtracted from a date-time object to obtain a new date-time object that is the given number of days earlier than the input date-time object.

DateTime objects may be converted to integer, long, or float numbers of days since January 1, 1901, using the standard int, long, and float functions (Compatibility Note: int, long and float return the number of days since 1901 in GMT rather than local machine timezone). DateTime objects also provide access to their value in a float format usable with the python time module, provided that the value of the object falls in the range of the epoch-based time module.

Anonymous User - June 10, 2002 10:51 am:
 It actually seems to return the time in seconds since 1/1/1970, not 1/1/1901.
Anonymous User - July 24, 2002 2:32 pm:
 I'm guessing that's a typo -- python has always run time from 1970
Anonymous User - Aug. 20, 2002 12:15 am:
 epoch

 [UNIX: prob. from astronomical timekeeping] n. The time and date corresponding to 0 in an operating system's
 clock and timestamp values. Under most UNIX versions the epoch is 00:00:00 GMT, January 1, 1970; under VMS,
 it's 00:00:00 of November 17, 1858 (base date of the U.S. Naval Observatory's ephemerides); on a Macintosh,
it's the midnight beginning January 1 1904. System time is measured in seconds or ticks past the epoch. Weird
 problems may ensue when the clock wraps around (see wrap around), which is not necessarily a rare event; on
 systems counting 10 ticks per second, a signed 32-bit count of ticks is good only for 6.8 years. The
 1-tick-per-second clock of UNIX is good only until January 18, 2038, assuming at least some software
 continues to consider it signed and that word lengths don't increase by then.
jmunoz - Nov. 14, 2002 10:57 am:
 I confirm, it's the numbers of seconds, and not days, as said here.

 Correct this in the next release of the Zope Book, please !!
Anonymous User - Nov. 28, 2002 5:19 am:
 ...but when I run

 return str(DateTime()+1)

 ... it returns the date of tomorrow, not one second later from now!!... it seems DateTime REALLY returns
 'days' not seconds
 Run for Zope 2.60 (Python 2.1.3)
Anonymous User - Dec. 25, 2002 11:51 am:
 Yes, but this is another issue.
 Julian

A DateTime object should be considered immutable; all conversion and numeric operations return a new DateTime object rather than modify the current object.

A DateTime object always maintains its value as an absolute UTC time, and is represented in the context of some timezone based on the arguments used to create the object. A DateTime object's methods return values based on the timezone context.

Note that in all cases the local machine timezone is used for representation if no timezone is specified.

DateTimes may be created with from zero to seven arguments.

  • If the function is called with no arguments, then the current date/time is returned, represented in the timezone of the local machine.
  • If the function is invoked with a single string argument which is a recognized timezone name, an object representing the current time is returned, represented in the specified timezone.
  • If the function is invoked with a single string argument representing a valid date/time, an object representing that date/time will be returned.

    As a general rule, any date-time representation that is recognized and unambiguous to a resident of North America is acceptable.(The reason for this qualification is that in North America, a date like: 2/1/1994 is interpreted as February 1, 1994, while in some parts of the world, it is interpreted as January 2, 1994.) A date/time string consists of two components, a date component and an optional time component, separated by one or more spaces. If the time component is omitted, 12:00am is assumed. Any recognized timezone name specified as the final element of the date/time string will be used for computing the date/time value. (If you create a DateTime with the string Mar 9, 1997 1:45pm US/Pacific, the value will essentially be the same as if you had captured time.time() at the specified date and time on a machine in that timezone):

    
    e=DateTime("US/Eastern")
    # returns current date/time, represented in US/Eastern.
    
    x=DateTime("1997/3/9 1:45pm")
    # returns specified time, represented in local machine zone.
    
    y=DateTime("Mar 9, 1997 13:45:00")
    # y is equal to x
    

    The date component consists of year, month, and day values. The year value must be a one-, two-, or four-digit integer. If a one- or two-digit year is used, the year is assumed to be in the twentieth century. The month may be an integer, from 1 to 12, a month name, or a month abbreviation, where a period may optionally follow the abbreviation. The day must be an integer from 1 to the number of days in the month. The year, month, and day values may be separated by periods, hyphens, forward slashes, or spaces. Extra spaces are permitted around the delimiters. Year, month, and day values may be given in any order as long as it is possible to distinguish the components. If all three components are numbers that are less than 13, then a month-day-year ordering is assumed.

    The time component consists of hour, minute, and second values separated by colons. The hour value must be an integer between 0 and 23 inclusively. The minute value must be an integer between 0 and 59 inclusively. The second value may be an integer value between 0 and 59.999 inclusively. The second value or both the minute and second values may be omitted. The time may be followed by am or pm in upper or lower case, in which case a 12-hour clock is assumed.

  • If the DateTime function is invoked with a single Numeric argument, the number is assumed to be a floating point value such as that returned by time.time().

    A DateTime object is returned that represents the gmt value of the time.time() float represented in the local machine's timezone.

  • If the function is invoked with two numeric arguments, then the first is taken to be an integer year and the second argument is taken to be an offset in days from the beginning of the year, in the context of the local machine timezone. The date-time value returned is the given offset number of days from the beginning of the given year, represented in the timezone of the local machine. The offset may be positive or negative. Two-digit years are assumed to be in the twentieth century.
  • If the function is invoked with two arguments, the first a float representing a number of seconds past the epoch in gmt (such as those returned by time.time()) and the second a string naming a recognized timezone, a DateTime with a value of that gmt time will be returned, represented in the given timezone.:
    
    import time
    t=time.time()
    
    now_east=DateTime(t,'US/Eastern')
    # Time t represented as US/Eastern
    
    now_west=DateTime(t,'US/Pacific')
    # Time t represented as US/Pacific
    
    # now_east == now_west
    # only their representations are different
    
  • If the function is invoked with three or more numeric arguments, then the first is taken to be an integer year, the second is taken to be an integer month, and the third is taken to be an integer day. If the combination of values is not valid, then a DateTimeError is raised. Two-digit years are assumed to be in the twentieth century. The fourth, fifth, and sixth arguments specify a time in hours, minutes, and seconds; hours and minutes should be positive integers and seconds is a positive floating point value, all of these default to zero if not given. An optional string may be given as the final argument to indicate timezone (the effect of this is as if you had taken the value of time.time() at that time on a machine in the specified timezone).

If a string argument passed to the DateTime constructor cannot be parsed, it will raise DateTime.SyntaxError. Invalid date, time, or timezone components will raise a DateTime.DateTimeError.

The module function Timezones() will return a list of the timezones recognized by the DateTime module. Recognition of timezone names is case-insensitive.

strftime(format)

Return date time string formatted according to format

Anonymous User - June 26, 2002 2:12 pm:
 A explanation for the world outside the US would be helpfull. 
For me it was hard to find something like <dtml-var bobobase_modification_time fmt="%d.%m.%Y %H:%M:%S">
(like
 we use the date/time in Europe) to understand the time module.

See Python's time.strftime function.

Anonymous User - Nov. 13, 2002 11:38 am:
 This is so frustrating. How about an example of some of this usage - from this I 
 never would have guessed that the way to call DateTime in a DTML method was: 

 <dtml-var expr="_.DateTime()">

 And I STILL can't guess how to call strftime within a DTML method.  Anybody care
 to clairify this?
Anonymous User - Nov. 13, 2002 11:46 am:
 After trying many things I found that this works:

 <dtml-var expr="_.DateTime().strftime('%Y/%m/%d %H:%M:%S')">

 Is there a better way to handle this?
Anonymous User - Nov. 13, 2002 7:45 pm:
 or you can do <dtml-var expr="_.DateTime()" fmt="%Y/%m/%d %H:%M:%S"> 

 also checkout 
 http://www.zopelabs.com/cookbook/990690237

dow()

Return the integer day of the week, where Sunday is 0

Permission
Always available

aCommon()

Return a string representing the object's value in the format: Mar 1, 1997 1:45 pm

Permission
Always available

h_12()

Return the 12-hour clock representation of the hour

Permission
Always available

Mon_()

Compatibility: see pMonth

Permission
Always available

HTML4()

Return the object in the format used in the HTML4.0 specification, one of the standard forms in ISO8601.

See HTML 4.0 Specification

Dates are output as: YYYY-MM-DDTHH:MM:SSZ T, Z are literal characters. The time is in UTC.

Permission
Always available

greaterThanEqualTo(t)

Compare this DateTime object to another DateTime object OR a floating point number such as that which is returned by the python time module. Returns true if the object represents a date/time greater than or equal to the specified DateTime or time module style time. Revised to give more correct results through comparison of long integer milliseconds.

Permission
Always available

dayOfYear()

Return the day of the year, in context of the timezone representation of the object

Permission
Always available

lessThan(t)

Compare this DateTime object to another DateTime object OR a floating point number such as that which is returned by the python time module. Returns true if the object represents a date/time less than the specified DateTime or time module style time. Revised to give more correct results through comparison of long integer milliseconds.

Permission
Always available

AMPM()

Return the time string for an object to the nearest second.

Permission
Always available

isCurrentHour()

Return true if this object represents a date/time that falls within the current hour, in the context of this object's timezone representation

Permission
Always available

Month()

Return the full month name

Permission
Always available

mm()

Return month as a 2 digit string

Permission
Always available

ampm()

Return the appropriate time modifier (am or pm)

Permission
Always available

hour()

Return the 24-hour clock representation of the hour

Permission
Always available

aCommonZ()

Return a string representing the object's value in the format: Mar 1, 1997 1:45 pm US/Eastern

Permission
Always available

Day_()

Compatibility: see pDay

Permission
Always available

pCommon()

Return a string representing the object's value in the format: Mar. 1, 1997 1:45 pm

Permission
Always available

minute()

Return the minute

Permission
Always available

day()

Return the integer day

Permission
Always available

earliestTime()

Return a new DateTime object that represents the earliest possible time (in whole seconds) that still falls within the current object's day, in the object's timezone context

Anonymous User - Jan. 20, 2003 4:53 am:
 day() same of dayOfYear()?

Permission
Always available

Date()

Return the date string for the object.

Permission
Always available

Time()

Return the time string for an object to the nearest second.

Permission
Always available

isFuture()

Return true if this object represents a date/time later than the time of the call

Permission
Always available

greaterThan(t)

Compare this DateTime object to another DateTime object OR a floating point number such as that which is returned by the python time module. Returns true if the object represents a date/time greater than the specified DateTime or time module style time. Revised to give more correct results through comparison of long integer milliseconds.

Permission
Always available

TimeMinutes()

Return the time string for an object not showing seconds.

Permission
Always available

yy()

Return calendar year as a 2 digit string

Permission
Always available

isCurrentDay()

Return true if this object represents a date/time that falls within the current day, in the context of this object's timezone representation

Permission
Always available

dd()

Return day as a 2 digit string

Permission
Always available

rfc822()

Return the date in RFC 822 format

Permission
Always available

isLeapYear()

Return true if the current year (in the context of the object's timezone) is a leap year

Permission
Always available

fCommon()

Return a string representing the object's value in the format: March 1, 1997 1:45 pm

Permission
Always available

isPast()

Return true if this object represents a date/time earlier than the time of the call

Permission
Always available

fCommonZ()

Return a string representing the object's value in the format: March 1, 1997 1:45 pm US/Eastern

Permission
Always available

timeTime()

Return the date/time as a floating-point number in UTC, in the format used by the python time module. Note that it is possible to create date/time values with DateTime that have no meaningful value to the time module.

Permission
Always available

toZone(z)

Return a DateTime with the value as the current object, represented in the indicated timezone.

Permission
Always available

lessThanEqualTo(t)

Compare this DateTime object to another DateTime object OR a floating point number such as that which is returned by the python time module. Returns true if the object represents a date/time less than or equal to the specified DateTime or time module style time. Revised to give more correct results through comparison of long integer milliseconds.

Permission
Always available

Mon()

Compatibility: see aMonth

Permission
Always available

parts()

Return a tuple containing the calendar year, month, day, hour, minute second and timezone of the object

Permission
Always available

isCurrentYear()

Return true if this object represents a date/time that falls within the current year, in the context of this object's timezone representation

Permission
Always available

PreciseAMPM()

Return the time string for the object.

Permission
Always available

AMPMMinutes()

Return the time string for an object not showing seconds.

Permission
Always available

equalTo(t)

Compare this DateTime object to another DateTime object OR a floating point number such as that which is returned by the python time module. Returns true if the object represents a date/time equal to the specified DateTime or time module style time. Revised to give more correct results through comparison of long integer milliseconds.

Permission
Always available

pDay()

Return the abbreviated (with period) name of the day of the week

gaetan - Oct. 1, 2002 10:36 am:
 like Mon. for monday
gaetan - Oct. 1, 2002 10:40 am:
 like Mon. for monday, so you can get the whole name with Python dictionnary
 dd={"Mon.":'monday', "Tue.":'tuesday', ..., "Sun.":'sunday'} and use dd[date.pDay()]
Anonymous User - Jan. 22, 2003 4:59 pm:
 thiii

Permission
Always available

notEqualTo(t)

Compare this DateTime object to another DateTime object OR a floating point number such as that which is returned by the python time module. Returns true if the object represents a date/time not equal to the specified DateTime or time module style time. Revised to give more correct results through comparison of long integer milliseconds.

Permission
Always available

h_24()

Return the 24-hour clock representation of the hour

Permission
Always available

pCommonZ()

Return a string representing the object's value in the format: Mar. 1, 1997 1:45 pm US/Eastern

Permission
Always available

isCurrentMonth()

Return true if this object represents a date/time that falls within the current month, in the context of this object's timezone representation

Permission
Always available

DayOfWeek()

Compatibility: see Day

Permission
Always available

latestTime()

Return a new DateTime object that represents the latest possible time (in whole seconds) that still falls within the current object's day, in the object's timezone context

Permission
Always available

dow_1()

Return the integer day of the week, where Sunday is 1

Permission
Always available

timezone()

Return the timezone in which the object is represented.

Permission
Always available

year()

Return the calendar year of the object

Permission
Always available

PreciseTime()

Return the time string for the object.

Permission
Always available

ISO()

Return the object in ISO standard format

Dates are output as: YYYY-MM-DD HH:MM:SS

Permission
Always available

millis()

Return the millisecond since the epoch in GMT.

Permission
Always available

second()

Return the second

Permission
Always available

month()

Return the month of the object as an integer

Permission
Always available

pMonth()

Return the abbreviated (with period) month name.

Permission
Always available

aMonth()

Return the abbreviated month name.

Permission
Always available

isCurrentMinute()

Return true if this object represents a date/time that falls within the current minute, in the context of this object's timezone representation

regebro - Jan. 17, 2003 4:50 am:
 From 2.6.1 DateTime has an additional method tzoffset() that returns the offset in seconds to UTC of the
 DateTime objects timezone.

Permission
Always available

Day()

Return the full name of the day of the week

Permission
Always available

aDay()

Return the abbreviated name of the day of the week

Permission
Always available

module ExternalMethod

class ExternalMethod

Web-callable functions that encapsulate external Python functions.

The function is defined in an external file. This file is treated like a module, but is not a module. It is not imported directly, but is rather read and evaluated. The file must reside in the Extensions subdirectory of the Zope installation, or in an Extensions subdirectory of a product directory.

Due to the way ExternalMethods are loaded, it is not currently possible to import Python modules that reside in the Extensions directory. It is possible to import modules found in the lib/python directory of the Zope installation, or in packages that are in the lib/python directory.

manage_edit(title, module, function, REQUEST=None)

Change the External Method.

See the description of manage_addExternalMethod for a description of the arguments module and function.

Note that calling manage_edit causes the "module" to be effectively reloaded. This is useful during debugging to see the effects of changes, but can lead to problems of functions rely on shared global data.

__call__(*args, **kw)

Call the External Method.

Calling an External Method is roughly equivalent to calling the original actual function from Python. Positional and keyword parameters can be passed as usual. Note however that unlike the case of a normal Python method, the "self" argument must be passed explicitly. An exception to this rule is made if:

  • The supplied number of arguments is one less than the required number of arguments, and
  • The name of the function's first argument is self.

In this case, the URL parent of the object is supplied as the first argument.

ObjectManager Constructor

manage_addExternalMethod(id, title, module, function)

Add an external method to an

ObjectManager

.

In addition to the standard object-creation arguments,

id

and title, the following arguments are defined:

function
The name of the python function. This can be a an ordinary Python function, or a bound method.

module
The name of the file containing the function definition.

The module normally resides in the Extensions directory, however, the file name may have a prefix of product., indicating that it should be found in a product directory.

For example, if the module is: ACMEWidgets.foo, then an attempt will first be made to use the file lib/python/Products/ACMEWidgets/Extensions/foo.py. If this failes, then the file Extensions/ACMEWidgets.foo.py will be used.

module File

class File(ObjectManagerItem, PropertyManager)

A File is a Zope object that contains file content. A File object can be used to upload or download file information with Zope.

Anonymous User - Dec. 27, 2002 8:33 pm:
 Is there a way to use Python and XML-RPC to create a Page Template? The closest I can get is
 manage_addFile(); this adds a file, but it's not quite a template. I can't find a manage_addTemplate(). I
 want to programmatically add template objects to my site.

Using a File object in Zope is easy. The most common usage is to display the contents of a file object in a web page. This is done by simply referencing the object from DTML:


<dtml-var standard_html_header>
  <dtml-var FileObject>
<dtml-var standard_html_footer>

A more complex example is presenting the File object for download by the user. The next example displays a link to every File object in a folder for the user to download:


<dtml-var standard_html_header>
<ul>
  <dtml-in "ObjectValues('File')">
    <li><a href="<dtml-var absolute_url>"><dtml-var
    id></a></li>
  </dtml-in>
</ul>
<dtml-var standard_html_footer>
rich - Oct. 13, 2002 7:07 am:
 "ObjectValues" should be "objectValues".

In this example, the absolute_url method and id are used to create a list of HTML hyperlinks to all of the File objects in the current Object Manager.

Also see ObjectManager for details on the objectValues method.

getContentType()

Returns the content type of the file.

Permission
View

update_data(data, content_type=None, size=None)

Updates the contents of the File with data.

Anonymous User - Oct. 1, 2002 1:53 pm:
 I have examined the coed for this method and I don't see how it works: there seems to be no variable data
 that is local to each file. Thus 'self.data' can not be set if it doesn't exist. I have tested this method
 thoroughly and It does not do anything!

The data argument must be a string. If content_type is not provided, then a content type will not be set. If size is not provided, the size of the file will be computed from data.

Anonymous User - Oct. 1, 2002 1:58 pm:
 I made the above comment and I apologize. My external method had nothing to return, but without a return
 staement update_data was not executed. Thus, it does work!

Permission
Python only

getSize()

Returns the size of the file in bytes.

Permission
View

ObjectManager Constructor

manage_addFile(id, file="", title="", precondition="", content_type="")

Add a new File object.

Creates a new File object id with the contents of file
Anonymous User - June 23, 2002 12:37 am:
 can you use this to overwrite and existing file?
 the update object doesn't seem to be able to change the title, just the data of the file

module Folder

class Folder(ObjectManagerItem, ObjectManager, PropertyManager)

A Folder is a generic container object in Zope.

Folders are the most common ObjectManager subclass in Zope.

ObjectManager Constructor

manage_addFolder(id, title)

Add a Folder to the current ObjectManager

Permission
Add Folders

module Image

class Image(File)

An Image is a Zope object that contains image content. An Image object can be used to upload or download image information with Zope.

Image objects have two properties the define their dimension, height and width. These are calculated when the image is uploaded. For image types that Zope does not understand, these properties may be undefined.

Using a Image object in Zope is easy. The most common usage is to display the contents of an image object in a web page. This is done by simply referencing the object from DTML:


<dtml-var standard_html_header>
  <dtml-var ImageObject>
<dtml-var standard_html_footer>

This will generate an HTML IMG tag referencing the URL to the Image. This is equivalent to:


<dtml-var standard_html_header>
  <dtml-with ImageObject>
    <img src="<dtml-var absolute_url>">
  </dtml-with>
<dtml-var standard_html_footer>

You can control the image display more precisely with the tag method. For example:


<dtml-var "ImageObject.tag(border='5', align='left')">

tag(height=None, width=None, alt=None, scale=0, xscale=0, yscale=0, **args)

This method returns a string which contains an HTML IMG tag reference to the image.

Optionally, the height, width, alt, scale, xscale and yscale arguments can be provided which are turned into HTML IMG tag attributes. Note, height and width are provided by default, and alt comes from the title_or_id method.

Keyword arguments may be provided to support other or future IMG tag attributes. The one exception to this is the HTML Cascading Style Sheet tag class. Because the word class is a reserved keyword in Python, you must instead use the keyword argument css_class. This will be turned into a class HTML tag attribute on the rendered img tag.

Permission
View

ObjectManager Constructor

manage_addImage(id, file, title="", precondition="", content_type="")

Add a new Image object.

Creates a new Image object id with the contents of file.

module MailHost

class MailHost

MailHost objects work as adapters to Simple Mail Transfer Protocol (SMTP) servers. MailHosts are used by DTML sendmail tags to find the proper host to deliver mail to.

send(messageText, mto=None, mfrom=None, subject=None, encode=None)

Sends an email message. The arguments are:

messageText
The body of the mail message.

mto
A string or list of recipient(s) of the message.

mfrom
The address of the message sender.

subject
The subject of the message.

encode
The rfc822 defined encoding of the message. The default of None means no encoding is done. Valid values are base64, quoted-printable and uuencode.

Anonymous User - July 29, 2002 1:42 pm:
 typo: change ObjectManager constructor below to MailHost constructor.

ObjectManager Constructor

manage_addMailHost(id, title="", smtp_host=None, localhost=localhost, smtp_port=25, timeout=1.0)

Add a mailhost object to an ObjectManager.

module ObjectManager

class ObjectManager

An ObjectManager contains other Zope objects. The contained objects are Object Manager Items.

ajung - June 20, 2002 8:39 am:
 why are the manage_* () functions missing?
 people are asking how to delete an object from the objectmanager
 and there is no documentation here.
Anonymous User - July 21, 2002 12:33 am:
 For anyone who is actually trying to figure out how to delete an object, refer to...
 http://www.zope.org/Members/Mammux/removeZClasses
xqvverty - Sep. 13, 2002 9:53 pm:
 If somone wants to delete a file, use this:

 <dtml-call "manage_delObjects('ObjectName')">

 The explanation of this instruction should be in this section of the manual.
Anonymous User - Oct. 3, 2002 4:32 am:
Here here! In fact a proper "API documentation" should include ALL methods, functions, constructors available
- just to know the method names and argument types would help! I have spent nearly an hour trying to find the
 syntax for deleting objects from Zope. Very annoying!

To create an object inside an object manager use 'manage_addProduct':


self.manage_addProduct['OFSP'].manage_addFolder(id, title)
Anonymous User - June 13, 2002 4:37 pm:
 what is OFSP??????
 explanation would help here...
Anonymous User - Dec. 1, 2002 6:03 pm:
 I'd second that, it seems to be used in an awefuly lot of stuff and looks to be very important but the book
 doesn't seem to mention it.

In DTML this would be:


<dtml-call "manage_addProduct['OFSP'].manage_addFolder(id, title)">

These examples create a new Folder inside the current ObjectManager.

manage_addProduct is a mapping that provides access to product constructor methods. It is indexed by product id.

Constructor methods are registered during product initialization and should be documented in the API docs for each addable object.

objectItems(type=None)

This method returns a sequence of (id, object) tuples.

Like objectValues and objectIds, it accepts one argument, either a string or a list to restrict the results to objects of a given meta_type or set of meta_types.

Each tuple's first element is the id of an object contained in the Object Manager, and the second element is the object itself.

Example:


<dtml-in objectItems>
 id: <dtml-var sequence-key>,
 type: <dtml-var meta_type>
<dtml-else>
  There are no sub-objects.
</dtml-in>

Permission
Access contents information

superValues(type)

This method returns a list of objects of a given meta_type(es) contained in the Object Manager and all its parent Object Managers.

The type argument specifies the meta_type(es). It can be a string specifying one meta_type, or it can be a list of strings to specify many.

Permission
Python only

objectValues(type=None)

This method returns a sequence of contained objects.

Like objectItems and objectIds, it accepts one argument, either a string or a list to restrict the results to objects of a given meta_type or set of meta_types.

Example:


<dtml-in expr="objectValues('Folder')">
  <dtml-var icon>
  This is the icon for the: <dtml-var id> Folder<br>.
<dtml-else>
  There are no Folders.
</dtml-in>
Anonymous User - July 17, 2002 9:30 pm:
The above sample illustrates how to pass a meta_type to the objectValues method. But how do you pass a set of
 meta_types to objectValues method?
Anonymous User - July 17, 2002 9:40 pm:
 Use list to specify a set of meta_types, try this:
 <dtml-in expr="objectValues(['File','Folder'])">
 ...
 </dtml-in>

The results were restricted to Folders by passing a meta_type to objectValues method.

Permission
Access contents information

objectIds(type=None)

This method returns a list of the ids of the contained objects.

Optionally, you can pass an argument specifying what object meta_type(es) to restrict the results to. This argument can be a string specifying one meta_type, or it can be a list of strings to specify many.

Example:


<dtml-in objectIds>
  <dtml-var sequence-item>
<dtml-else>
  There are no sub-objects.
</dtml-in>

This DTML code will display all the ids of the objects contained in the current Object Manager.

Permission
Access contents information

module ObjectManagerItem

class ObjectManagerItem

A Zope object that can be contained within an Object Manager. Almost all Zope objects that can be managed through the web are Object Manager Items.

ObjectMangerItems have these instance attributes:

title
The title of the object.

This is an optional one-line string description of the object.

meta_type
A short name for the type of the object.

This is the name that shows up in product add list for the object and is used when filtering objects by type.

This attribute is provided by the object's class and should not be changed directly.

REQUEST
The current web request.

This object is acquired and should not be set.

title_or_id()

If the title is not blank, return it, otherwise return the id.

Permission
Always available

getPhysicalRoot()

Returns the top-level Zope Application object.

Permission
Python only

manage_workspace()

This is the web method that is called when a user selects an item in a object manager contents view or in the Zope Management navigation view.

Permission
View management screens

getPhysicalPath()

Get the path of an object from the root, ignoring virtual hosts.

Permission
Always available

unrestrictedTraverse(path, default=None)

Return the object obtained by traversing the given path from the object on which the method was called. This method begins with "unrestricted" because (almost) no security checks are performed.

If an object is not found then the default argument will be returned.

Permission
Python only

getId()

Returns the object's id.

The id is the unique name of the object within its parent object manager. This should be a string, and can contain letters, digits, underscores, dashes, commas, and spaces.

This method replaces direct access to the id attribute.

Permission
Always available

absolute_url(relative=None)

Return the absolute url to the object.

If the relative argument is provided with a true value, then the URL returned is relative to the site object. Note, if virtual hosts are being used, then the path returned is a logical, rather than a physical path.

Permission
Always available

this()

Return the object.

This turns out to be handy in two situations. First, it provides a way to refer to an object in DTML expressions.

The second use for this is rather deep. It provides a way to acquire an object without getting the full context that it was acquired from. This is useful, for example, in cases where you are in a method of a non-item subobject of an item and you need to get the item outside of the context of the subobject.

Anonymous User - Sep. 19, 2002 1:37 pm:
 What does this last sentence even mean?  What is the difference between an item and a non-item?

Permission
Always available

restrictedTraverse(path, default=None)

Return the object obtained by traversing the given path from the object on which the method was called, performing security checks along the way.

Anonymous User - Sep. 19, 2002 1:34 pm:
What is the path supposed to look like? I have tried every path relating to a given object to no avail.
Should
 the path be relative to the object or relative to the root?
Anonymous User - Sep. 19, 2002 1:39 pm:
 How can I traverse a path? Is there any way to traverse through containers and thier
 subcontainers/subobjects?

If an object is not found then the default argument will be returned.

Permission
Always available

title_and_id()

If the title is not blank, the return the title followed by the id in parentheses. Otherwise return the id.

Anonymous User - May 14, 2002 11:02 pm:
 TYPO: 'then' return the title

Permission
Always available

module PropertyManager

class PropertyManager

A Property Manager object has a collection of typed attributes called properties. Properties can be managed through the web or via DTML.

In addition to having a type, properties can be writable or read-only and can have default values.

propertyItems()

Return a list of (id, property) tuples.

Permission
Access contents information

propertyValues()

Returns a list of property values.

Permission
Access contents information

propertyMap()

Returns a tuple of mappings, giving meta-data for properties. The meta-data includes id, type, and mode.

Permission
Access contents information

propertyIds()

Returns a list of property ids.

Permission
Access contents information

getPropertyType(id)

Get the type of property id. Returns None if no such property exists.

Permission
Access contents information

getProperty(id, d=None)

Return the value of the property id. If the property is not found the optional second argument or None is returned.

Permission
Access contents information

hasProperty(id)

Returns a true value if the Property Manager has the property id. Otherwise returns a false value.

Permission
Access contents information

module PropertySheet

class PropertySheet

A PropertySheet is an abstraction for organizing and working with a set of related properties. Conceptually it acts like a container for a set of related properties and meta-data describing those properties. A PropertySheet may or may not provide a web interface for managing its properties.

xml_namespace()

Return a namespace string usable as an xml namespace for this property set. This may be an empty string if there is no default namespace for a given property sheet (especially property sheets added in ZClass definitions).

Permission
Python only

propertyItems()

Return a list of (id, property) tuples.

Permission
Access contents information

propertyValues()

Returns a list of actual property values.

Permission
Access contents information

getPropertyType(id)

Get the type of property id. Returns None if no such property exists.

Anonymous User - May 22, 2002 7:25 am:
 For ZClasses:

 use as: context.propertysheets.propertysheetname.propertyItems() in Python scripts and as: <dtml-var
 "propertysheets.propertysheetname.propertyItems()"> in DTML, where propertysheetname is the name of the
 property sheet you've defined in the ZClass.

Permission
Python only

propertyInfo()

Returns a mapping containing property meta-data.

Permission
Python only

getProperty(id, d=None)

Get the property id, returning the optional second argument or None if no such property is found.

Permission
Python only

manage_delProperties(ids=None, REQUEST=None)

Delete one or more properties with the given ids. The ids argument should be a sequence (tuple or list) containing the ids of the properties to be deleted. If ids is empty no action will be taken. If any of the properties named in ids does not exist, an error will be raised.

Some objects have "special" properties defined by product authors that cannot be deleted. If one of these properties is named in ids, an HTML error message is returned.

If no value is passed in for REQUEST, the method will return None. If a value is provided for REQUEST (as it will be when called via the web), the property management form for the object will be rendered and returned.

This method may be called via the web, from DTML or from Python code.

Permission
Manage Properties

manage_changeProperties(REQUEST=None, **kw)

Change existing object properties by passing either a mapping object as REQUEST containing name:value pairs or by passing name=value keyword arguments.

Some objects have "special" properties defined by product authors that cannot be changed. If you try to change one of these properties through this method, an error will be raised.

Note that no type checking or conversion happens when this method is called, so it is the caller's responsibility to ensure that the updated values are of the correct type. This should probably change.

If a value is provided for REQUEST (as it will be when called via the web), the method will return an HTML message dialog. If no REQUEST is passed, the method returns None on success.

This method may be called via the web, from DTML or from Python code.

Permission
Manage Properties

manage_addProperty(id, value, type, REQUEST=None)

Add a new property with the given id, value and type.

These are the property types:

boolean
1 or 0.

date
A DateTime value, for example 12/31/1999 15:42:52 PST.

float
A decimal number, for example 12.4.

int
An integer number, for example, 12.

lines
A list of strings, one per line.

long
A long integer, for example 12232322322323232323423.

string
A string of characters, for example This is a string.

text
A multi-line string, for example a paragraph.

tokens
A list of strings separated by white space, for example one two three.

selection
A string selected by a pop-up menu.

multiple selection
A list of strings selected by a selection list.

This method will use the passed in type to try to convert the value argument to the named type. If the given value cannot be converted, a ValueError will be raised.

The value given for selection and multiple selection properites may be an attribute or method name. The attribute or method must return a sequence values.

If the given type is not recognized, the value and type given are simply stored blindly by the object.

If no value is passed in for REQUEST, the method will return None. If a value is provided for REQUEST (as it will when called via the web), the property management form for the object will be rendered and returned.

This method may be called via the web, from DTML or from Python code.

Permission
Manage Properties

propertyMap()

Returns a tuple of mappings, giving meta-data for properties.

Permssion
Python only

propertyIds()

Returns a list of property ids.

Permission
Access contents information

hasProperty(id)

Returns true if self has a property with the given id, false otherwise.

Permission
Access contents information

module PropertySheets

class PropertySheets

A PropertySheet is an abstraction for organizing and working with a set of related properties. Conceptually it acts like a container for a set of related properties and meta-data describing those properties. PropertySheet objects are accessed through a PropertySheets object that acts as a collection of PropertySheet instances.

Objects that support property sheets (objects that support the PropertyManager interface or ZClass objects) have a propertysheets attribute (a PropertySheets instance) that is the collection of PropertySheet objects. The PropertySheets object exposes an interface much like a Python mapping, so that individual PropertySheet objects may be accessed via dictionary-style key indexing.

get(name, default=None)

Return the PropertySheet identified by name, or the value given in default if the named PropertySheet is not found.

Permission
Python only

values()

Return a sequence of all of the PropertySheet objects in the collection.

Permission
Python only

items()

Return a sequence containing an (id, object) tuple for each PropertySheet object in the collection.

Permission
Python only

module PythonScript

class PythonScript(Script)

Python Scripts contain python code that gets executed when you call the script by:

  • Calling the script through the web by going to its location with a web browser.
  • Calling the script from another script object.
  • Calling the script from a method object, such as a DTML Method.

Python Scripts can contain a "safe" subset of the python language. Python Scripts must be safe because they can be potentially edited by many different users through an insecure medium like the web. The following safety issues drive the need for secure Python Scripts:

  • Because many users can use Zope, a Python Script must make sure it does not allow a user to do something they are not allowed to do, like deleting an object they do not have permission to delete. Because of this requirement, Python Scripts do many security checks in the course of their execution.
  • Because Python Scripts can be edited through the insecure medium of the web, they are not allowed access to the Zope server's file-system. Normal Python builtins like open are, therefore, not allowed.
  • Because many standard Python modules break the above two security restrictions, only a small subset of Python modules may be imported into a Python Scripts with the "import" statement unless they have been validated by Zope's security policy. Currently, the following standard python modules have been validated:
    • string
    • math
    • whrandom and random
    • Products.PythonScripts.standard
  • Because it allows you to execute arbitrary python code, the python "exec" statement is not allowed in Python methods.
  • Because they may represent or cause security violations, some Python builtin functions are not allowed. The following Python builtins are not allowed:
    • open
    • input
    • raw_input
    • eval
    • execfile
    • compile
    • type
    • coerce
    • intern
    • dir
    • globals
    • locals
    • vars
    • buffer
    • reduce
  • Other builtins are restricted in nature. The following builtins are restricted:
    range
    Due to possible memory denial of service attacks, the range builtin is restricted to creating ranges less than 10,000 elements long.
    filter, map, tuple, list
    For the same reason, builtins that construct lists from sequences do not operate on strings.
    getattr, setattr, delattr
    Because these may enable Python code to circumvent Zope's security system, they are replaced with custom, security constrained versions.
  • In order to be consistent with the Python expressions available to DTML, the builtin functions are augmented with a small number of functions and a class:
    • test
    • namespace
    • render
    • same_type
    • DateTime
  • Because the "print" statement cannot operate normally in Zope, its effect has been changed. Rather than sending text to stdout, "print" appends to an internal variable. The special builtin name "printed" evaluates to the concatenation of all text printed so far during the current execution of the script.

Anonymous User - Sep. 23, 2002 12:14 pm:
 What about the python function "id"? It seems to be restricted to.

document_src(REQUEST=None, RESPONSE=None)

Return the text of the read method, with content type text/plain set on the RESPONSE.

ZPythonScript_edit(params, body)

Change the parameters and body of the script. This method accepts two arguments:

params
The new value of the Python Script's parameters. Must be a comma seperated list of values in valid python function signature syntax. If it does not contain a valid signature string, a SyntaxError is raised.

body
The new value of the Python Script's body. Must contain valid Python syntax. If it does not contain valid Python syntax, a SyntaxError is raised.

ZPythonScript_setTitle(title)

Change the script's title. This method accepts one argument, title which is the new value for the script's title and must be a string.

ZPythonScriptHTML_upload(REQUEST, file="")

Pass the text in file to the write method.

write(text)

Change the script by parsing the text argument into parts. Leading lines that begin with ## are stripped off, and if they are of the form ##name=value, they are used to set meta-data such as the title and parameters. The remainder of the text is set as the body of the Python Script.

ZScriptHTML_tryParams()

Return a list of the required parameters with which to test the script.

read()

Return the body of the Python Script, with a special comment block prepended. This block contains meta-data in the form of comment lines as expected by the write method.

ZPythonScriptHTML_editAction(REQUEST, title, params, body)

Change the script's main parameters. This method accepts the following arguments:

REQUEST
The current request.

title
The new value of the Python Script's title. This must be a string.

params
The new value of the Python Script's parameters. Must be a comma seperated list of values in valid python function signature syntax. If it does not contain a valid signature string, a SyntaxError is raised.

body
The new value of the Python Script's body. Must contain valid Python syntax. If it does not contain valid Python syntax, a SyntaxError is raised.

ObjectManager Constructor

manage_addPythonScript(id, REQUEST=None)

Add a Python script to a folder.

module Request

class Request

The request object encapsulates all of the information regarding the current request in Zope. This includes, the input headers, form data, server data, and cookies.

The request object is a mapping object that represents a collection of variable to value mappings. In addition, variables are divided into five categories:

  • Environment variables

    These variables include input headers, server data, and other request-related data. The variable names are as specified in the CGI specification

  • Form data

    These are data extracted from either a URL-encoded query string or body, if present.

    Anonymous User - Aug. 29, 2002 12:26 pm:
     How can we access the form subobject content (within the REQUEST object) from DTML?
    
    Anonymous User - Nov. 29, 2002 6:03 am:
     form suboject meaning form fields??(in which case <dtml-var "REQUEST.form.keys()" >)
    

  • Cookies

    These are the cookie data, if present.

  • Lazy Data

    These are callables which are deferred until explicitly referenced, at which point they are resolved (called) and the result stored as "other" data, ie regular request data.

    Thus, they are "lazy" data items. An example is SESSION objects.

    Lazy data in the request may only be set by the Python method set_lazy(name,callable) on the REQUEST object. This method is not callable from DTML or through the web.

  • Other

    Data that may be set by an application object.

The request object may be used as a mapping object, in which case values will be looked up in the order: environment variables, other variables, form data, and then cookies.

These special variables are set in the Request:

PARENTS
A list of the objects traversed to get to the published object. So, PARENTS[0] would be the ancestor of the published object.

REQUEST
The Request object.

RESPONSE
The Response object.

PUBLISHED
The actual object published as a result of url traversal.

URL
The URL of the Request without query string.

URLn
URL0 is the same as URL. URL1 is the same as URL0 with the last path element removed. URL2 is the same as URL1 with the last element removed. Etcetera.

For example if URL=http://localhost/foo/bar, then URL1=http://localhost/foo and URL2=http://localhost.

URLPATHn
URLPATH0 is the path portion of URL, URLPATH1 is the path portion of URL1, and so on.

For example if URL=http://localhost/foo/bar, then URLPATH1=/foo and URLPATH2=/.

BASEn
BASE0 is the URL up to but not including the Zope application object. BASE1 is the URL of the Zope application object. BASE2 is the URL of the Zope application object with an additional path element added in the path to the published object. Etcetera.

For example if URL=http://localhost/Zope.cgi/foo/bar, then BASE0=http://localhost, BASE1=http://localhost/Zope.cgi, and BASE2=http://localhost/Zope.cgi/foo.

BASEPATHn
BASEPATH0 is the path portion of BASE0, BASEPATH1 is the path portion of BASE1, and so on. BASEPATH1 is the externally visible path to the root Zope folder, equivalent to CGI's SCRIPT_NAME, but virtual-host aware.

For example if URL=http://localhost/Zope.cgi/foo/bar, then BASEPATH0='/, BASEPATH1=/Zope.cgi', and BASEPATH2=/Zope.cgi/foo.

Anonymous User - May 6, 2002 8:30 am:
 compared to what i know or see with dtml-var REQUEST,
 this list is incomplete, if not very, very sparse
 at least a ref to a complete list would be ok

get_header(name, default=None)

Return the named HTTP header, or an optional default argument or None if the header is not found. Note that both original and CGI header names without the leading HTTP_ are recognized, for example, Content-Type, CONTENT_TYPE and HTTP_CONTENT_TYPE should all return the Content-Type header, if available.

Permission
Always available

items()

Returns a sequence of (key, value) tuples for all the keys in the REQUEST object.

Permission
Always available

keys()

Returns a sorted sequence of all keys in the REQUEST object.

Permission
Always available

setVirtualRoot(path, hard=0)

Alters URL, URLn, URLPATHn, BASEn, BASEPATHn, and absolute_url() so that the current object has path path. If hard is true, PARENTS is emptied.

Provides virtual hosting support. Intended to be called from publishing traversal hooks.

Permission
Always available

values()

Returns a sequence of values for all the keys in the REQUEST object.

Permission
Always available

set(name, value)

Create a new name in the REQUEST object and assign it a value. This name and value is stored in the Other category.

Anonymous User - Sep. 27, 2002 5:07 pm:
 get(name, defaultvalue) ??
Anonymous User - Jan. 5, 2003 4:29 am:
 No, get(name)

Permission
Always available

has_key(key)

Returns a true value if the REQUEST object contains key, returns a false value otherwise.

Permission
Always available

setServerURL(protocol=None, hostname=None, port=None)

Sets the specified elements of SERVER_URL, also affecting URL, URLn, BASEn, and absolute_url().

Provides virtual hosting support.

Permission
Always available

module Response

class Response

The Response object represents the response to a Zope request.

setHeader(name, value)

Sets an HTTP return header "name" with value "value", clearing the previous value set for the header, if one exists. If the literal flag is true, the case of the header name is preserved, otherwise word-capitalization will be performed on the header name on output.

Permission
Always available

setCookie(name, value, **kw)

Set an HTTP cookie on the browser

The response will include an HTTP header that sets a cookie on cookie-enabled browsers with a key "name" and value "value". This overwrites any previously set value for the cookie in the Response object.

Anonymous User - May 1, 2002 6:59 am:
great, but where is the getCookie method? In particular how do I force it to look for a key in the cookie, as
 opposed to the headers or elsewhere?
Anonymous User - May 7, 2002 7:29 pm:
 apparently you may reference cookies like any other dtml variable, but within dtml. still trying to figure
 out how to reference dtml variables within python
Anonymous User - May 30, 2002 5:09 pm:
 You *get* cookies from the REQUEST, not the RESPONSE.
Anonymous User - June 14, 2002 12:48 pm:
 To reference a dtml variable called 'test', within python:
 request = container.REQUEST
 RESPONSE =  request.RESPONSE
 test = request.test
Anonymous User - Sep. 12, 2002 1:50 pm:
 There are many examples in Zope using a 'path' parameter for setCookie. Is this a valid parameter and if so,
 what is it for?
jmunoz - Oct. 18, 2002 1:27 pm:
 What is the usage of the keyword arguments ?

Permission
Always available

addHeader(name, value)

Set a new HTTP return header with the given value, while retaining any previously set headers with the same name.

Permission
Always available

appendHeader(name, value, delimiter=,)

Append a value to a cookie

Sets an HTTP return header "name" with value "value", appending it following a comma if there was a previous value set for the header.

Brian - June 13, 2002 9:43 am:
 This should read "append value to header", not cookie. -BL

Permission
Always available

write(data)

Return data as a stream

HTML data may be returned using a stream-oriented interface. This allows the browser to display partial results while computation of a response to proceed.

The published object should first set any output headers or cookies on the response object.

Note that published objects must not generate any errors after beginning stream-oriented output.

Permission
Always available

setStatus(status, reason=None)

Sets the HTTP status code of the response; the argument may either be an integer or one of the following strings:

OK, Created, Accepted, NoContent, MovedPermanently, MovedTemporarily, NotModified, BadRequest, Unauthorized, Forbidden, NotFound, InternalError, NotImplemented, BadGateway, ServiceUnavailable

that will be converted to the correct integer value.

Permission
Always available

setBase(base)

Set the base URL for the returned document.

Permission
Always available

expireCookie(name, **kw)

Cause an HTTP cookie to be removed from the browser

The response will include an HTTP header that will remove the cookie corresponding to "name" on the client, if one exists. This is accomplished by sending a new cookie with an expiration date that has already passed. Note that some clients require a path to be specified - this path must exactly match the path given when creating the cookie. The path can be specified as a keyword argument.

jmunoz - Oct. 18, 2002 1:28 pm:
 "The path can be specified as a keyword argument"

 How ?
jmunoz - Oct. 18, 2002 1:36 pm:
 Looking the sources..

 Example in DTML:

 <dtml-call expr="RESPONSE.expireCookie('__ac_user', path='/')">

Permission
Always available

appendCookie(name, value)

Returns an HTTP header that sets a cookie on cookie-enabled browsers with a key "name" and value "value". If a value for the cookie has previously been set in the response object, the new value is appended to the old one separated by a colon.

Permission
Always available

redirect(location, lock=0)

Cause a redirection without raising an error. If the "lock" keyword argument is passed with a true value, then the HTTP redirect response code will not be changed even if an error occurs later in request processing (after redirect() has been called).

Permission
Always available

module

Script

Script module

This provides generic script support

class Script

Web-callable script base interface.

ZScriptHTML_tryAction(REQUEST, argvars)

Apply the test parameters provided by the dictionary argvars. This will call the current script with the given arguments and return the result.

module SessionInterfaces

Session API

See Also

class SessionDataManagerErr

Error raised during some session data manager operations, as explained in the API documentation of the Session Data Manager.

Anonymous User - July 17, 2002 5:24 am:
 Transient Object API link above is broken!
Anonymous User - Oct. 10, 2002 10:37 am:
 Still broken!
Anonymous User - Nov. 26, 2002 4:48 am:
 the link is broken the link is broken ...

This exception may be caught in PythonScripts. A successful import of the exception for PythonScript use would need to be:


from Products.Sessions import SessionDataManagerErr

class BrowserIdManagerInterface

Zope Browser Id Manager interface.

A Zope Browser Id Manager is responsible for assigning ids to site visitors, and for servicing requests from Session Data Managers related to the browser id.

getBrowserId(self, create=1)

If create=0, returns a the current browser id or None if there is no browser id associated with the current request. If create=1, returns the current browser id or a newly-created browser id if there is no browser id associated with the current request. This method is useful in conjunction with getBrowserIdName if you wish to embed the browser-id-name/browser-id combination as a hidden value in a POST-based form. The browser id is opaque, has no business meaning, and its length, type, and composition are subject to change.

Permission required: Access contents information

Raises: BrowserIdManagerErr if ill-formed browser id is found in REQUEST.

isBrowserIdFromCookie(self)

Returns true if browser id comes from a cookie.

Permission required: Access contents information

Raises: BrowserIdManagerErr. If there is no current browser id.

isBrowserIdNew(self)

Returns true if browser id is new. A browser id is new when it is first created and the client has therefore not sent it back to the server in any request.

Permission required: Access contents information

Raises: BrowserIdManagerErr. If there is no current browser id.

encodeUrl(self, url)

Encodes a provided URL with the current request's browser id and returns the result. For example, the call encodeUrl(http://foo.com/amethod) might return http://foo.com/amethod?_ZopeId=as9dfu0adfu0ad.

Permission required: Access contents information

Raises: BrowserIdManagerErr. If there is no current browser id.

flushBrowserIdCookie(self)

Deletes the browser id cookie from the client browser, iff the cookies browser id namespace is being used.

Permission required: Access contents information

Raises: BrowserIdManagerErr. If the cookies namespace isn't a browser id namespace at the time of the call.

getBrowserIdName(self)

Returns a string with the name of the cookie/form variable which is used by the current browser id manager as the name to look up when attempting to obtain the browser id value. For example, _ZopeId.

Permission required: Access contents information

isBrowserIdFromForm(self)

Returns true if browser id comes from a form variable (query string or post).

Permission required: Access contents information

Raises: BrowserIdManagerErr. If there is no current browser id.

hasBrowserId(self)

Returns true if there is a browser id for this request.

Permission required: Access contents information

setBrowserIdCookieByForce(self, bid)

Sets the browser id cookie to browser id bid by force. Useful when you need to chain browser id cookies across domains for the same user (perhaps temporarily using query strings).

Permission required: Access contents information

Raises: BrowserIdManagerErr. If the cookies namespace isn't a browser id namespace at the time of the call.

class BrowserIdManagerErr

Error raised during some browser id manager operations, as explained in the API documentation of the Browser Id Manager.

This exception may be caught in PythonScripts. A successful import of the exception for PythonScript use would need to be:


from Products.Sessions import BrowserIdManagerErr

class SessionDataManagerInterface

Zope Session Data Manager interface.

A Zope Session Data Manager is responsible for maintaining Session Data Objects, and for servicing requests from application code related to Session Data Objects. It also communicates with a Browser Id Manager to provide information about browser ids.

getSessionDataByKey(self, key)

Returns a Session Data Object associated with key. If there is no Session Data Object associated with key return None.

Permission required: Access arbitrary user session data

getSessionData(self, create=1)

Returns a Session Data Object associated with the current browser id. If there is no current browser id, and create is true, returns a new Session Data Object. If there is no current browser id and create is false, returns None.

Permission required: Access session data

getBrowserIdManager(self)

Returns the nearest acquirable browser id manager.

Raises SessionDataManagerErr if no browser id manager can be found.

Permission required: Access session data

hasSessionData(self)

Returns true if a Session Data Object associated with the current browser id is found in the Session Data Container. Does not create a Session Data Object if one does not exist.

Permission required: Access session data

module TransienceInterfaces

Transient Objects

class TransientObject

A transient object is a temporary object contained in a transient object container.

Most of the time you'll simply treat a transient object as a dictionary. You can use Python sub-item notation:


SESSION['foo']=1
foo=SESSION['foo']
del SESSION['foo']

When using a transient object from Python-based Scripts or DTML you can use the get, set, and delete methods instead.

Methods of transient objects are not protected by security assertions.

Anonymous User - Aug. 13, 2002 7:15 am:
 Please explain.

It's necessary to reassign mutuable sub-items when you change them. For example:


l=SESSION['myList']
l.append('spam')
SESSION['myList']=l

This is necessary in order to save your changes. Note that this caveat is true even for mutable subitems which inherit from the Persistence.Persistent class.

delete(self, k)

Call __delitem__ with key k.

Permission
Always available

setLastAccessed(self)

Cause the last accessed time to be set to now.

Permission
Always available

getCreated(self)

Return the time the transient object was created in integer seconds-since-the-epoch form.

Permission
Always available

values(self)

Return sequence of value elements.

Permission
Always available

has_key(self, k)

Return true if item referenced by key k exists.

Permission
Always available

getLastAccessed(self)

Return the time the transient object was last accessed in integer seconds-since-the-epoch form.

Permission
Always available

getId(self)

Returns a meaningful unique id for the object.

Permission
Always available

update(self, d)

Merge dictionary d into ourselves.

Permission
Always available

clear(self)

Remove all key/value pairs.

Permission
Always available

items(self)

Return sequence of (key, value) elements.

Permission
Always available

keys(self)

Return sequence of key elements.

Permission
Always available

get(self, k, default=marker)

Return value associated with key k. If k does not exist and default is not marker, return default, else raise KeyError.

Permission
Always available

set(self, k, v)

Call __setitem__ with key k, value v.

Permission
Always available

getContainerKey(self)

Returns the key under which the object is "filed" in its container. getContainerKey will often return a differnt value than the value returned by getId.

Permission
Always available

invalidate(self)

Invalidate (expire) the transient object.

Causes the transient object container's "before destruct" method related to this object to be called as a side effect.

Permission
Always available

class MaxTransientObjectsExceeded

An exception importable from the Products.Transience.Transience module which is raised when an attempt is made to add an item to a TransientObjectContainer that is full.

This exception may be caught in PythonScripts through a normal import. A successful import of the exception can be achieved via:


from Products.Transience import MaxTransientObjectsExceeded

class TransientObjectContainer

TransientObjectContainers hold transient objects, most often, session data.

You will rarely have to script a transient object container. You'll almost always deal with a TransientObject itself which you'll usually get as REQUEST.SESSION.

new(self, k)

Creates a new subobject of the type supported by this container with key "k" and returns it.

If an object already exists in the container with key "k", a KeyError is raised.

"k" must be a string, else a TypeError is raised.

If the container is full, a MaxTransientObjectsExceeded will be raised.

Permission
Create Transient Objects

setDelNotificationTarget(self, f)

Cause the before destruction function to be f.

If f is not callable and is a string, treat it as a Zope path to a callable function.

before destruction functions need accept a single argument: item, which is the item being destroyed.

Permission
Manage Transient Object Container

getTimeoutMinutes(self)

Return the number of minutes allowed for subobject inactivity before expiration.

Permission
View management screens

has_key(self, k)

Return true if container has value associated with key k, else return false.

Permission
Access Transient Objects

setAddNotificationTarget(self, f)

Cause the after add function to be f.

If f is not callable and is a string, treat it as a Zope path to a callable function.

after add functions need accept a single argument: item, which is the item being added to the container.

Permission
Manage Transient Object Container

getId(self)

Returns a meaningful unique id for the object.

Permission
Always available

setTimeoutMinutes(self, timeout_mins)

Set the number of minutes of inactivity allowable for subobjects before they expire.

Permission
Manage Transient Object Container

new_or_existing(self, k)

If an object already exists in the container with key "k", it is returned.

Otherwiser, create a new subobject of the type supported by this container with key "k" and return it.

"k" must be a string, else a TypeError is raised.

If the container is full, a MaxTransientObjectsExceeded exception be raised.

Permission
Create Transient Objects

get(self, k, default=None)

Return value associated with key k. If value associated with k does not exist, return default.

Permission
Access Transient Objects

getAddNotificationTarget(self)

Returns the current after add function, or None.

Permission
View management screens

getDelNotificationTarget(self)

Returns the current before destruction function, or None.

Permission
View management screens

module UserFolder

class UserFolder

User Folder objects are containers for user objects. Programmers can work with collections of user objects using the API shared by User Folder implementations.

userFolderEditUser(name, password, roles, domains, **kw)

API method for changing user object attributes. Note that not all user folder implementations support changing of user object attributes. Implementations that do not support changing of user object attributes will raise an error for this method.

Permission
Manage users

userFolderDelUsers(names)

API method for deleting one or more user objects. Note that not all user folder implementations support deletion of user objects. Implementations that do not support deletion of user objects will raise an error for this method.

Permission
Manage users

userFolderAddUser(name, password, roles, domains, **kw)

API method for creating a new user object. Note that not all user folder implementations support dynamic creation of user objects. Implementations that do not support dynamic creation of user objects will raise an error for this method.

Anonymous User - June 4, 2002 2:09 pm:
 Please document the argument types; for example, roles must be a list  
 (e.g., '[Manager]') and not a string.  Zope will accept 'Manager' and  
 create a user, but it's an invalid entry--when you click on it, Zope  
 gives an error. 

 Also, please explain the **kw (keywords) argment.
Anonymous User - Sep. 29, 2002 5:39 pm:
 use [' '] as parameter for domains and it works. domains is of type tokens.
 somewhere in the code i found out that an empty token equals [' '] and not ['']
marko - Aug. 6, 2003 4:46 pm:
 eeeh, if i do this
 context.acl_users.userFolderAddUser(email ,wachtw ,['Authenticated', 'customer'], [' '],0)

 zope says that userfolderadduser only takes 5 arguments and 6 are given??

 i only count 5 there TBH.

 If i don't include the domain in there it seems to work, but the user can't log in!

 they get this error:

 Error Type: TypeError
 Error Value: tuple() argument must be a sequence

 I can't find any reasonable documentation for this :(

 if u know how to solve this, mail me at [email protected]

Permission
Manage users

getUsers()

Returns a sequence of all user objects which reside in the user folder.

Permission
Manage users

getUserNames()

Returns a sequence of names of the users which reside in the user folder.

Permission
Manage users

getUser(name)

Returns the user object specified by name. If there is no user named name in the user folder, return None.

Permission
Manage users

module Vocabulary

class Vocabulary

A Vocabulary manages words and language rules for text indexing. Text indexing is done by the ZCatalog and other third party Products.

words()

Return list of words.

insert(word)

Insert a word in the Vocabulary.

query(pattern)

Query Vocabulary for words matching pattern.

ObjectManager Constructor

manage_addVocabulary(id, title, globbing=None, REQUEST=None)

Add a Vocabulary object to an ObjectManager.

module ZCatalog

class ZCatalog

ZCatalog object

A ZCatalog contains arbitrary index like references to Zope objects. ZCatalog's can index either Field values of object, Text values, or KeyWord values:

ZCatalogs have three types of indexes:

Text
Text indexes index textual content. The index can be used to search for objects containing certain words.

Field
Field indexes index atomic values. The index can be used to search for objects that have certain properties.

Keyword
Keyword indexes index sequences of values. The index can be used to search for objects that match one or more of the search terms.

The ZCatalog can maintain a table of extra data about cataloged objects. This information can be used on search result pages to show information about a search result.

The meta-data table schema is used to build the schema for ZCatalog Result objects. The objects have the same attributes as the column of the meta-data table.

ZCatalog does not store references to the objects themselves, but rather to a unique identifier that defines how to get to the object. In Zope, this unique identifier is the object's relative path to the ZCatalog (since two Zope objects cannot have the same URL, this is an excellent unique qualifier in Zope).

schema()

Returns a sequence of names that correspond to columns in the meta-data table.

__call__(REQUEST=None, **kw)

Search the catalog, the same way as searchResults.

uncatalog_object(uid)

Uncatalogs the object with the unique identifier uid.

getobject(rid, REQUEST=None)

Return a cataloged object given a data_record_id_

indexes()

Returns a sequence of names that correspond to indexes.

getpath(rid)

Return the path to a cataloged object given a data_record_id_

Anonymous User - Dec. 23, 2002 6:22 pm:
 getpath is actually spelled getPath ;)

 -jj

index_objects()

Returns a sequence of actual index objects.

searchResults(REQUEST=None, **kw)

Search the catalog. Search terms can be passed in the REQUEST or as keyword arguments.

Search queries consist of a mapping of index names to search parameters. You can either pass a mapping to searchResults as the variable REQUEST or you can use index names and search parameters as keyword arguments to the method, in other words:


searchResults(title='Elvis Exposed',
              author='The Great Elvonso')

is the same as:


searchResults({'title' : 'Elvis Exposed',
               'author : 'The Great Elvonso'})
Anonymous User - Aug. 6, 2002 10:03 am:
 missing ' in "'author"

In these examples, title and author are indexes. This query will return any objects that have the title Elvis Exposed AND also are authored by The Great Elvonso. Terms that are passed as keys and values in a searchResults() call are implicitly ANDed together. To OR two search results, call searchResults() twice and add concatenate the results like this:


results = ( searchResults(title='Elvis Exposed') +
            searchResults(author='The Great Elvonso') )

This will return all objects that have the specified title OR the specified author.

There are some special index names you can pass to change the behavior of the search query:

sort_on
This parameters specifies which index to sort the results on.

sort_order
You can specify reverse or descending. Default behavior is to sort ascending.

There are some rules to consider when querying this method:

  • an empty query mapping (or a bogus REQUEST) returns all items in the catalog.
  • results from a query involving only field/keyword indexes, e.g. {'id':'foo'} and no sort_on will be returned unsorted.
  • results from a complex query involving a field/keyword index and a text index, e.g. {'id':foo,'PrincipiaSearchSource':'bar'} and no sort_on will be returned unsorted.
  • results from a simple text index query e.g.{'PrincipiaSearchSource':'foo'} will be returned sorted in descending order by score. A text index cannot beused as a sort_on parameter, and attempting to do so will raise an error.

Depending on the type of index you are querying, you may be able to provide more advanced search parameters that can specify range searches or wildcards. These features are documented in The Zope Book.

uniqueValuesFor(name)

returns the unique values for a given FieldIndex named name.

catalog_object(obj, uid)

Catalogs the object obj with the unique identifier uid.

ObjectManager Constructor

manage_addZCatalog(id, title, vocab_id=None)

Add a ZCatalog object.

vocab_id is the name of a Vocabulary object this catalog should use. A value of None will cause the Catalog to create its own private vocabulary.

module ZSQLMethod

class ZSQLMethod

ZSQLMethods abstract SQL code in Zope.

SQL Methods behave like methods of the folders they are accessed in. In particular, they can be used from other methods, like Documents, ExternalMethods, and even other SQL Methods.

Database methods support the Searchable Object Interface. Search interface wizards can be used to build user interfaces to them. They can be used in joins and unions. They provide meta-data about their input parameters and result data.

For more information, see the searchable-object interface specification.

Database methods support URL traversal to access and invoke methods on individual record objects. For example, suppose you had an employees database method that took a single argument employee_id. Suppose that employees had a service_record method (defined in a record class or acquired from a folder). The service_record method could be accessed with a URL like:


employees/employee_id/1234/service_record

Search results are returned as Record objects. The schema of a Record objects matches the schema of the table queried in the search.

manage_edit(title, connection_id, arguments, template)

Change database method properties.

The connection_id argument is the id of a database connection that resides in the current folder or in a folder above the current folder. The database should understand SQL.

The arguments argument is a string containing an arguments specification, as would be given in the SQL method creation form.

The template argument is a string containing the source for the SQL Template.

__call__(REQUEST=None, **kw)

Call the ZSQLMethod.

The arguments to the method should be passed via keyword arguments, or in a single mapping object. If no arguments are given, and if the method was invoked through the Web, then the method will try to acquire and use the Web REQUEST object as the argument mapping.

The returned value is a sequence of record objects.

ObjectManager Constructor

manage_addZSQLMethod(id, title, connection_id, arguments, template)

Add an SQL Method to an ObjectManager.

The connection_id argument is the id of a database connection that resides in the current folder or in a folder above the current folder. The database should understand SQL.

The arguments argument is a string containing an arguments specification, as would be given in the SQL method cration form.

The template argument is a string containing the source for the SQL Template.

module ZTUtils

ZTUtils: Page Template Utilities

The classes in this module are available from Page Templates.

class Batch

Batch - a section of a large sequence.

You can use batches to break up large sequences (such as search results) over several pages.

Batches provide Page Templates with similar functions as those built-in to <dtml-in>.

You can access elements of a batch just as you access elements of a list. For example:


>>> b=Batch(range(100), 10)
>>> b[5]
4
>>> b[10]
IndexError: list index out of range

Batches have these public attributes:

start
The first element number (counting from 1).
first
The first element index (counting from 0). Note that this is that same as start - 1.
end
The last element number (counting from 1).
orphan
The desired minimum batch size. This controls how sequences are split into batches. If a batch smaller than the orphan size would occur, then no split is performed, and a batch larger than the batch size results.
overlap
The number of elements that overlap between batches.
length
The actual length of the batch. Note that this can be different than size due to orphan settings.
size
The desired size. Note that this can be different than the actual length of the batch due to orphan settings.
previous
The previous batch or None if this is the first batch.
next
The next batch or None if this is the last batch.

__init__(self, sequence, size, start=0, end=0, orphan=0, overlap=0)

Creates a new batch given a sequence and a desired batch size.

sequence
The full sequence.

size
The desired batch size.

start
The index of the start of the batch (counting from 0).

end
The index of the end of the batch (counting from 0).

orphan
The desired minimum batch size. This controls how sequences are split into batches. If a batch smaller than the orphan size would occur, then no split is performed, and a batch larger than the batch size results.

overlap
The number of elements that overlap between batches.

Anonymous User - Sep. 26, 2002 4:52 pm:
 Note that the "start" attribute counts from 1, but the "start" parameter of __init__ counts from 0.

module math

math: Python math module

The math module provides trigonometric and other math functions. It is a standard Python module.

Since Zope 2.4 requires Python 2.1, make sure to consult the Python 2.1 documentation.

See Also

"Python math module":http://www.python.org/doc/current/lib/module-math.html documentation at Python.org

module random

random: Python random module

The random module provides pseudo-random number functions. With it, you can generate random numbers and select random elements from sequences. This module is a standard Python module.

Since Zope 2.4 requires Python 2.1, make sure to consult the Python 2.1 documentation.

See Also

"Python random module":http://www.python.org/doc/current/lib/module-random.html documentation at Python.org

module sequence

sequence: Sequence sorting module

This module provides a sort function for use with DTML, Page Templates, and Python-based Scripts.

def sort(seq, sort)

Sort the sequence

seq

of objects by the optional sort schema

sort

.

sort

is a sequence of tuples

(key, func, direction)

that describe the sort order.

key
Attribute of the object to be sorted.

func
Defines the compare function (optional). Allowed values:
"cmp"
Standard Python comparison function
"nocase"
Case-insensitive comparison
"strcoll" or "locale"
Locale-aware string comparison
"strcoll_nocase" or "locale_nocase"
Locale-aware case-insensitive string comparison
other
A specified, user-defined comparison function, should return 1, 0, -1.
direction
defines the sort direction for the key (optional). (allowed values: "asc", "desc")

DTML Examples

Sort child object (using the objectValues method) by id (using the getId method), ignoring case:


<dtml-in expr="_.sequence.sort(objectValues(),
                               (('getId', 'nocase'),))">
  <dtml-var getId> <br>
</dtml-in>
Anonymous User - Sep. 25, 2002 5:52 pm:
 prev paragraph (dont have a comment tag there) in sort func args: 
 outdent "direction". Also: if optional, what is the default??

Sort child objects by title (ignoring case) and date (from newest to oldest):


<dtml-in expr="_.sequence.sort(objectValues(),
                               (('title', 'nocase'),
                                ('bobobase_modification_time',
                                'cmp', 'desc')
                               ))">
  <dtml-var title> <dtml-var bobobase_modification_time> <br>
</dtml-in>

Page Template Examples

You can use the sequence.sort function in Python expressions to sort objects. Here's an example that mirrors the DTML example above:


<table tal:define="objects here/objectValues;
                   sort_on python:(('title', 'nocase', 'asc'),
                                   ('bobobase_modification_time', 'cmp', 'desc'));
                   sorted_objects python:sequence.sort(objects, sort_on)">
  <tr tal:repeat="item sorted_objects">
    <td tal:content="item/title">title</td>
    <td tal:content="item/bobobase_modification_time">
      modification date</td>  
  </tr>
</table>

This example iterates over a sorted list of object, drawing a table row for each object. The objects are sorted by title and modification time.

Anonymous User - July 11, 2002 1:12 pm:
 should probably read:
 "...sorted list of objectS, ..."

See Also

Python cmp function

module standard

Products.PythonScripts.standard: Utility functions and classes

The functions and classes in this module are available from Python-based scripts, DTML, and Page Templates.

def structured_text(s)

Convert a string in structured-text format to HTML.

See Also

Structured-Text Rules

def html_quote(s)

Convert characters that have special meaning in HTML to HTML character entities.

See Also

"Python cgi module":http://www.python.org/doc/current/lib/Functions_in_cgi_module.html escape function.

def url_quote_plus(s)

Like url_quote but also replace blank space characters with +. This is needed for building query strings in some cases.

See Also

"Python urllib module":http://www.python.org/doc/current/lib/module-urllib.html url_quote_plus function.

def dollars_and_cents(number)

Show a numeric value with a dollar symbol and two decimal places.

def sql_quote(s)

Convert single quotes to pairs of single quotes. This is needed to safely include values in Standard Query Language (SQL) strings.

def whole_dollars(number)

Show a numeric value with a dollar symbol.

def url_quote(s)

Convert characters that have special meaning in URLS to HTML character entities using decimal values.

See Also

"Python urllib module":http://www.python.org/doc/current/lib/module-urllib.html url_quote function.

class DTML

DTML - temporary, security-restricted DTML objects

__init__(source, **kw)

Create a DTML object with source text and keyword variables. The source text defines the DTML source content. The optinal keyword arguments define variables.

call(client=None, REQUEST={}, **kw)

Render the DTML.

To accomplish its task, DTML often needs to resolve various names into objects. For example, when the code <dtml-var spam> is executed, the DTML engine tries to resolve the name spam.

In order to resolve names, you must be pass a namespace to the DTML. This can be done several ways:

  • By passing a client object - If the argument client is passed, then names are looked up as attributes on the argument.
  • By passing a REQUEST mapping - If the argument REQUEST is passed, then names are looked up as items on the argument. If the object is not a mapping, an TypeError will be raised when a name lookup is attempted.
  • By passing keyword arguments -- names and their values can be passed as keyword arguments to the Method.

The namespace given to a DTML object is the composite of these three methods. You can pass any number of them or none at all. Names will be looked up first in the keyword argument, next in the client and finally in the mapping.

def thousand_commas(number)

Insert commas every three digits to the left of a decimal point in values containing numbers. For example, the value, "12000 widgets" becomes "12,000 widgets".

def newline_to_br(s)

Convert newlines and carriage-return and newline combinations to break tags.

module string

string: Python string module

The string module provides string manipulation, conversion, and searching functions. It is a standard Python module.

Since Zope 2.4 requires Python 2.1, make sure to consult the Python 2.1 documentation.

See Also

"Python string module":http://www.python.org/doc/current/lib/module-string.html documentation at Python.org

Previous Page Up one Level Next Page Appendix B: API Reference Comments On/Off Table of Contents