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.
AccessControl
The functions and classes in this module are available to Python-based Scripts and Page Templates.
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.
validate(accessed=None, container=None, name=None, value=None, roles=None)
Validate access.
Arguments:
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.
checkPermission(self, permission, object)
Check whether the security context allows the given permission on the given object.
getUser(self)
Get the current authenticated user. See the
AuthenticatedUser
class.
validateValue(self, value, roles=None)
Convenience for common case of simple value validation.
def getSecurityManager()
Returns the security manager. See the SecurityManager
class.
AuthenticatedUser
AuthenticatedUser
This interface needs to be supported by objects that are returned by user validation and used for access control.
getUserName()
Return the name of a user
getId()
Get the ID of the user. The ID can be used from Python to get the user from the user's UserDatabase.
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.
getRoles()
Return a list of the user's roles.
has_permission(permission, object)
Return true if the user has a permission on an object.
getRolesInContext(object)
Return the list of roles assigned to the user, including local roles assigned in context of an object.
getDomains()
Return the list of domain restrictions for a user.
DTMLDocument
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.
Change DTML Documents
document_src()
Returns the unrendered source text of the DTML Document.
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 '<dtml-var
spam>' 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:
client
object -- If the argument client
is
passed, then names are looked up as attributes on the
argument.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.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.
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>
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.
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.
View
get_size()
Returns the size of the unrendered source text of the DTML Document in bytes.
View
manage_addDocument(id, title)
Add a DTML Document to the current ObjectManager
DTMLMethod
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.
Change DTML Methods
document_src()
Returns the unrendered source text of the DTML Method.
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 '<dtml-var
spam>' 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:
client
object -- If the argument client
is
passed, then names are looked up as attributes on the
argument.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.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:
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>
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.
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.
View
get_size()
Returns the size of the unrendered source text of the DTML Method in bytes.
View
manage_addDTMLMethod(id, title)
Add a DTML Method to the current ObjectManager
DateTime
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:
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.
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.
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.
A DateTime object is returned that represents the gmt value of the time.time() float represented in the local machine's 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 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
See Python's time.strftime function.
dow()
Return the integer day of the week, where Sunday is 0
aCommon()
Return a string representing the object's value in the format: Mar 1, 1997 1:45 pm
h_12()
Return the 12-hour clock representation of the hour
Mon_()
Compatibility: see pMonth
HTML4()
Return the object in the format used in the HTML4.0 specification, one of the standard forms in ISO8601.
Dates are output as: YYYY-MM-DDTHH:MM:SSZ T, Z are literal characters. The time is in UTC.
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.
dayOfYear()
Return the day of the year, in context of the timezone representation of the object
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.
AMPM()
Return the time string for an object to the nearest second.
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
Month()
Return the full month name
mm()
Return month as a 2 digit string
ampm()
Return the appropriate time modifier (am or pm)
hour()
Return the 24-hour clock representation of the hour
aCommonZ()
Return a string representing the object's value in the format: Mar 1, 1997 1:45 pm US/Eastern
Day_()
Compatibility: see pDay
pCommon()
Return a string representing the object's value in the format: Mar. 1, 1997 1:45 pm
minute()
Return the minute
day()
Return the integer day
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
Date()
Return the date string for the object.
Time()
Return the time string for an object to the nearest second.
isFuture()
Return true if this object represents a date/time later than the time of the call
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.
TimeMinutes()
Return the time string for an object not showing seconds.
yy()
Return calendar year as a 2 digit string
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
dd()
Return day as a 2 digit string
rfc822()
Return the date in RFC 822 format
isLeapYear()
Return true if the current year (in the context of the object's timezone) is a leap year
fCommon()
Return a string representing the object's value in the format: March 1, 1997 1:45 pm
isPast()
Return true if this object represents a date/time earlier than the time of the call
fCommonZ()
Return a string representing the object's value in the format: March 1, 1997 1:45 pm US/Eastern
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.
toZone(z)
Return a DateTime with the value as the current object, represented in the indicated timezone.
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.
Mon()
Compatibility: see aMonth
parts()
Return a tuple containing the calendar year, month, day, hour, minute second and timezone of the object
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
PreciseAMPM()
Return the time string for the object.
AMPMMinutes()
Return the time string for an object not showing seconds.
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.
pDay()
Return the abbreviated (with period) name of the day of the week
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.
h_24()
Return the 24-hour clock representation of the hour
pCommonZ()
Return a string representing the object's value in the format: Mar. 1, 1997 1:45 pm US/Eastern
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
DayOfWeek()
Compatibility: see Day
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
dow_1()
Return the integer day of the week, where Sunday is 1
timezone()
Return the timezone in which the object is represented.
year()
Return the calendar year of the object
PreciseTime()
Return the time string for the object.
ISO()
Return the object in ISO standard format
Dates are output as: YYYY-MM-DD HH:MM:SS
millis()
Return the millisecond since the epoch in GMT.
second()
Return the second
month()
Return the month of the object as an integer
pMonth()
Return the abbreviated (with period) month name.
aMonth()
Return the abbreviated month name.
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
Day()
Return the full name of the day of the week
aDay()
Return the abbreviated name of the day of the week
ExternalMethod
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:
self
.In this case, the URL parent of the object is supplied as the first argument.
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:
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.
File
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.
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>
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.
View
update_data(data, content_type=None, size=None)
Updates the contents of the File with data
.
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
.
getSize()
Returns the size of the file in bytes.
View
manage_addFile(id, file="", title="", precondition="", content_type="")
Add a new File object.
Creates a new File object id
with the contents of file
Folder
Folder(ObjectManagerItem, ObjectManager, PropertyManager)
A Folder is a generic container object in Zope.
Folders are the most common ObjectManager subclass in Zope.
manage_addFolder(id, title)
Add a Folder to the current ObjectManager
Add Folders
Image
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.
View
manage_addImage(id, file, title="", precondition="", content_type="")
Add a new Image object.
Creates a new Image object id
with the contents of file
.
MailHost
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:
None
means no encoding is done. Valid values
are base64
, quoted-printable
and uuencode
.manage_addMailHost(id, title="", smtp_host=None, localhost=localhost, smtp_port=25, timeout=1.0)
Add a mailhost object to an ObjectManager.
ObjectManager
ObjectManager
An ObjectManager contains other Zope objects. The contained objects are Object Manager Items.
To create an object inside an object manager use manage_addProduct
:
self.manage_addProduct['OFSP'].manage_addFolder(id, title)
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>
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.
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>
The results were restricted to Folders by passing a
meta_type to objectValues
method.
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.
Access contents information
ObjectManagerItem
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
This is an optional one-line string description of the object.
meta_type
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
This object is acquired and should not be set.
title_or_id()
If the title is not blank, return it, otherwise return the id.
getPhysicalRoot()
Returns the top-level Zope Application object.
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.
View management screens
getPhysicalPath()
Get the path of an object from the root, ignoring virtual hosts.
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.
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.
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.
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.
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.
If an object is not found then the default
argument will be
returned.
title_and_id()
If the title is not blank, the return the title followed by the id in parentheses. Otherwise return the id.
PropertyManager
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.
Access contents information
propertyValues()
Returns a list of property values.
Access contents information
propertyMap()
Returns a tuple of mappings, giving meta-data for properties.
The meta-data includes id
, type
, and mode
.
Access contents information
propertyIds()
Returns a list of property ids.
Access contents information
getPropertyType(id)
Get the type of property id
. Returns None if no such
property exists.
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.
Access contents information
hasProperty(id)
Returns a true value if the Property Manager has the property
id
. Otherwise returns a false value.
Access contents information
PropertySheet
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).
propertyItems()
Return a list of (id, property) tuples.
Access contents information
propertyValues()
Returns a list of actual property values.
Access contents information
getPropertyType(id)
Get the type of property id
. Returns None if no such
property exists.
propertyInfo()
Returns a mapping containing property meta-data.
getProperty(id, d=None)
Get the property id
, returning the optional second
argument or None if no such property is found.
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.
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.
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
date
DateTime
value, for example 12/31/1999 15:42:52 PST
.float
12.4
. int
12
. lines
long
12232322322323232323423
. string
This is a string
. text
tokens
one two three
. selection
multiple selection
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.
Manage Properties
propertyMap()
Returns a tuple of mappings, giving meta-data for properties.
propertyIds()
Returns a list of property ids.
Access contents information
hasProperty(id)
Returns true if self
has a property with the given id
,
false otherwise.
Access contents information
PropertySheets
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.
values()
Return a sequence of all of the PropertySheet objects in the collection.
items()
Return a sequence containing an (id, object)
tuple for
each PropertySheet object in the collection.
PythonScript
PythonScript(Script)
Python Scripts contain python code that gets executed when you call the script by:
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:
open
are, therefore,
not allowed.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:
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:
manage_addPythonScript(id, REQUEST=None)
Add a Python script to a folder.
Request
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:
These variables include input headers, server data, and other request-related data. The variable names are as specified in the CGI specification
These are data extracted from either a URL-encoded query string or body, if present.
These are the cookie data, if present.
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.
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
PARENTS[0]
would be the ancestor of
the published object.REQUEST
RESPONSE
PUBLISHED
URL
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'.
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='/'.
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'.
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'.
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.
items()
Returns a sequence of (key, value) tuples for all the keys in the REQUEST object.
keys()
Returns a sorted sequence of all keys in the REQUEST object.
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.
values()
Returns a sequence of values for all the keys in the REQUEST object.
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.
has_key(key)
Returns a true value if the REQUEST object contains key, returns a false value otherwise.
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.
Response
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.
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.
addHeader(name, value)
Set a new HTTP return header with the given value, while retaining any previously set headers with the same name.
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.
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.
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.
setBase(base)
Set the base URL for the returned document.
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.
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.
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).
Script
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.
SessionInterfaces
See Also
SessionDataManagerErr
Error raised during some session data manager operations, as explained in the API documentation of the Session Data 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 SessionDataManagerErr
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.
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
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
TransienceInterfaces
Transient Objects
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.
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.
setLastAccessed(self)
Cause the last accessed time to be set to now.
getCreated(self)
Return the time the transient object was created in integer seconds-since-the-epoch form.
values(self)
Return sequence of value elements.
has_key(self, k)
Return true if item referenced by key k exists.
getLastAccessed(self)
Return the time the transient object was last accessed in integer seconds-since-the-epoch form.
getId(self)
Returns a meaningful unique id for the object.
update(self, d)
Merge dictionary d into ourselves.
clear(self)
Remove all key/value pairs.
items(self)
Return sequence of (key, value) elements.
keys(self)
Return sequence of key elements.
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.
set(self, k, v)
Call __setitem__ with key k, value v.
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.
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.
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
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.
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.
Manage Transient Object Container
getTimeoutMinutes(self)
Return the number of minutes allowed for subobject inactivity before expiration.
View management screens
has_key(self, k)
Return true if container has value associated with key k, else return false.
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.
Manage Transient Object Container
getId(self)
Returns a meaningful unique id for the object.
setTimeoutMinutes(self, timeout_mins)
Set the number of minutes of inactivity allowable for subobjects before they expire.
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.
Create Transient Objects
get(self, k, default=None)
Return value associated with key k. If value associated with k does not exist, return default.
Access Transient Objects
getAddNotificationTarget(self)
Returns the current after add
function, or None.
View management screens
getDelNotificationTarget(self)
Returns the current before destruction
function, or None.
View management screens
UserFolder
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.
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.
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.
getUsers()
Returns a sequence of all user objects which reside in the user folder.
getUserNames()
Returns a sequence of names of the users which reside in the user folder.
getUser(name)
Returns the user object specified by name. If there is no
user named name
in the user folder, return None.
Vocabulary
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.
manage_addVocabulary(id, title, globbing=None, REQUEST=None)
Add a Vocabulary object to an ObjectManager.
ZCatalog
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:
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_
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'})
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:
reverse
or descending
.
Default behavior is to sort ascending.sort_on
will be
returned unsorted.sort_on
will be returned unsorted.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
.
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.
ZSQLMethod
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.
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.
ZTUtils
The classes in this module are available from Page Templates.
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:
__init__(self, sequence, size, start=0, end=0, orphan=0, overlap=0)
Creates a new batch given a sequence and a desired batch size.
math
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.
Python math
module
documentation at Python.org
random
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.
Python random
module
documentation at Python.org
sequence
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.
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>
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>
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.
standard
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.
def html_quote(s)
Convert characters that have special meaning in HTML to HTML character entities.
Python cgi
module_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.
Python urllib
module
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.
Python urllib
module
url_quote
function.
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:
client
object - If the argument client
is
passed, then names are looked up as attributes on the
argument.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.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.
string
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.
Python string
module
documentation at Python.org