Skip to content.

plope

Personal tools
You are here: Home » Books » 2_7Edition » Appendix B: API Reference
 
 
Views
  • State: visible
Previous Page Up one Level Next Page Appendix B: API Reference Comments On/Off Table of Contents Sections Index

Appendix B: API Reference

Introduction

This reference describes the interfaces to the most common set of basic Zope objects. This reference is useful while writing Page Templates, DTML, Python scripts, and Product code.

The intended audience is able to read simple Python code and has at least passing experience with object-oriented programming.

The reference is not a tutorial. Nor is it a substitute for reading the rest of the Zope Book. Examples, where they are provided, are intended to be illustrative, but not comprehensive.

XXX STATUS

Updated by Paul Winkler, Thu Jan 27 01:22:54 EST 2005

More items moved from TODO to DONE.

All new comments merged from the zope.org 2.6 version, up until 2005/01/27 00:24:00.954 US/Eastern

Some more cleanup of DateTime (added return types for everything except where very obviously a string).

XXX TO DO

  • For all modules, classes, methods, and functions in the reference:
    • verify that all names are correct
    • see if any non-private methods are missing, and add them
    • document types of arguments and return values and expected exceptions
    • compare API reference to source docstrings and to the HelpSys .stx files, combine and edit all for completeness and clarity.
    • check base classes for things that need documenting - either add the base class to this API ref, or document any non-overridden methods as part of the derived class docs - not sure how best to do this so i'm handling it on a case-by-case basis. We don't want to document every base class in zope's tangled hierarchy, but we do want everything that's reasonably part of "the API" which is nebulous.

    It's a big job, best done one module at a time. So far it takes me about an hour to do one module properly :-( Many modules are done, see DONE below.

    The below modules are still to do:

    
    Products/OFSP   XXX maybe ignore this since it just provides Versions??
    Products/MIMETools  XXX does anybody use this??  just provides dtml-mime
    Products/PageTemplates
    Products/PluginIndexes
    Products/SiteAccess
    Products/SiteErrorLog
    Products/StandardCacheManagers
    Products/TemporaryFolder
    Products/ZCTextIndex
    Products/ZGadflyDA
    Products/ZODBMountPoint
    Products/ZopeTutorial
    Produts/ZReST
    PropertySheet
    PropertySheets
    SessionInterfaces
    TransienceInterfaces
    Vocabulary
    ZCatalog
    ZSQLMethod
    ZTUtils
    

  • Maybe omit module names for one-class modules, as suggested on zope-web by Don Hopkins?
  • Maybe add descriptive categories such as "Core", "Content", and "Utility" next to class names, as suggested on zope-web by Don Hopkins?
  • List the meta_type for all classes that have one??
  • lots of people want embedded examples a la http://www.php.net ... add more.
  • add manage_clone docs
  • add manage_delObjects docs
  • all manage_addFoo examples must show the package name!
  • all manage_addFoo examples must document the permissions needed.
  • add missing modules and classes from http://dev.zope.org/Wikis/DevSite/Proposals/IdentifyMissingStuff
  • add permission information to methods that don't have it.
  • consistently document availability. Right now it's very spotty and ad-hoc. By availability, I mean e.g. can you import it in a Python Script? Is it available to DTML and if so how? etc. This could be done just under the Permission documentation.
  • fix up any formatting issues.
  • Methods used for FTP? I skipped these on everything prior to ObjectManager, might have to go back and do em.
  • ZServer.FTPRequest
  • Address all remaining XXX items
  • Credits for this edition - extract from the DONE section

