Appendix B
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.
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.
- 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.
module AuthenticatedUser
class 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
- 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.
- 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.
- 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 '<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:
- By passing a
client
object -- If the argumentclient
is passed, then names are looked up as attributes on the argument. - By passing a
REQUEST
mapping -- If the argumentREQUEST
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.
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.
- 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 '<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:
- By passing a
client
object -- If the argumentclient
is passed, then names are looked up as attributes on the argument. - By passing a
REQUEST
mapping -- If the argumentREQUEST
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.
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.
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
See Python's time.strftime function.
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.
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
- 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
- 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
- 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 fails, 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.
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.
- Permission
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
.
- 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
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 where the messageText is an rfc822 formatted message. This allows you complete control over the message headers, including setting any extra headers such as Cc: and Bcc:. The arguments are:
- messageText
- The mail message. It can either be a rfc822 formed text with header fields, or just a body without any header fields. The other arguments given will override the header fields in the message, if they exist.
- mto
- A comma-separated 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 arebase64
,quoted-printable
anduuencode
.
simple_send(self, mto, mfrom, subject, body)
Sends a message. Only To:, From: and Subject: headers can be set. The arguments are:
- mto
- A comma-separated string or list of recipient(s) of the message.
- mfrom
- The address of the message sender.
- subject
- The subject of the message.
- body
- The body of the message.
MailHost 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.
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>
- 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>
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.
- 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.
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.
- 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.
- 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 example12/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
properties 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.
- Permission
- 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.
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 separated 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 separated 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.
- 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 asURL
.URL1
is the same asURL0
with the last path element removed.URL2
is the same asURL1
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 ofURL
,URLPATH1
is the path portion ofURL1
, 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 ofBASE0
,BASEPATH1
is the path portion ofBASE1
, and so on.BASEPATH1
is the externally visible path to the root Zope folder, equivalent to CGI'sSCRIPT_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.
- 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.
- 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.
- 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.
- 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.
- 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.
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.
It's necessary to reassign mutable 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 different 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.
Otherwise, 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.
- 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_
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:
- sort_on
- This parameters specifies which index to sort the results on.
- sort_order
- You can specify
reverse
ordescending
. 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 asort_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 creation 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.
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 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 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>
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.
module standard
- 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.
def html_quote(s)
Convert characters that have special meaning in HTML to HTML character entities.
See Also
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.
See Also
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.
See Also
Python urllib
module 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 optional 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 argumentclient
is passed, then names are looked up as attributes on the argument. - By passing a
REQUEST
mapping - If the argumentREQUEST
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 documentation at Python.org