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.
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).
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
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".
self argument from methods, for consistency.AccessControlThe 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 ?
SecurityManagerA 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?
checkPermission(permission, object)Check whether the security context (including the current user) allows the given permission on the given object.
getUser()
Get the current authenticated user. See the
BasicUser class.
Hello, user
<em
tal:define="sm python:modules['AccessControl'].getSecurityManager();
user python:sm.getUser()"
tal:content="user">
Bob
</em>!
validate(accessed=None, container=None, name=None, value=None, roles=None)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.
validateValue(value, roles=None)Convenience for common case of simple value validation.
getSecurityManager()
Returns the current security manager.
See the SecurityManager class.
Example usage in a Script (Python):
import AccessControl sm = AccessControl.getSecurityManager() return sm.getUser()
AcquisitionSee the Acquisition documentation in the Developers' Guide
DateTimeDateTimeThe 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 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.
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.
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.
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.
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
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.
AMPMMinutes()
Like AMPM but omits the seconds, e.g. 01:29 am.
Date()
Return the date string for the object, in the format YYYY/MM/DD.
Day()Return the full name of the day of the week.
Day_()For backwards compatibility; see pDay. May be deprecated someday.
DayOfWeek()For backwards compatibility: see Day. May be deprecated someday.
HTML4()Return a string 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 where T and Z are literal characters. The time is in UTC.
ISO()Return a string in ISO standard format. Dates are output as: YYYY-MM-DD HH:MM:SS
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.
Mon_()For backwards compatibility; see pMonth. May be deprecated someday.
Month()PreciseAMPM()
Return the time string for the object, including milliseconds
and the modifier, e.g. 01:31:07.525 am.
PreciseTime()
Return the time string for the object, including milliseconds,
in 24-hour format, e.g. 23:59:37.963.
Time()
Return the time string for an object to the nearest second,
in 24-hour format, e.g. 23:30:15.
TimeMinutes()
Return the time string for an object not showing seconds,
in 24-hour format, e.g. 23:31.
aCommon()Return a string representing the object's value in the format: Mar 1, 1997 1:45 pm
aCommonZ()Return a string representing the object's value in the format: Mar 1, 1997 1:45 pm US/Eastern
aDay()Return the abbreviated name of the day of the week.
aMonth()Return the abbreviated month name.
ampm()Return the appropriate time modifier (am or pm), as a lowercase string.
day()Return the day of the month as an integer.
dayOfYear()Return the day of the year as an integer, in context of the timezone representation of the object.
dd()Return the day of the month as a 2-digit string.
dow()Return the integer day of the week, where Sunday is 0.
dow_1()Return the integer day of the week, where Sunday is 1.
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.
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.
fCommon()Return a string representing the object's value in the format: March 1, 1997 1:45 pm
fCommonZ()Return a string representing the object's value in the format: March 1, 1997 1:45 pm US/Eastern
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.
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.
h_12()Return the 12-hour clock representation of the hour as an integer.
h_24()Return the 24-hour clock representation of the hour as an integer.
hour()Return the 24-hour clock representation of the hour as an integer.
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.
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.
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.
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.
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.
isFuture()Return true if this object represents a date/time later than the time of the call.
isLeapYear()Return true if the current year (in the context of the object's timezone) is a leap year.
isPast()Return true if this object represents a date/time earlier than the time of the call.
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.
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.
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.
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.
millis()Return the milliseconds since the epoch in UTC, as a long integer.
minute()Return the minute portion of the time as an integer.
mm()Return the month of the object as a 2-digit string.
month()Return the month of the object as an integer.
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.
parts()Return a tuple containing the calendar year, month, day, hour, minute, second and timezone of the object.
pCommon()Return a string representing the object's value in the format: Mar. 1, 1997 1:45 pm
pCommonZ()Return a string representing the object's value in the format: Mar. 1, 1997 1:45 pm US/Eastern
pDay()
Return the abbreviated (with period) name of the day of the
week, e.g. Wed.
pMonth()
Return the abbreviated (with period) month name, e.g. Mar.
rfc822()
Return the date of the object as a string in RFC 822 format,
e.g. Wed, 01 Sep 2004 01:34:12 -0400.
second()Return the second portion of the time, as a float.
strftime(format)
Return date/time string formatted according to format,
using the current timezone representation.
See Python's time.strftime function.
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.
timezone()
Return the timezone in which the object is represented,
as a string, e.g. US/Eastern or GMT, or GMT+2.
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.
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
year()Return the calendar year of the object as an integer.
yy()
Return calendar year of the object as a 2-digit string,
e.g. DateTime(2004/01/01) == 04.
DTMLDocumentDTMLDocument(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.
)Add a DTML Document to the current ObjectManager. The file argument may be a string or a file-like object.
DTMLMethodDTMLMethod(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 <dtml-var
spam> is executed, the DTML engine tries to resolve the name
spam.
In order to resolve names, the Method must be passed a namespace to look them up in. This can be done several ways:
client object -- If the argument client is
passed, then names are looked up as attributes on the
argument.REQUEST mapping -- If the argument REQUEST
is passed, then names are looked up as items on the
argument. If the object is not a mapping, a TypeError
will be raised when a name lookup is attempted.
Typically, the REQUEST is an HTTPRequest instance.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:
A DTML Method can be called from another DTML Method or Document:
<dtml-var standard_html_header> <dtml-var aDTMLMethod> <dtml-var standard_html_footer>
In this example, the Method aDTMLMethod is being called
from another DTML object by name. The calling method passes
the value this as the client argument and the current DTML
namespace as the REQUEST argument. The above is identical
to this following usage in a DTML Python expression:
<dtml-var standard_html_header> <dtml-var "aDTMLMethod(_.None, _)"> <dtml-var standard_html_footer>
Products, External Methods, and Scripts can call a DTML Method in the same way as calling a DTML Method from a Python expression in DTML, as shown in the previous example.
When the URL of a DTML Method is fetched from Zope, the DTML Method is called by the publisher. The REQUEST object is passed as the second argument to the Method.
ViewXXX PrincipiaSearchSource method?
document_src()Returns the unrendered source text of the DTML Method.
View management screensget_size()Returns the size of the unrendered source text of the DTML Method in bytes.
ViewChange, 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.
Change DTML Methods, REQUEST=None)Replace the contents of the document with the text in file.
Change DTML Methods)Add a DTML Method to the current ObjectManager. The file argument may be a string or a file-like object.
ExternalMethodExternalMethod(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)Calling an External Method is roughly equivalent to calling the original actual function from Python. Positional and keyword parameters can be passed as usual. Note however that unlike the case of a normal Python method, the "self" argument must be passed explicitly. An exception to this rule is made if:
self.In this case, the URL parent of the object is supplied as the first argument. XXX container, not ever context?
manage_edit(title, module, function, REQUEST=None)
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.
manage_addExternalMethod(id, title, module, function, REQUEST=None)ObjectManager
.
In addition to the standard object-creation arguments,
id
and title, the following arguments are defined:
The module normally resides in the Extensions directory;
however, the file name may have a prefix 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.
FolderFolder(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.
, 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.
Add FoldersHTTPRequestFileUploadFile 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
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:
.environ)These variables include input headers, server data, and other request-related data. The variable names are as specified in the CGI specification.
.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).other)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:
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:PARENTSPARENTS[0] would be the ancestor of
the published object.REQUESTRESPONSEPUBLISHEDURLThis 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).
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.
URLPATH0 is the path portion of URL,
URLPATH1 is the path portion of URL1, and so on.
For example if URL=http://localhost/foo/bar, then
URLPATH1=/foo and URLPATH2=/.
BASE0 is the URL up to but not including the Zope
application object. BASE1 is the URL of the Zope application
object. BASE2 is the URL of the Zope application object with
an additional path element added in the path to the published
object. Etcetera.
For example if URL=http://localhost/Zope.cgi/foo/bar, then
BASE0=http://localhost, BASE1=http://localhost/Zope.cgi,
and BASE2=http://localhost/Zope.cgi/foo.
BASEPATH0 is the path portion of BASE0,
BASEPATH1 is the path portion of BASE1, and so on.
BASEPATH1 is the externally visible path to the root Zope
folder, equivalent to CGI's SCRIPT_NAME, but virtual-host aware.
For example if URL=http://localhost/Zope.cgi/foo/bar, then
BASEPATH0='/, BASEPATH1=/Zope.cgi', and BASEPATH2=/Zope.cgi/foo.
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
<span tal:replace="request" />
<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.
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.
getClientAddr()The IP address of the client, as a string. If cannot be determined, the string will be empty.
has_key(key)Returns a true value if the request object contains key, otherwise false.
items()Returns a sequence of (key, value) tuples for all the keys in the request object.
keys()Returns a sorted sequence of all keys in the request object.
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?
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.
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.
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.
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.
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.
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.
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.
values()Returns a sequence of values for all the keys in the request object.
HTTPResponseHTTPResponse
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:
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.
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.
appendHeader(name, value, delimiter=",")Sets an HTTP return header "name" with value "value", appending it following delimiter if there was a previous value set for the header.
badRequestError(name)debugError(entry)enableHTTPCompression,REQUEST={},force=0,disable=0,query=0)Enable HTTP Content Encoding with gzip compression if possible.
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.
forbiddenError(entry="Unknown")notFoundError(entry="Unknown")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").
setBase(base)Set the base URL for the returned document. If base is None, or the document already has a base, has no effect.
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.
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.
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").
unauthorizedwrite(data)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.
ImageFile(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.
Viewget_size()Returns the size of the file in bytes.
Viewindex_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.
Viewmanage_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.
Change Images and Filesmanage_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.
Change Images and Filesupdate_data(data, content_type=None, size=None)XXX Is this really part of the API?
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.
view_image_or_file(URL1)Used by the UI to redirect to the default view of the File or Image.
Viewmanage_addFile(id, file="", title="", precondition="", content_type="", REQUEST=None)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.
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