XXX DONE

  • verify that module, class, and method names are correct, and verify against the source code docstrings, and see if those classes grew more methods. (Big job but these tasks are easier done one module at a time.) Some of these are done, see DONE below.

    DONE for these modules:

    
    AccessControl
    Acquisition (just a link to dev guide chapter)
    DateTime
    DTMLDocument (removed a lot of stuff inherited from DTMLMethod)
    DTMLMethod
    ExternalMethod
    Folder
    HTTPRequest
    HTTPResponse
    Image
    MailHost
    ObjectManager
    PropertyManager
    PythonScripts (Thanks to Jim Alexander! ... no changes)
    Script (actually Shared.DC.Scripts.Script)
    SimpleItem 
    Traversable
    User
    UserFolder (Thanks to David Evans!!) 
    math
    random
    sequence
    standard
    string
    

    ... with miscellaneous stuff still left to do on those, marked by "XXX".

  • changed "ObjectManager Constructor" to "ObjectManager factory"
  • changed "constructor method" to "factory function" in ObjectManager docs... because it is :-P
  • changed "Python only" to the more descriptive "restricted Python only."
  • check all links
  • wrote an intro.
  • removed self argument from methods, for consistency.
  • added Traversable
  • replaced ObjectManagerItem with Item and SimpleItem, yay!
  • removed File module, moved File to Image module
  • trivial typo comments addressed & removed
  • some module names fixed: HTTPRequest, HTTPResponse, PythonScripts
  • sorted method names (alphanumeric)
  • sorted function names (alphanumeric), after class names
  • sorted class names (alphanumeric)
  • sorted module names (alphanumeric)
  • we now have hierarchical TOC, yay

module AccessControl

AccessControl: Security functions and classes

The functions and classes in this module are available to Python-based Scripts and Page Templates, but not to DTML. In DTML you can use the related functions described in the DTML chapters of the Zope Book.

XXX missing ClassSecurityInfo? ModuleSecurityInfo? allow_module? allow_class ?

class SecurityManager

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

Typically in Zope code, you do not instantiate one of these; instead, you access the current existing one by calling the getSecurityManager() function.

calledByExecutable()

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

XXX what the heck does that mean?

permission
Always available

checkPermission(permission, object)

Check whether the security context (including the current user) allows the given permission on the given object.

Arguments:

permission
A permission name (string).
object
The object being accessed.
permission
Always available

getUser()

Get the current authenticated user. See the BasicUser class.

Example usage in ZPT:


Hello, user 
<em
 tal:define="sm python:modules['AccessControl'].getSecurityManager();
             user python:sm.getUser()"
 tal:content="user"> 
    Bob 
</em>!

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 container of the accessed object.
name
The name used to access the value.
value
The object 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.

XXX verify arg descriptions and give examples.

permission
Always available

validateValue(value, roles=None)

Convenience for common case of simple value validation.

permission
Always available

function getSecurityManager()

Returns the current security manager. See the SecurityManager class.

Example usage in a Script (Python):


import AccessControl
sm = AccessControl.getSecurityManager()
return sm.getUser()

module Acquisition

See the Acquisition documentation in the Developers' Guide

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 internal 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 the host system's epoch, using the standard int, long, and float functions. (Compatibility Note: int, long and float return the number of days since the epoch in UTC 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.

(Note: the epoch is a reference date that depends on the underlying operating system. On most Unix systems, it is 00:00:00 UTC, January 1, 1970.)

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 internal 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 initialized with no arguments, then the current date/time is returned, represented in the timezone of the local machine.
  • If initialized 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 initialized 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.)

    Note that this behavior can be reversed by setting the "datefmt" variable as described below (in which case, "2/1/1994" is interpreted as January 2 instead of February 1).

    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). Finally, the DateTime constructor automatically detects and handles ISO8601-compliant dates (YYYY-MM-DDThh:mm:ssTZD). See http://www.w3.org/TR/NOTE-datetime for full specs.

    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.

    Examples of initializing with a single string:

    
    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
    
    z=DateTime("1997-03-09T13:45:00-0500").
    # z is equal to y
    

    For non-ISO-8601 strings, the string is assumed to consist of a date component followed by an optional time component.

    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 or float 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 is initialized with a single numeric argument, the number is assumed to be a floating point value representing seconds since the epoch, such as that returned by time.time(). Example:
    
    x = DateTime(0)
    x == DateTime('1970/01/01 00:00:00 UTC')
    

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

  • If the DateTime is initialized 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.

    Example:

    
    x = DateTime(2010, 55.5)
    x == DateTime('2010/02/24 16:00:00 UTC')
    

    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 DateTime 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.

    Example:

    
    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 DateTime is initialized 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 DateError 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. If the hours, minutes, or seconds are not valid, a TimeError is raised. 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).

    Example:

    
    x = DateTime(2000, 6, 1, 11, 45, 00, 'GMT') 
    y = DateTime('2000/06/01 11:45:00 UTC')
    x == y
    

    New in Zope 2.7: A new keyword parameter "datefmt" can be passed to the constructor. If set to "international", the constructor is forced to treat ambigious dates as "days before month before year". This useful if you need to parse non-US dates in a reliable way. The default value is "us" but can be overridden in your zope.config file.

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

AMPM()

Return the time string for an object to the nearest second, using a 12-hour clock and the am or pm modifier, e.g. 01:28:08 am.

Permission
Always available

AMPMMinutes()

Like AMPM but omits the seconds, e.g. 01:29 am.

Permission
Always available

Date()

Return the date string for the object, in the format YYYY/MM/DD.

Permission
Always available

Day()

Return the full name of the day of the week.

Permission
Always available

Day_()

For backwards compatibility; see pDay. May be deprecated someday.

Permission
Always available

DayOfWeek()

For backwards compatibility: see Day. May be deprecated someday.

Permission
Always available

HTML4()

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

See HTML 4.0 Specification

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

Permission
Always available

ISO()

Return a string in ISO standard format. Dates are output as: YYYY-MM-DD HH:MM:SS

Permission
Always available

JulianDay()

Return the Julian day as an integer, according to http://www.tondering.dk/claus/cal/node3.html#sec-calcjd

Mon()

For backwards compatibility; see aMonth. May be deprecated someday.

Permission
Always available

Mon_()

For backwards compatibility; see pMonth. May be deprecated someday.

Permission
Always available

Month()

Return the full month name.

Permission
Always available

PreciseAMPM()

Return the time string for the object, including milliseconds and the modifier, e.g. 01:31:07.525 am.

Permission
Always available

PreciseTime()

Return the time string for the object, including milliseconds, in 24-hour format, e.g. 23:59:37.963.

Permission
Always available

Time()

Return the time string for an object to the nearest second, in 24-hour format, e.g. 23:30:15.

Permission
Always available

TimeMinutes()

Return the time string for an object not showing seconds, in 24-hour format, e.g. 23:31.

Permission
Always available

aCommon()

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

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

aDay()

Return the abbreviated name of the day of the week.

Permission
Always available

aMonth()

Return the abbreviated month name.

Permission
Always available

ampm()

Return the appropriate time modifier (am or pm), as a lowercase string.

Permission
Always available

day()

Return the day of the month as an integer.

Permission
Always available

dayOfYear()

Return the day of the year as an integer, in context of the timezone representation of the object.

Permission
Always available

dd()

Return the day of the month as a 2-digit string.

Permission
Always available

dow()

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

Permission
Always available

dow_1()

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

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

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 t. Revised to give more correct results through comparison of long integer milliseconds.

Permission
Always available

fCommon()

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

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

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 t. Revised to give more correct results through comparison of long integer milliseconds.

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 t. Revised to give more correct results through comparison of long integer milliseconds.

Permission
Always available

h_12()

Return the 12-hour clock representation of the hour as an integer.

Permission
Always available

h_24()

Return the 24-hour clock representation of the hour as an integer.

Permission
Always available

hour()

Return the 24-hour clock representation of the hour as an integer.

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

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

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

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

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

isFuture()

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

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

isPast()

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

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

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 t. Revised to give more correct results through comparison of long integer milliseconds.

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 t. Revised to give more correct results through comparison of long integer milliseconds.

Permission
Always available

localZone(ltm=None)

Return the local time zone on the given date, in the format US/Eastern. The time zone can change according to daylight savings. The optional ltm argument is a tuple in the format returned by time.localtime() from the Python standard library. If no argument is passed, use the current time.

Permission
Always available

millis()

Return the milliseconds since the epoch in UTC, as a long integer.

Permission
Always available

minute()

Return the minute portion of the time as an integer.

Permission
Always available

mm()

Return the month of the object as a 2-digit string.

Permission
Always available

month()

Return the month of the object as an integer.

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 t. Revised to give more correct results through comparison of long integer milliseconds.

Permission
Always available

parts()

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

Permission
Always available

pCommon()

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

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

pDay()

Return the abbreviated (with period) name of the day of the week, e.g. Wed.

Permission
Always available

pMonth()

Return the abbreviated (with period) month name, e.g. Mar.

Permission
Always available

rfc822()

Return the date of the object as a string in RFC 822 format, e.g. Wed, 01 Sep 2004 01:34:12 -0400.

Permission
Always available

second()

Return the second portion of the time, as a float.

Permission
Always available

strftime(format)

Return date/time string formatted according to format, using the current timezone representation.

See Python's time.strftime function.

Example:


DateTime('2004/01/01').strftime('%m.%Y') == '01.2004'

timeTime()

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

Permission
Always available

timezone()

Return the timezone in which the object is represented, as a string, e.g. US/Eastern or GMT, or GMT+2.

Permission
Always available

toZone(z)

Return a DateTime with the same value as the current object, represented in the indicated timezone. z is a string e.g. US/Pacific, or GMT, or GMT-1.

Permission
Always available

tzoffset()

Return the timezone offset for the object's timezone as an integer, measured in seconds relative to UTC. Examples:


DateTime().toZone('GMT').tzoffset() == 0
DateTime().toZone('GMT-1').tzoffset() == -3600

week()

Return the week number of the object as an integer, according to ISO. See http://www.tondering.dk/claus/cal/node6.html#SECTION00670000000000000000 Example:


DateTime('2005/12/31').week() == 52

Permission
Always available

year()

Return the calendar year of the object as an integer.

Permission
Always available

yy()

Return calendar year of the object as a 2-digit string, e.g. DateTime(2004/01/01) == 04.

Permission
Always available

module DTMLDocument

class DTMLDocument(PropertyManager, DTMLMethod)

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

DTML Documents are identical to DTML Methods with two differences:

First, it supports the PropertyManager API, so you can store properties in the object.

Secondly, when the Document is called, its own namespace is merged with that of the client argument. So properties and methods of the Document will be used before those of the container or context. For example, calling absolute_url() on a DTMLDocument will return the URL of the DTMLDocument itself.

ObjectManager Factory

'manage_addDTMLDocument(id, title='', file=')

Add a DTML Document to the current ObjectManager. The file argument may be a string or a file-like object.

module DTMLMethod

class DTMLMethod(RestrictedDTML, HTML, Acquisition.Implicit, RoleManager, ElementWithTitle, Item_w__name__, History.Historical, Cacheable)

XXX many of those base classes are not listed in this ref. add some or all of them?

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.

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

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

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

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

  • By passing a client object -- If the argument client is passed, then names are looked up as attributes on the argument.
  • By passing a REQUEST mapping -- If the argument REQUEST is passed, then names are looked up as items on the argument. If the object is not a mapping, a TypeError will be raised when a name lookup is attempted. Typically, the REQUEST is an HTTPRequest instance.
  • 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.

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

Unlike DTMLDocuments, a DTMLMethod does not look up names in its own namespace. In this sense, it acts only as a method of its container or context. For example, calling absolute_url() on a DTMLMethod will return the URL of its container. XXX container before context as usual, right??

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

XXX PrincipiaSearchSource method?

XXX manage_proxy method?

XXX manage_haveProxy method?

XXX setCacheNamespaceKeys?

document_src()

Returns the unrendered source text of the DTML Method.

Permission
View management screens

get_size()

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

Permission
View

'manage_edit(data, title, SUBMIT=Change, dtpref_cols=100%, dtpref_rows=20, REQUEST=None)'

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

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

The SUBMIT parameter is also used during through-the-web editing to change the size of the editing area on the default Document edit screen. If the value is "Smaller", the rows and columns decrease by 5. If the value is "Bigger", the rows and columns increase by 5. If any other or no value is supplied, the data gets checked for DTML errors and is saved.

Permission
Change DTML Methods

'manage_upload(file=', REQUEST=None)

Replace the contents of the document with the text in file.

Permission
Change DTML Methods

ObjectManager Factory

'manage_addDTMLMethod(id, title='', file=')

Add a DTML Method to the current ObjectManager. The file argument may be a string or a file-like object.

module ExternalMethod

class

ExternalMethod(Item, Persistent, Acquisition.Explicit, RoleManager, Navigation)

XXX do we want all those base classes?

Web-callable functions that encapsulate external Python functions.

The wrapped 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.

There are no security restrictions on the code that can be placed in or imported by this external file.

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.

__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. XXX container, not ever context?

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 if functions rely on shared global data.

ObjectManager Factory

manage_addExternalMethod(id, title, module, function, REQUEST=None)

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 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 a product package name, 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 Products/ACMEWidgets/Extensions/foo.py. If this failes, then the file Extensions/ACMEWidgets.foo.py will be used.

module Folder

class Folder(ObjectManager, PropertyManager, RoleManager, webdav.Collection.Collection, Item, FindSupport.FindSupport)

A Folder is a generic container object. Folders are the most common ObjectManager subclass in Zope.

ObjectManager Factory

'manage_addFolder(id, title=', createPublic=0, createUserF=0, REQUEST=None)

Add a Folder to the current ObjectManager with the given id and optional title.

If the createPublic argument is true, a Page Template with the id index_html will be created in the new folder.

If the createUserF argument is true, a UserFolder with the id acl_users will be created in the new folder.

Permission
Add Folders

module HTTPRequest

class FileUpload

File upload objects are used to represent file-uploaded data.

File upload objects can be used just like files objects. See the Python documentation for details on file objects.

In addition, FileUploads have a headers attribute that is a dictionary containing the file-upload headers, and a filename attribute containing the name of the uploaded file.

__init__(aFieldStorage)

Create a new FileUpload object. Argument is an instance of cgi.FieldStorage, see the cgi documentation in the Python Library Reference

class HTTPRequest(BaseRequest)

XXX we don't document the BaseRequest module. Should we???

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.

Request objects are typically not created by application code; one is created for you by the object publisher and will be passed to published objects through the argument named REQUEST.

The current request is also accessible as the REQUEST attribute of any acquisition-aware object. Page Templates also bind the current request to the name "request". The different spelling in these different circumstances is a bit of a wart. Sorry about that.

The request can also be used as a namespace, in which names are resolved the same as for the mapping interface, as described below.

HTTPRequest provides a somewhat richer interface than BaseRequest, notably by providing some support for virtual hosting, and by providing richer variable categorization.

Variables are organized into four categories. Each category is represented as a dictionary and available as an attribute of the REQUEST object, as follows:

  • Environment variables (.environ)

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

  • Form data (.form)

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

    The form attribute of a request is actually a FieldStorage object. When file uploads are used, this provides a richer and more complex interface than is provided by accessing form data as items of the request. See the cgi module documentation in the Python library reference for more details.

  • Cookies (.cookies)

    The cookie data, if present.

  • Other (.other)

    Data that may be set by an application object.

When the request object is used as a mapping object, values will be looked up in all of the above categories, in this order: environ, other, form, cookies.

In addition, there is a special pseudo-category:

  • 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, i.e. 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) as described below.

    Accessing lazy data is no different from accessing any other request data.

So, if a request variable foo exists only in the other category, then the following ways of accessing it will return the same value:


request = context.REQUEST

f1 = request['foo']          # mapping, no error-checking.

f2 = request.foo             # attribute, no error-checking.

f3 = request.get('foo')      # mapping, returns None on error.

f4 = request.other['foo']    # mapping, more specific, no
                             # error-checking.

f5 = request.other.get('foo')   # mapping, more specific, returns
                                # None on error.

The following special (XXX read-only? lazy?) variables are always available in the

other

category:

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 itself.

RESPONSE
The Response object, generally an instance of HTTPResponse.

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

URL
The URL of the published object.

This is almost the same as the exact URL the client requested, but it does not include any query parameters, nor does it include any trailing path elements (i.e. the traverse_subpath available to Python Scripts and Page Templates).

URLn
URL0 is the same as URL. URL1 is the same as URL0 with the last path element removed. URL2 is the same as URL1 with the last element removed. Etcetera. Only as many URLn variables are defined as is necessary.

For example if URL=http://localhost/foo/bar, then URL1=http://localhost/foo, URL2=http://localhost, and URL3 and higher are not defined.

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

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

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

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

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

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

In addition, many variables are commonly set by other parts of the system, such as the virtual host machinery, or the published objects, or your own application code. XXX These should be noted in each relevant section.

It is very instructive to view all the contents of a request. This is a popular technique during debugging and development. For example, in a Python Script:


request = context.REQUEST
return request

Or in a Page Template:


<span tal:replace="request" />

Or in DTML:


<dtml-var REQUEST>

get(key, default=None)

Get the value of the request variable key. If not found, return default.

The value will be looked up from one of the request data categories. The search order is: environment variables, other variables, form data, and then cookies.

Permission
Always available

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

getClientAddr()

The IP address of the client, as a string. If cannot be determined, the string will be empty.

Permission
XXX Always available?

has_key(key)

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

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

physicalPathToVirtualPath(path)

Remove the path to the VirtualRoot from the given physical path.

path may be a string delimited by slashes, or a sequence of strings.

Returned value is a sequence of strings.

XXX example? must call setVirtualRoot first.

XXX usage? is this intended to be public?

Permission
Always available XXX

physicalPathFromURL(URL)

Convert a URL string into a physical path (sequence of strings) in the current context. If the URL makes no sense in light of the current virtual hosting context, a ValueError is raised.

Note that this does not verify existence of an object at the resulting path.

Permission
Always available XXX

physicalPathToURL(path, relative=0)

Convert a physical path into a URL in the current context. Returns a url-quoted string.

path is a sequence of strings.

If relative is true, the resulting path begins with the path of the current context. Otherwise, the server URL is included too.

Intended to be called from publishing traversal hooks. If you are constructing URLs, you should probably use methods of Traversable instead.

Permission
Always available XXX

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

set_lazy(key, callable)

Add a lazy variable to the other category. When key is subsequently requested for the first time, callable will be called to compute the value, which is then stored in other for the remainder of the request's lifetime.

Permission
XXX

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

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

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

Permission
Always available

setVirtualRoot(path, hard=0)

Alters URL, URLn, URLPATHn, BASEn, BASEPATHn, and virtual-host-aware methods such as absolute_url(), such 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

traverse(path, response=None, validated_hook=None)

Traverse the object space. Return an object if possible and if allowed by the security machinery; otherwise, call an appropriate error method of the response.

The REQUEST must already have a PARENTS item with at least one object in it. This is typically the root object.

response can be passed as an HTTPResponse instance. It defaults to self.response.

validated_hook is an optional callable which, if passed, will be called after security validation succeeds, with two positional arguments: the request itself, and the validated user object.

Permission
Always available

values()

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

Permission
Always available

module HTTPResponse

class HTTPResponse

The Response object encapsulates all possible responses to HTTP requests. Responses are normally created by the object publisher. A published object may recieve the response abject as an argument named RESPONSE. A published object may also create it's own response object.

Normally, published objects use response objects to:

  • Provide specific control over output headers,
  • Set cookies, or
  • Provide stream-oriented output.

If stream oriented output is used, then the response object passed into the object must be used.

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

appendCookie(name, value, delimiter=,)

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

appendHeader(name, value, delimiter=",")

Append a value to a header.

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

Permission
Always available

badRequestError(name)

Raise a BadRequest error.

debugError(entry)

Raises NotFound.

enableHTTPCompression,REQUEST={},force=0,disable=0,query=0)

Enable HTTP Content Encoding with gzip compression if possible.

REQUEST
used to check if client can accept compression force -- set true to ignore REQUEST headers disable -- set true to disable compression query -- just return if compression has been previously requested
returns
1 if compression will be attempted, 2 if compression is forced, 0 if no compression

The HTTP specification allows for transfer encoding and content encoding. Unfortunately many web browsers still do not support transfer encoding, but they all seem to support content encoding.

This function is designed to be called on each request to specify on a request-by-request basis that the response content should be compressed. This is quite useful for xml-rpc transactions, where compression rates of 90% or more can be achieved for text data.

The REQUEST headers are used to determine if the client accepts gzip content encoding. The force parameter can force the use of gzip encoding regardless of REQUEST, and the disable parameter can be used to "turn off" previously enabled encoding (but note that any existing content-encoding header will not be changed). The query parameter can be used to determine if compression has been previously requested.

In setBody, the major mime type is used to determine if content encoding should actually be performed.

By default, image types are not compressed. Additional major mime types can be specified by setting the environment variable DONT_GZIP_MAJOR_MIME_TYPES to a comma-seperated list of major mime types that should also not be gzip compressed.

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

forbiddenError(entry="Unknown")

raise NotFound.

notFoundError(entry="Unknown")

raise NotFound.

redirect(location, status=302, 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).

You can also override the integer status code, e.g. you might want to use 301 ("Moved Permanently") instead of 302 ("Moved Temporarily").

Permission
Always available

setBase(base)

Set the base URL for the returned document. If base is None, or the document already has a base, has no effect.

Permission
Always available

setBody(body, title="", is_error=0)

Sets the response body equal to the (string) argument body. Also updates the "content-length" return header.

You can also specify a title, in which case the title and body will be wrapped up in html, head, title, and body tags.

If the body is a 2-element tuple, then it will be treated as (title,body).

If is_error is true then the HTML will be formatted as a Zope error message instead of a generic HTML page.

setCookie(name, value, **kw)

Set an HTTP cookie on the browser

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

Anonymous User - Oct. 13, 2004 11:11 am:
 (quote from http://wp.netscape.com/newsref/std/cookie_spec.html)
 expires=DATE
     The expires attribute specifies a date string that defines the valid life time of
 that cookie. Once the expiration date has been reached, the cookie will no longer be
 stored or given out.
     The date string is formatted as:
         Wdy, DD-Mon-YYYY HH:MM:SS GMT
     This is based on RFC 822, RFC 850, RFC 1036, and RFC 1123, with the variations that
 the only legal time zone is GMT and the separators between the elements of the date must
 be dashes.
     expires is an optional attribute. If not specified, the cookie will expire when the
 user's session ends.
     Note: There is a bug in Netscape Navigator version 1.1 and earlier. Only cookies whose
 path attribute is set explicitly to "/" will be properly saved between sessions if they
 have an expires attribute.

Permission
Always available

setHeader(name, value, literal=0)

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

setStatus(status, reason=None)

Sets the HTTP status code of the response; the

status

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.

The reason argument is an optional string which may override the default explanatory text (e.g. if you want to describe a 404 status with something other than "Not Found").

Permission
Always available

unauthorized

Raise an Unauthorized error.

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. In particular, the CONTENT-LENGTH header must be set correctly.

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

Permission
Always available

module Image

class File(Persistent, Implicit, PropertyManager, RoleManager, Item_w__name__, Cacheable)

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

If the File contains some text data, it may be rendered in a Page Template very easily like so:


<span tal:replace="context/FileObject" />

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:


<ul>
  <li tal:repeat="f python:context.objectValues('File')">
    <a tal:attributes="f/absolute_url"
       tal:content="f/getId"> the ID goes here </a>
  </li>
</ul>

In this example, the absolute_url method and getId are used to create a list of HTML hyperlinks to all of the File objects in the current Object Manager. See ObjectManager for more about the objectValues method.

getContentType()

Returns the content type of the file.

Permission
View

get_size()

Returns the size of the file in bytes.

Permission
View

index_html(REQUEST, RESPONSE)

The default view of the contents of a File or Image.

Uses the RESPONSE object to output the contents of the file or image. Also, sets the Content-Type header of RESPONSE to the object's content type.

If the object has a precondition (as described in the constructor), it will be called before any data is returned.

Return value is a string, but it may be empty: the File may elect to set a 304 (Not Modified) status and return immediately; or if the file's size is not tiny, it may elect to use the RESPONSE object's streaming interface. In either case, the return value will be an empty string.

Permission
View

manage_edit(title, content_type, precondition="", filedata=None, REQUEST=None)

Changes the title and content type attributes of the object.

If filedata is provided, it replaces the object's uploaded data. It can be either a string or a FileUpload instance.

If precondition is provided, it replaces any existing precondition. See the ObjectManager constructor for explanation of precondition.

Permission
Change Images and Files

manage_upload(file, REQUEST=None)

Replaces the current contents of the File or Image object with file, which may be a string or a FileUpload instance.

Permission
Change Images and Files

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

XXX Is this really part of the API?

Updates the contents of the File with data.

Anonymous User - Nov. 6, 2004 6:11 am:
 I don't get why you can't access this internally.

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
restricted Python only

view_image_or_file(URL1)

Used by the UI to redirect to the default view of the File or Image.

Permission
View

ObjectManager Factory

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

Add a new File object.

The optional file may be a string or a FileUpload instance. If not provided, the new File object will have no data.

The optional precondition is an ID for a callable object. If non-empty, it will be looked up (via acquisition) and called every time the file is viewed. The intention is that this object may raise an exception if you wish to prevent the file from being viewed.

content_type may be explicitly passed; otherwise, an attempt will be made to guess.

class Image(File)

An Image is a Zope object that contains image content.

Images have all the same methods as Files, with a few useful additions.

Images have two read-only properties which define their dimensions, height and width. These are calculated when the image is uploaded. For image types that Zope does not understand, these properties may be undefined.

Zope only recognizes JPEG, PNG, and GIF images.

Using an 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 a Page Template:


<img tal:replace="structure context/ImageObject" />

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


<img tal:attributes="src context/ImageObject/absolute_url;
                     height context/ImageObject/height;
                     width context/ImageObject/width;
                     alt context/ImageObject/title_or_id" />

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


<img tal:replace="structure  
                  python:context.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 keywo