Appendix B: API Reference
This reference describes the interfaces to the most common set of basic Zope objects. This reference is useful while writing DTML, Perl, and Python scripts that create and manipulate Zope objects.
Anonymous User - June 20, 2002 6:55 pm: This section needs a Table of Contents too.
Anonymous User - June 26, 2002 1:43 pm: The reference describes nearly nothing when you don't know the solution! Examples are absolutely necessary.
Anonymous User - July 12, 2002 3:32 pm: i agree.
Anonymous User - July 14, 2002 5:21 am: Strongly disagree. This is a reference, not a tutorial or explanatory text.
Anonymous User - Aug. 20, 2002 11:13 pm: A reference doesn't contain explanatory text?
Anonymous User - Nov. 12, 2003 10:52 am: Look at http://www.php.net : it's both a precise API reference for PHP developers, and a tutorial full of interesting samples. Apart from the Zope Book (which efficiently sums up the ZMI) I have rarely seen such a poor pedagogical and practical approach as among the zope documentation.
Anonymous User - Nov. 12, 2003 8:18 pm: As a Zope User, imaging my surprise to see this page referenced in the W3C Validator service's tip of the day for further information on how to implement a page redirect instead of a page refresh (see http://www.w3.org/QA/Tips/reback ). What a kudo from the industry! Imagine my disappointment at landing on this mess of bickering commentary as well as no discussion or TOC for finding syntax for redirection. I think a lot of people following the link and unaware of Zope would click 'back' pretty quickly with a lees than positive impression. FWIW, Duke
Anonymous User - Dec. 11, 2003 12:43 am: I agree with the comments suggesting that a table of contents (and an index too perhaps) would enhance the value of this API reference. I also agree that some code snippets showing proper usage and some explanatory notes would help to make this API reference more useful. I come from a Java background.
Anonymous User - Dec. 24, 2003 1:55 am: So convoluted! So frustrating! It would be much more useful to have this information organized in a more hierarchical fashion, like Python's Global Module Index (c.f. http://www.python.org/doc/current/modindex.html)
Anonymous User - Jan. 18, 2004 5:46 am: For the love of god, someone please listen to these suggestions. 1) Table of contents / index 2) General organization (php.net, http://www.python.org/doc/current/modindex.html) 3) Example code. One of greatest things that the PHP community has going for it is a clear, concise, organized reference, WITH EXAMPLES. Newbies get rolling instantly, and advanced users are able to skip to exactly what they're looking for.
edcass - Jan. 18, 2004 7:24 pm: man, I stopped developing in Zope 2 years ago... I thought this would have been dealt with by now. Well, I suppose I'll finish this project off and then check back in in another 2 years. See you then...
furiag - Mar. 1, 2004 5:12 am: This API reference is uncompleted. It doesn´t include commands like manage_clone or manage_delObjects. I guess there are a lot more.
furiag - Mar. 1, 2004 5:52 am: For a quick reference visit the Zope Documentation project at http://zdp.zope.org/ZQR
furiag - Mar. 1, 2004 6:24 am: For a complet reference on APIs (advise: it's huge and you can easily get lost), download http://zdp.zope.org/download/ArchetypesAPIDoc.zip
slinkp - Sep. 7, 2004 7:19 pm: Table of Contents is coming! ... and a whole lot of additions and fixes, too. I'm working on it as part of the Zope Book 2.7 edition. Help would be welcome from experienced Zoperators. It's a big job. Read the in progress version "here":http://www.plope.com/Books/2_7Edition/AppendixB.stx Other chapters need volunteers too. See "the sign-up page":http://www.plope.com/Books/zb_signup
slinkp - Jan. 27, 2005 1:35 am: we really ought to disable commenting while the 2.7 edition is in progress. at this point it's not helpful, it's a spam magnet.
Anonymous User - May 22, 2005 2:02 pm: you're right. go use PHP. or JAVA. "Verily I say unto you, They have their reward." (Mt 6.2) HA HA HA
inflatables - Oct. 16, 2005 11:04 pm: i agree. ----- my inflatables china site http://www.inflatables-china.net
Anonymous User - Apr. 1, 2006 11:25 am: I want mp3 player. What will advise?
Anonymous User - Apr. 5, 2006 5:06 pm: Hi To write the letter, it is necessary ...
Anonymous User - Apr. 10, 2006 12:09 pm: Thank you for being generous with your resources... I hope that you will receive more than you need for your time and energy. Keep at work!
Anonymous User - Apr. 20, 2006 1:55 pm: hi Why I can not insert the image into my message?
Anonymous User - Apr. 30, 2006 2:39 pm: Great page, not too fancy but well balanced! Cheers!
Anonymous User - May 12, 2006 4:12 pm: Tell, and here at you always so?
Anonymous User - May 19, 2006 6:25 pm: Hi! What you do today by evening?
Anonymous User - May 20, 2006 5:42 am: Hi, why nobody responds me?
Anonymous User - May 20, 2006 6:46 am: Hi As to me to create the same page?
Anonymous User - May 29, 2006 9:17 am: Help to choose a videocamera. What standard to choose?
Anonymous User - May 29, 2006 12:00 pm: Help to choose a videocamera. What standard to choose?
Anonymous User - July 19, 2006 7:53 pm: Great new site about mature mom <a href="http://www.xxxmom.info/sexymilf10.html">sexy milf 10</a>. Millions pics and movies t2}</a>!
Anonymous User - July 19, 2006 8:45 pm: <a href="http://www.games-slots-2006.info/ ">http://www.games-slots-2006.info/ </a>, <a href="http://www.games-slots-2006.info/gamblblackj.html">gambling blackjack slots</a>
Anonymous User - Aug. 3, 2006 1:50 pm: Hi Just wanted to thank you guys for uploading such a smooth loading, informative site. <a href="http://www.homedecor-store.info">http://www.homedecor-store.info</a>
Anonymous User - Sep. 1, 2006 7:02 pm: Great new site about hot teens <a href="http://www.hotteenie.info/teenboyspub.html">teen boys puberty</a>. Millions pics and movies <a href="http://www.hotteenie.info/asianteenblowj.html">asian teen blowjob</a>!
Anonymous User - Sep. 17, 2006 12:45 pm: Hi all! This is a great porno site: <a href="http://www.hot-amateur.info/grannysexamatteen.html">granny sex amateur teen video</a> look this hardcore action: <a href="http://www.hot-amateur.info/hannvidsexamatlukesexyjok.html">hannah video sex amateur luke sexy jokes</a> ))
Anonymous User - Sep. 22, 2006 4:15 am: <a href="http://www.game-slots.info/ ">http://www.game-slots.info/ </a>, <a href="http://www.game-slots.info/rulefor.html">rule for playing craps</a>
Anonymous User - Sep. 22, 2006 2:29 pm: <a href="http://www.super-casino1.info/ ">http://www.super-casino1.info/ </a>, <a href="http://www.super-casino1.info/onlineroulette.html">online roulette gambling</a>
Anonymous User - Oct. 2, 2006 10:54 pm: Hi, people!! Great new site about anal sex. <a href="http://www.hotanalmovies.info/asseaters.html">ass eaters galleries</a> The youngest, freshest and hardest porn for FREE! Updates Everyday! <a href="http://www.hotanalmovies.info/asiantight.html">asian tight ass</a> Best porno pics and video !!! All category, millions movies and photos !!! <a href="http://www.hotanalmovies.info/asstraffjasm.html">ass traffic jasmine lynn</a>
Anonymous User - Oct. 3, 2006 2:19 am: Aphrodite love ... <a href="http://www.fantasy-amateur.info/freeliveteensexvidandsampl.html">free live teen sex videos and samples</a> and hotty girlsss:<a href="http://www.fantasy-amateur.info/freenudeamatpictandvideo.html">free nude amateur pictures and video free</a> yes yes yes!!! <a href="http://www.fantasy-amateur.info/freenudecelebs.html">free nude celebs movie amateur fuck</a>
Anonymous User - Oct. 8, 2006 8:46 am: Hi, people!! Great new site about anal toys!!! <a href="http://www.sexanaltoys.info/gaymenass.html">gay men ass licking</a> Hundreds pretty girls put dildos in treir asses!!! <a href="http://www.sexanaltoys.info/teenasspics.html">teen ass pics</a> Enjoy!!
Anonymous User - Oct. 12, 2006 6:17 am: Hi, people!! Great new site about anal sex!!! <a href="http://www.fuckmyassnow.info/monica.html">monica bellucci's naked ass</a> Only best asses!! thousands photos!!! <a href="http://www.fuckmyassnow.info/denis.html">denis leary ass hole song</a> Fantastic!!
Anonymous User - Nov. 1, 2006 7:59 am: <a href="http://www.analmovies-xxx.info/gaymenhav.html">gay men having sex huge cocks</a>Watch these horny sluts taking it in the ass for the first time and getting their virgin butts ripped wide open. <a href="http://www.analmovies-xxx.info/hugedildoporn.html">huge dildo porn videos</a>It’s an experience they will never forget. Frenzied 3some and wild anal actions caught on video are waiting here for you.
Anonymous User - Nov. 1, 2006 11:01 am: They feel so much power licking man’s swollen balls or lying face own on the pillow letting a couple of horny machos work their hard cocks on every hole of their hot bodies…<a href="http://www.porno-hot-wife.info/howbigis.html">how big is kevin bacon's penis</a> But in fact they are just dirty sluts who need to be fucked properly up their ass to make men feel good! <a href="http://www.porno-hot-wife.info/musclegay.html">muscle gay men huge cocks</a>Watch the best videos and pix right here!
Anonymous User - Nov. 5, 2006 4:58 pm: Are you savoring for free-for-all fuck fest with wild bisexual sandwiches and intense outdoor group sex?<a href="http://www.bisexual-movies-xxx.com/bisexinveg.html">bi-sexuals in vegas</a>It’s the paradise for you. Cock-suckers, first bi-timers, double penetration and anal-oral thrills are waiting for you at this site. <a href="http://www.bisexual-movies-xxx.com/freemmfbisinterr.html">free mmf bisexual interrasial images</a>One click and all your dirty bisexual dreams will come true!
Anonymous User - Nov. 8, 2006 8:28 am: dudes, goin’ crazy for the yammy XXXL boobs? <a href="http://www.boobsphoto.info/oralsuck.html">oral suck tits</a> Take a look at the complete range of ‘em all gathered on this page, you’ll be taken away by the variety of the huge tits. <a href="http://www.boobsphoto.info/tittycumshot.html">Titty Cumshot</a> Just think of your dildo squeezed in between… !!
Anonymous User - Nov. 10, 2006 6:56 pm: Sweet delicious <a href="http://www.teenz-loverz.info/bbsteengirlson.html">bbs teen girls on film</a> teens in outrageous hardcore scenes. Follow these young cuties <a href="http://www.teenz-loverz.info/asainteenmin.html">asain teen miniskirt</a> and they’ll show you that they’re not that innocent. Dive down into the world of sex adventures <a href="http://www.teenz-loverz.info/asianyoungteenlesbphoto.html">asian young teen lesbian photo videos</a>. These girls just want to have fun.
Anonymous User - Dec. 2, 2006 2:28 pm: Have you ever dreamed of sweet innocent looking teens in wild and dirty hardcore scenes? 1) <a href="http://www.fuck-10-teens.info/pointyteennud.html">pointy teen nudes</a> 2) <a href="http://www.fuck-10-teens.info/pornteenboard.html">porn teen board</a> 3) <a href="http://www.fuck-10-teens.info/realfreesexy.html">real free sexy teen girls</a>
Anonymous User - Dec. 8, 2006 2:24 am: Hardcore gay XXX actions! Hot buddies with bare sweet asses ready to play all in soap and foam. See them ride cocks and suck the hell out of them. <a href="http://www.extreme-toon-sex.info/picsofgay.html">pics of gay guys pissing</a>Ass-licking, orgies, cock thrusting and much more you can find here, at this gay paradise place! <a href="http://www.extreme-toon-sex.info/gothwom.html">gothic women giving blowjobs</a>
Anonymous User - Dec. 10, 2006 11:19 pm: These anal addicted sluts can take two cocks at once up their shit holes! <a href="http://www.anal-video-xxx.info/hairymusclementoon.html">hairy muscle men toon</a>How about a chick getting all of her three holes plugged or drinking cum after hard ass banging? Yeah, it’s cool! <a href="http://www.anal-video-xxx.info/fistin.html">fist in anal</a>
Anonymous User - Dec. 13, 2006 12:45 am: If hard ass banging, crazy anal ripping and mind-blowing ass-to-mouth are what you’re looking for, you’ve come to the right place! <a href="http://www.anal-movies-xxx.info/femdfoot.html">femdom foot fetish</a>The site is jammed with hardcore anal scenes with dirty blonde bombshells, nasty raven-heads and exotic Asians with extremely tight assholes. <a href="http://www.anal-movies-xxx.info/cheerlead.html">cheerleader fuck tits</a>Enjoy this ass destruction!
Anonymous User - Dec. 24, 2006 11:59 pm: These chicks are cute. no, They are gorgeous, sexy and hot. <a href="http://www.chocolate-boobs.info/hotwetmex.html">hot wet mexican movie thumbs</a>They can't say no to anyone who ask them to suck his cock or take their thongs off to show off their firm little asses. <a href="http://www.chocolate-boobs.info/wetpussypant.html">wet pussy panties</a>But it is not all
Anonymous User - Dec. 28, 2006 11:28 pm: <a href="{link1}">{text1}</a>, <a href="{link2}">{text2}</a>
Anonymous User - Dec. 29, 2006 12:11 am: good website
Anonymous User - Dec. 29, 2006 12:28 am: <a href="{link1}">{text1}</a>, <a href="{link2}">{text2}</a>
Anonymous User - Dec. 29, 2006 2:13 am: good website
Anonymous User - Dec. 29, 2006 2:22 am: <a href="{link1}">{text1}</a>, <a href="{link2}">{text2}</a>
Anonymous User - Dec. 29, 2006 2:39 am: <a href="{link1}">{text1}</a>, <a href="{link2}">{text2}</a>
Anonymous User - Dec. 29, 2006 4:14 am: <a href="{link1}">{text1}</a>, <a href="{link2}">{text2}</a>
module AccessControl
AccessControl: Security functions and classes
The functions and classes in this module are available to Python-based Scripts and Page Templates.
inflatables - Oct. 14, 2005 11:32 pm: I agree -------------- <a href="http://www.inflatables-china.net">inflatable china</a>
class SecurityManager
A security manager provides methods for checking access and managing executable context and policies
calledByExecutable(self)
Return a boolean value indicating if this context was called by an executable.
- permission
- Always available
validate(accessed=None, container=None, name=None, value=None, roles=None)
- accessed
- the object that was being accessed
- container
- the object the value was found in
- name
- The name used to access the value
- value
- The value retrieved though the access.
- roles
- The roles of the object if already known.
The arguments may be provided as keyword arguments. Some of these arguments may be omitted, however, the policy may reject access in some cases when arguments are omitted. It is best to provide all the values possible.
- permission
- Always available
checkPermission(self, permission, object)
Check whether the security context allows the given permission on the given object.
- permission
- Always available
getUser(self)
Get the current authenticated user. See the
AuthenticatedUser
class.
bkwasniewski - Nov. 11, 2003 1:46 pm: Newbie How to use this function in dtml method, plese show an example
flow - Dec. 3, 2003 12:40 am: <dtml-var "AUTHENTICATED_USER.getUserName()"> <dtml-unless "acl_users.authenticate(name=user_name,password=password,request=None)">not</dtml-unless>authenticat ed
Anonymous User - Jan. 13, 2005 11:03 am: ZPT Example: Hello, user <em tal:define="sm python:modules['AccessControl'].getSecurityManager(); user python:sm.getUser()" tal:content="user"> Bob </em>!
Anonymous User - Jan. 13, 2005 11:04 am: Newbie How to use this function in Python script method, plese show an example. HELP!
Anonymous User - Feb. 2, 2005 9:19 am: That would be nice indeed :)
Anonymous User - Feb. 15, 2005 4:22 pm: from AccessControl import getSecurityManager user = getSecurityManager().getUser() # None für Anonymous user found at www.zope.de
Anonymous User - Mar. 25, 2005 12:33 am: newbie when using the above script gives this result user=<bound method SecurityManager.getUser of <SecurityManager instance at 038E9160>> want to get the login name of the user in plone. Help!!
- permission
- Always available
validateValue(self, value, roles=None)
Convenience for common case of simple value validation.
- permission
- Always available
def getSecurityManager()
Returns the security manager. See the SecurityManager
class.
Anonymous User - June 20, 2002 6:56 pm: Examples?
module AuthenticatedUser
class AuthenticatedUser
This interface needs to be supported by objects that are returned by user validation and used for access control.
Anonymous User - July 12, 2002 3:32 pm: i don't seem to be able to access these methods from DTML... example?
Anonymous User - Nov. 1, 2003 1:00 pm: _.SecurityGetUser() returns an AuthenticatedUser reference. So do something like _.SecurityGetUser().has_role('foo')
getUserName()
- Permission
- Always available
getId()
Get the ID of the user. The ID can be used from Python to get the user from the user's UserDatabase.
- Permission
- Always available
has_role(roles, object=None)
Return true if the user has at least one role from a list of roles, optionally in the context of an object.
Anonymous User - Sep. 30, 2005 4:31 am: σδφσδφσδφσ δφ σδφσδφ
- Permission
- Always available
getRoles()
Return a list of the user's roles.
- Permission
- Always available
has_permission(permission, object)
Return true if the user has a permission on an object.
- Permission
- Always available
getRolesInContext(object)
Return the list of roles assigned to the user, including local roles assigned in context of an object.
- Permission
- Always available
getDomains()
Return the list of domain restrictions for a user.
- Permission
- Always available
module DTMLDocument
class DTMLDocument(ObjectManagerItem, PropertyManager)
A DTML Document is a Zope object that contains and executes DTML code. It is useful to represent web pages.
manage_edit(data, title)
Change the DTML Document, replacing its contents with data
and
changing its title.
The data argument may be a file object or a string.
- Permission
Change DTML Documents
document_src()
Returns the unrendered source text of the DTML Document.
- Permission
View management screens
__call__(client=None, REQUEST={}, RESPONSE=None, **kw)
Calling a DTMLDocument causes the Document to interpret the DTML code that it contains. The method returns the result of the interpretation, which can be any kind of object.
To accomplish its task, DTML Document often needs to resolve various
names into objects. For example, when the code <dtml-var
spam>
is executed, the DTML engine tries to resolve the name
spam
.
In order to resolve names, the Document must be passed a namespace to look them up in. This can be done several ways:
- By passing a
client
object -- If the argumentclient
is passed, then names are looked up as attributes on the argument. - By passing a
REQUEST
mapping -- If the argumentREQUEST
is passed, then names are looked up as items on the argument. If the object is not a mapping, an TypeError will be raised when a name lookup is attempted. - By passing keyword arguments -- names and their values can be passed as keyword arguments to the Document.
The namespace given to a DTML Document is the composite of these three methods. You can pass any number of them or none at all. Names are looked up first in the keyword arguments, then in the client, and finally in the mapping.
A DTMLDocument implicitly pass itself as a client argument in addition to the specified client, so names are looked up in the DTMLDocument itself.
Passing in a namespace to a DTML Document is often referred to as providing the Document with a context.
DTML Documents can be called three ways.
From DTML
A DTML Document can be called from another DTML Method or Document:
<dtml-var standard_html_header> <dtml-var aDTMLDocument> <dtml-var standard_html_footer>
In this example, the Document aDTMLDocument
is being called
from another DTML object by name. The calling method
passes the value this
as the client argument and the
current DTML namespace as the REQUEST argument. The above
is identical to this following usage in a DTML Python
expression:
<dtml-var standard_html_header> <dtml-var "aDTMLDocument(_.None, _)"> <dtml-var standard_html_footer>
From Python
Products, External Methods, and Scripts can call a DTML Document in the same way as calling a DTML Document from a Python expression in DTML; as shown in the previous example.
By the Publisher
When the URL of a DTML Document is fetched from Zope, the DTML Document is called by the publisher. The REQUEST object is passed as the second argument to the Document.
- Permission
View
get_size()
Returns the size of the unrendered source text of the DTML Document in bytes.
Anonymous User - June 20, 2002 8:06 am: manage_addDocument should be manage_addDTMLDocument! if you use manage_addDocument, you�ll get a DTML Method...
- Permission
View
ObjectManager Constructor
manage_addDocument(id, title)
Add a DTML Document to the current ObjectManager
module DTMLMethod
class DTMLMethod(ObjectManagerItem)
A DTML Method is a Zope object that contains and executes DTML code. It can act as a template to display other objects. It can also hold small pieces of content which are inserted into other DTML Documents or DTML Methods.
The DTML Method's id is available via the document_id
variable and the title is available via the document_title
variable.
manage_edit(data, title)
Change the DTML Method, replacing its contents with data
and
changing its title.
The data argument may be a file object or a string.
- Permission
Change DTML Methods
document_src()
Returns the unrendered source text of the DTML Method.
- Permission
View management screens
__call__(client=None, REQUEST={}, **kw)
Calling a DTMLMethod causes the Method to interpret the DTML code that it contains. The method returns the result of the interpretation, which can be any kind of object.
To accomplish its task, DTML Method often needs to resolve various
names into objects. For example, when the code <dtml-var
spam>
is executed, the DTML engine tries to resolve the name
spam
.
In order to resolve names, the Method must be passed a namespace to look them up in. This can be done several ways:
- By passing a
client
object -- If the argumentclient
is passed, then names are looked up as attributes on the argument. - By passing a
REQUEST
mapping -- If the argumentREQUEST
is passed, then names are looked up as items on the argument. If the object is not a mapping, an TypeError will be raised when a name lookup is attempted. - By passing keyword arguments -- names and their values can be passed as keyword arguments to the Method.
The namespace given to a DTML Method is the composite of these three methods. You can pass any number of them or none at all. Names will be looked up first in the keyword argument, next in the client and finally in the mapping.
Unlike DTMLDocuments, DTMLMethods do not look up names in their own instance dictionary.
Passing in a namespace to a DTML Method is often referred to as providing the Method with a context.
DTML Methods can be called three ways:
From DTML
A DTML Method can be called from another DTML Method or Document:
<dtml-var standard_html_header> <dtml-var aDTMLMethod> <dtml-var standard_html_footer>
In this example, the Method aDTMLMethod
is being called
from another DTML object by name. The calling method passes
the value this
as the client argument and the current DTML
namespace as the REQUEST argument. The above is identical
to this following usage in a DTML Python expression:
<dtml-var standard_html_header> <dtml-var "aDTMLMethod(_.None, _)"> <dtml-var standard_html_footer>
From Python
Products, External Methods, and Scripts can call a DTML Method in the same way as calling a DTML Method from a Python expression in DTML; as shown in the previous example.
By the Publisher
When the URL of a DTML Method is fetched from Zope, the DTML Method is called by the publisher. The REQUEST object is passed as the second argument to the Method.
- Permission
View
get_size()
Returns the size of the unrendered source text of the DTML Method in bytes.
- Permission
View
ObjectManager Constructor
manage_addDTMLMethod(id, title)
Add a DTML Method to the current ObjectManager
module DateTime
class DateTime
The DateTime object provides an interface for working with dates and times in various formats. DateTime also provides methods for calendar operations, date and time arithmetic and formatting.
Anonymous User - Mar. 25, 2004 7:10 pm: Statement of the type of each method in DateTime would be helpful, for example, what does timezone() return? A string such as "UTC"? Or the number of hours from UTC?
DateTime objects represent instants in time and provide interfaces for controlling its representation without affecting the absolute value of the object.
DateTime objects may be created from a wide variety of string or numeric data, or may be computed from other DateTime objects. DateTimes support the ability to convert their representations to many major timezones, as well as the ability to create a DateTime object in the context of a given timezone.
DateTime objects provide partial numerical behavior:
- Two date-time objects can be subtracted to obtain a time, in days between the two.
- A date-time object and a positive or negative number may be added to obtain a new date-time object that is the given number of days later than the input date-time object.
- A positive or negative number and a date-time object may be added to obtain a new date-time object that is the given number of days later than the input date-time object.
- A positive or negative number may be subtracted from a date-time object to obtain a new date-time object that is the given number of days earlier than the input date-time object.
DateTime objects may be converted to integer, long, or float numbers of days since January 1, 1901, using the standard int, long, and float functions (Compatibility Note: int, long and float return the number of days since 1901 in GMT rather than local machine timezone). DateTime objects also provide access to their value in a float format usable with the python time module, provided that the value of the object falls in the range of the epoch-based time module.
Anonymous User - June 10, 2002 10:51 am: It actually seems to return the time in seconds since 1/1/1970, not 1/1/1901.
Anonymous User - July 24, 2002 2:32 pm: I'm guessing that's a typo -- python has always run time from 1970
Anonymous User - Aug. 20, 2002 12:15 am: epoch [UNIX: prob. from astronomical timekeeping] n. The time and date corresponding to 0 in an operating system's clock and timestamp values. Under most UNIX versions the epoch is 00:00:00 GMT, January 1, 1970; under VMS, it's 00:00:00 of November 17, 1858 (base date of the U.S. Naval Observatory's ephemerides); on a Macintosh, it's the midnight beginning January 1 1904. System time is measured in seconds or ticks past the epoch. Weird problems may ensue when the clock wraps around (see wrap around), which is not necessarily a rare event; on systems counting 10 ticks per second, a signed 32-bit count of ticks is good only for 6.8 years. The 1-tick-per-second clock of UNIX is good only until January 18, 2038, assuming at least some software continues to consider it signed and that word lengths don't increase by then.
Anonymous User - Feb. 16, 2004 10:39 pm: on the win2k Pro you can get the system time by <dtml-call "REQUEST.set('cr_tm',_.DateTime())"> on the win2k Server you can get the system time by <dtml-call "REQUEST.set('cr_tm',_.DateTime().Date()+' '+_.DateTime().Time())"> on the linux red hat9.0 you can get the system time by <dtml-call "REQUEST.set('cr_tm',_.DateTime().Date()+' '+_.DateTime().Time())"> The most different is that on the linux and win2k server you can not get the system time by the function "_.DateTime()" directly. Good Luck everybody We r come from china you can contact with me by this mail address: [email protected] or by the MSN: [email protected]
Anonymous User - May 18, 2005 1:14 am: asdfg
A DateTime object should be considered immutable; all conversion and numeric operations return a new DateTime object rather than modify the current object.
A DateTime object always maintains its value as an absolute UTC time, and is represented in the context of some timezone based on the arguments used to create the object. A DateTime object's methods return values based on the timezone context.
Note that in all cases the local machine timezone is used for representation if no timezone is specified.
DateTimes may be created with from zero to seven arguments.
- If the function is called with no arguments, then the current date/time is returned, represented in the timezone of the local machine.
- If the function is invoked with a single string argument which is a recognized timezone name, an object representing the current time is returned, represented in the specified timezone.
- If the function is invoked with a single string argument
representing a valid date/time, an object representing
that date/time will be returned.
As a general rule, any date-time representation that is recognized and unambiguous to a resident of North America is acceptable.(The reason for this qualification is that in North America, a date like: 2/1/1994 is interpreted as February 1, 1994, while in some parts of the world, it is interpreted as January 2, 1994.) A date/time string consists of two components, a date component and an optional time component, separated by one or more spaces. If the time component is omitted, 12:00am is assumed. Any recognized timezone name specified as the final element of the date/time string will be used for computing the date/time value. (If you create a DateTime with the string
Mar 9, 1997 1:45pm US/Pacific
, the value will essentially be the same as if you had captured time.time() at the specified date and time on a machine in that timezone):e = DateTime("US/Eastern") # returns current date/time, represented in US/Eastern. x = DateTime("1997/3/9 1:45pm") # returns specified time, represented in local machine zone. y = DateTime("Mar 9, 1997 13:45:00") # y is equal to x
The date component consists of year, month, and day values. The year value must be a one-, two-, or four-digit integer. If a one- or two-digit year is used, the year is assumed to be in the twentieth century. The month may be an integer, from 1 to 12, a month name, or a month abbreviation, where a period may optionally follow the abbreviation. The day must be an integer from 1 to the number of days in the month. The year, month, and day values may be separated by periods, hyphens, forward slashes, or spaces. Extra spaces are permitted around the delimiters. Year, month, and day values may be given in any order as long as it is possible to distinguish the components. If all three components are numbers that are less than 13, then a month-day-year ordering is assumed.
The time component consists of hour, minute, and second values separated by colons. The hour value must be an integer between 0 and 23 inclusively. The minute value must be an integer between 0 and 59 inclusively. The second value may be an integer value between 0 and 59.999 inclusively. The second value or both the minute and second values may be omitted. The time may be followed by am or pm in upper or lower case, in which case a 12-hour clock is assumed.
- If the DateTime function is invoked with a single
Numeric argument, the number is assumed to be
a floating point value such as that returned by
time.time().
A DateTime object is returned that represents the gmt value of the time.time() float represented in the local machine's timezone.
- If the function is invoked with two numeric arguments, then the first is taken to be an integer year and the second argument is taken to be an offset in days from the beginning of the year, in the context of the local machine timezone. The date-time value returned is the given offset number of days from the beginning of the given year, represented in the timezone of the local machine. The offset may be positive or negative. Two-digit years are assumed to be in the twentieth century.
- If the function is invoked with two arguments, the first
a float representing a number of seconds past the epoch
in gmt (such as those returned by time.time()) and the
second a string naming a recognized timezone, a DateTime
with a value of that gmt time will be returned, represented
in the given timezone:
import time t = time.time() now_east = DateTime(t,'US/Eastern') # Time t represented as US/Eastern now_west = DateTime(t,'US/Pacific') # Time t represented as US/Pacific # now_east == now_west # only their representations are different
- If the function is invoked with three or more numeric arguments, then the first is taken to be an integer year, the second is taken to be an integer month, and the third is taken to be an integer day. If the combination of values is not valid, then a DateTimeError is raised. Two-digit years are assumed to be in the twentieth century. The fourth, fifth, and sixth arguments specify a time in hours, minutes, and seconds; hours and minutes should be positive integers and seconds is a positive floating point value, all of these default to zero if not given. An optional string may be given as the final argument to indicate timezone (the effect of this is as if you had taken the value of time.time() at that time on a machine in the specified timezone).
If a string argument passed to the DateTime constructor cannot be parsed, it will raise DateTime.SyntaxError. Invalid date, time, or timezone components will raise a DateTime.DateTimeError.
The module function Timezones() will return a list of the timezones recognized by the DateTime module. Recognition of timezone names is case-insensitive.
strftime(format)
Return date time string formatted according to format
Anonymous User - June 26, 2002 2:12 pm: A explanation for the world outside the US would be helpfull. For me it was hard to find something like <dtml-var bobobase_modification_time fmt="%d.%m.%Y %H:%M:%S"> (like we use the date/time in Europe) to understand the time module.
See Python's time.strftime() function.
Anonymous User - Oct. 18, 2005 4:12 am: A reference for 'format' or a pointer to it? Massimo
dow()
Return the integer day of the week, where Sunday is 0
- Permission
- Always available
aCommon()
Return a string representing the object's value in the format: Mar 1, 1997 1:45 pm
- Permission
- Always available
h_12()
Return the 12-hour clock representation of the hour
- Permission
- Always available
Mon_()
- Permission
- Always available
HTML4()
Return the object in the format used in the HTML4.0 specification, one of the standard forms in ISO8601.
Dates are output as: YYYY-MM-DDTHH:MM:SSZ T, Z are literal characters. The time is in UTC.
- Permission
- Always available
greaterThanEqualTo(t)
Compare this DateTime object to another DateTime object OR a floating point number such as that which is returned by the python time module. Returns true if the object represents a date/time greater than or equal to the specified DateTime or time module style time. Revised to give more correct results through comparison of long integer milliseconds.
- Permission
- Always available
dayOfYear()
Return the day of the year, in context of the timezone representation of the object
- Permission
- Always available
lessThan(t)
Compare this DateTime object to another DateTime object OR a floating point number such as that which is returned by the python time module. Returns true if the object represents a date/time less than the specified DateTime or time module style time. Revised to give more correct results through comparison of long integer milliseconds.
- Permission
- Always available
AMPM()
Return the time string for an object to the nearest second.
- Permission
- Always available
isCurrentHour()
Return true if this object represents a date/time that falls within the current hour, in the context of this object's timezone representation
- Permission
- Always available
Month()
- Permission
- Always available
mm()
Return month as a 2 digit string
- Permission
- Always available
ampm()
Return the appropriate time modifier (am or pm)
- Permission
- Always available
hour()
Return the 24-hour clock representation of the hour
- Permission
- Always available
aCommonZ()
Return a string representing the object's value in the format: Mar 1, 1997 1:45 pm US/Eastern
- Permission
- Always available
Day_()
- Permission
- Always available
pCommon()
Return a string representing the object's value in the format: Mar. 1, 1997 1:45 pm
- Permission
- Always available
minute()
- Permission
- Always available
day()
- Permission
- Always available
earliestTime()
Return a new DateTime object that represents the earliest possible time (in whole seconds) that still falls within the current object's day, in the object's timezone context
- Permission
- Always available
Date()
Return the date string for the object.
- Permission
- Always available
Time()
Return the time string for an object to the nearest second.
- Permission
- Always available
isFuture()
Return true if this object represents a date/time later than the time of the call
- Permission
- Always available
greaterThan(t)
Compare this DateTime object to another DateTime object OR a floating point number such as that which is returned by the python time module. Returns true if the object represents a date/time greater than the specified DateTime or time module style time. Revised to give more correct results through comparison of long integer milliseconds.
- Permission
- Always available
TimeMinutes()
Return the time string for an object not showing seconds.
- Permission
- Always available
yy()
Return calendar year as a 2 digit string
- Permission
- Always available
isCurrentDay()
Return true if this object represents a date/time that falls within the current day, in the context of this object's timezone representation
- Permission
- Always available
dd()
Return day as a 2 digit string
- Permission
- Always available
rfc822()
Return the date in RFC 822 format
- Permission
- Always available
isLeapYear()
Return true if the current year (in the context of the object's timezone) is a leap year
- Permission
- Always available
fCommon()
Return a string representing the object's value in the format: March 1, 1997 1:45 pm
- Permission
- Always available
isPast()
Return true if this object represents a date/time earlier than the time of the call
- Permission
- Always available
fCommonZ()
Return a string representing the object's value in the format: March 1, 1997 1:45 pm US/Eastern
- Permission
- Always available
timeTime()
Return the date/time as a floating-point number in UTC, in the format used by the python time module. Note that it is possible to create date/time values with DateTime that have no meaningful value to the time module.
- Permission
- Always available
toZone(z)
Return a DateTime with the value as the current object, represented in the indicated timezone.
- Permission
- Always available
lessThanEqualTo(t)
Compare this DateTime object to another DateTime object OR a floating point number such as that which is returned by the python time module. Returns true if the object represents a date/time less than or equal to the specified DateTime or time module style time. Revised to give more correct results through comparison of long integer milliseconds.
- Permission
- Always available
Mon()
- Permission
- Always available
parts()
Return a tuple containing the calendar year, month, day, hour, minute second and timezone of the object
- Permission
- Always available
isCurrentYear()
Return true if this object represents a date/time that falls within the current year, in the context of this object's timezone representation
- Permission
- Always available
PreciseAMPM()
Return the time string for the object.
- Permission
- Always available
AMPMMinutes()
Return the time string for an object not showing seconds.
- Permission
- Always available
equalTo(t)
Compare this DateTime object to another DateTime object OR a floating point number such as that which is returned by the python time module. Returns true if the object represents a date/time equal to the specified DateTime or time module style time. Revised to give more correct results through comparison of long integer milliseconds.
- Permission
- Always available
pDay()
Return the abbreviated (with period) name of the day of the week
- Permission
- Always available
notEqualTo(t)
Compare this DateTime object to another DateTime object OR a floating point number such as that which is returned by the python time module. Returns true if the object represents a date/time not equal to the specified DateTime or time module style time. Revised to give more correct results through comparison of long integer milliseconds.
- Permission
- Always available
h_24()
Return the 24-hour clock representation of the hour
- Permission
- Always available
pCommonZ()
Return a string representing the object's value in the format: Mar. 1, 1997 1:45 pm US/Eastern
- Permission
- Always available
isCurrentMonth()
Return true if this object represents a date/time that falls within the current month, in the context of this object's timezone representation
- Permission
- Always available
DayOfWeek()
- Permission
- Always available
latestTime()
Return a new DateTime object that represents the latest possible time (in whole seconds) that still falls within the current object's day, in the object's timezone context
- Permission
- Always available
dow_1()
Return the integer day of the week, where Sunday is 1
- Permission
- Always available
timezone()
Return the timezone in which the object is represented.
- Permission
- Always available
year()
Return the calendar year of the object
- Permission
- Always available
PreciseTime()
Return the time string for the object.
- Permission
- Always available
ISO()
Return the object in ISO standard format
Dates are output as: YYYY-MM-DD HH:MM:SS
- Permission
- Always available
millis()
Return the millisecond since the epoch in GMT.
- Permission
- Always available
second()
- Permission
- Always available
month()
Return the month of the object as an integer
- Permission
- Always available
pMonth()
Return the abbreviated (with period) month name.
- Permission
- Always available
aMonth()
Return the abbreviated month name.
- Permission
- Always available
isCurrentMinute()
Return true if this object represents a date/time that falls within the current minute, in the context of this object's timezone representation
- Permission
- Always available
Day()
Return the full name of the day of the week
- Permission
- Always available
aDay()
Return the abbreviated name of the day of the week
- Permission
- Always available
module ExternalMethod
class ExternalMethod
Web-callable functions that encapsulate external Python functions.
The function is defined in an external file. This file is treated
like a module, but is not a module. It is not imported directly,
but is rather read and evaluated. The file must reside in the
Extensions
subdirectory of the Zope installation, or in an
Extensions
subdirectory of a product directory.
Due to the way ExternalMethods are loaded, it is not currently
possible to import Python modules that reside in the Extensions
directory. It is possible to import modules found in the
lib/python
directory of the Zope installation, or in
packages that are in the lib/python
directory.
manage_edit(title, module, function, REQUEST=None)
See the description of manage_addExternalMethod for a
description of the arguments module
and function
.
Note that calling manage_edit
causes the "module" to be
effectively reloaded. This is useful during debugging to see
the effects of changes, but can lead to problems of functions
rely on shared global data.
__call__(*args, **kw)
Calling an External Method is roughly equivalent to calling the original actual function from Python. Positional and keyword parameters can be passed as usual. Note however that unlike the case of a normal Python method, the "self" argument must be passed explicitly. An exception to this rule is made if:
- The supplied number of arguments is one less than the required number of arguments, and
- The name of the function's first argument is
self
.
In this case, the URL parent of the object is supplied as the first argument.
ObjectManager Constructor
manage_addExternalMethod(id, title, module, function)
ObjectManager
.
In addition to the standard object-creation arguments,
id
and title, the following arguments are defined:
- function
- The name of the python function. This can be a an ordinary Python function, or a bound method.
- module
- The name of the file containing the function definition.
The module normally resides in the Extensions
directory, however, the file name may have a prefix of
product.
, indicating that it should be found in a product
directory.
For example, if the module is: ACMEWidgets.foo
, then an
attempt will first be made to use the file
lib/python/Products/ACMEWidgets/Extensions/foo.py
. If this
failes, then the file Extensions/ACMEWidgets.foo.py
will be
used.
module File
class File(ObjectManagerItem, PropertyManager)
A File is a Zope object that contains file content. A File object can be used to upload or download file information with Zope.
Anonymous User - Nov. 26, 2003 4:08 am: What properties do files have? How do you access the most recent modification time of a file using a Python Script? (You've explained earlier how to do it with dtml using bobobase_modification_time, but for some reason the following doesn't work with python: return context.file.bobobase_modification_time
Anonymous User - Dec. 15, 2003 11:33 pm: try this: return context.file.bobobase_modification_time() bobobase_modification_time() is a method, not a data attribute. It should be clearly described here somewhere, but AFAICT it is not.
Anonymous User - May 9, 2004 7:25 am: methods: * get_size() Returns the size in bytes (getSize() is deprecated) Python properties: * data Access to the underlying binary data
Anonymous User - May 24, 2004 5:16 am: I am wondering how to del a file. I can only find addFile method in this API.
Using a File object in Zope is easy. The most common usage is to display the contents of a file object in a web page. This is done by simply referencing the object from DTML:
<dtml-var standard_html_header> <dtml-var FileObject> <dtml-var standard_html_footer>
A more complex example is presenting the File object for download by the user. The next example displays a link to every File object in a folder for the user to download:
<dtml-var standard_html_header> <ul> <dtml-in "objectValues('File')"> <li><a href="<dtml-var absolute_url>"><dtml-var id></a></li> </dtml-in> </ul> <dtml-var standard_html_footer>
In this example, the absolute_url
method and id
are used to
create a list of HTML hyperlinks to all of the File objects in
the current Object Manager.
Also see ObjectManager for details on the objectValues
method.
getContentType()
Returns the content type of the file.
- Permission
View
update_data(data, content_type=None, size=None)
Updates the contents of the File with data
.
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
- Python only
getSize()
Returns the size of the file in bytes.
- Permission
View
ObjectManager Constructor
manage_addFile(id, file="", title="", precondition="", content_type="")
Creates a new File object id
with the contents of file
Anonymous User - June 23, 2002 12:37 am: can you use this to overwrite and existing file? the update object doesn't seem to be able to change the title, just the data of the file
module Folder
class Folder(ObjectManagerItem, ObjectManager, PropertyManager)
A Folder is a generic container object in Zope.
Folders are the most common ObjectManager subclass in Zope.
ObjectManager Constructor
manage_addFolder(id, title)
Add a Folder to the current ObjectManager
- Permission
Add Folders
module Image
class Image(File)
An Image is a Zope object that contains image content. An Image object can be used to upload or download image information with Zope.
Image objects have two properties the define their dimension,
height
and width
. These are calculated when the image is
uploaded. For image types that Zope does not understand, these
properties may be undefined.
Using a Image object in Zope is easy. The most common usage is to display the contents of an image object in a web page. This is done by simply referencing the object from DTML:
<dtml-var standard_html_header> <dtml-var ImageObject> <dtml-var standard_html_footer>
This will generate an HTML IMG tag referencing the URL to the Image. This is equivalent to:
<dtml-var standard_html_header> <dtml-with ImageObject> <img src="<dtml-var absolute_url>"> </dtml-with> <dtml-var standard_html_footer>
You can control the image display more precisely with the tag
method. For example:
<dtml-var "ImageObject.tag(border='5', align='left')">
tag(height=None, width=None, alt=None, scale=0, xscale=0, yscale=0, **args)
This method returns a string which contains an HTML IMG tag reference to the image.
Optionally, the height
, width
, alt
, scale
, xscale
and yscale
arguments can be provided which are turned into
HTML IMG tag attributes. Note, height
and width
are
provided by default, and alt
comes from the title_or_id
method.
Keyword arguments may be provided to support other or future IMG
tag attributes. The one exception to this is the HTML Cascading
Style Sheet tag class
. Because the word class
is a reserved
keyword in Python, you must instead use the keyword argument
css_class
. This will be turned into a class
HTML tag attribute
on the rendered img
tag.
Anonymous User - May 1, 2004 4:06 am: Anyone searching this API to try and find out what attributes can be referenced from TAL is not going to find this very useful. Okay, maybe that's not the reason that this section was written (though I suspect it was auto-generated from __doc__ strings), but there is *no* other reference that I can find (in a morning's searching) that lists what a TAL scripter can expect to be able to access for each object type.
- Permission
View
ObjectManager Constructor
manage_addImage(id, file, title="", precondition="", content_type="")
Creates a new Image object id
with the contents of file
.
module MailHost
class MailHost
MailHost objects work as adapters to Simple Mail Transfer Protocol
(SMTP) servers. MailHosts are used by DTML sendmail
tags
to find the proper host to deliver mail to.
send(messageText, mto=None, mfrom=None, subject=None, encode=None)
Sends an email message where the messageText is an rfc822 formatted message. This allows you complete control over the message headers, including setting any extra headers such as Cc: and Bcc:. The arguments are:
- messageText
- The mail message. It can either be a rfc822 formed text with header fields, or just a body without any header fields. The other arguments given will override the header fields in the message, if they exist.
- mto
- A commaseparated string or list of recipient(s) of the message.
- mfrom
- The address of the message sender.
- subject
- The subject of the message.
- encode
- The rfc822 defined encoding of the message. The
default of
None
means no encoding is done. Valid values arebase64
,quoted-printable
anduuencode
.
simple_send(self, mto, mfrom, subject, body)
Sends a message. Only To:, From: and Subject: headers can be set. The arguments are:
- mto
- A commaseparated string or list of recipient(s) of the message.
- mfrom
- The address of the message sender.
- subject
- The subject of the message.
- body
- The body of the message.
MailHost Constructor
manage_addMailHost(id, title="", smtp_host=None, localhost=localhost, smtp_port=25, timeout=1.0)
Add a mailhost object to an ObjectManager.
module ObjectManager
class ObjectManager
An ObjectManager contains other Zope objects. The contained objects are Object Manager Items.
ajung - June 20, 2002 8:39 am: why are the manage_* () functions missing? people are asking how to delete an object from the objectmanager and there is no documentation here.
Anonymous User - July 21, 2002 12:33 am: For anyone who is actually trying to figure out how to delete an object, refer to... http://www.zope.org/Members/Mammux/removeZClasses
Anonymous User - Feb. 16, 2004 2:34 am: Thanks for the hint! I was going to write a mail to the newsgroup asking about this. The Zope documentation definitely needs a major overhaul! Man I love the PHP documentation. Why can't the Zope documentation be like that?
To create an object inside an object manager use 'manage_addProduct':
self.manage_addProduct['OFSP'].manage_addFolder(id, title)
Anonymous User - June 13, 2002 4:37 pm: what is OFSP?????? explanation would help here...
Anonymous User - June 1, 2004 5:54 am: I can create a folder inside another one without manage_addProduct: Folder.manage_addFolder (id, title) But I can't create a Python Script. Folder.manage_addPythonScript (id) - does not work. I think it is a bag and it is necessary to correct this. Why do I need to make an additional call? At least this must be reported in section dedicated to the Script (Python) API This is a
Anonymous User - June 3, 2004 6:58 am: for good sake - could anyone responsible for this script take some time and power to made it a little bit more readable? i cant believe its everyone all the same...
<dtml-call "manage_addProduct['OFSP'].manage_addFolder(id, title)">
These examples create a new Folder inside the current ObjectManager.
manage_addProduct
is a mapping that provides access to product
constructor methods. It is indexed by product id.
Constructor methods are registered during product initialization and should be documented in the API docs for each addable object.
Anonymous User - Mar. 6, 2004 6:35 pm: What permissions are needed for manage_addProduct??
objectItems(type=None)
This method returns a sequence of (id, object) tuples.
Like objectValues and objectIds, it accepts one argument, either a string or a list to restrict the results to objects of a given meta_type or set of meta_types.
Each tuple's first element is the id of an object contained in the Object Manager, and the second element is the object itself.
<dtml-in objectItems> id: <dtml-var sequence-key>, type: <dtml-var meta_type> <dtml-else> There are no sub-objects. </dtml-in>
- Permission
Access contents information
superValues(type)
This method returns a list of objects of a given meta_type(es) contained in the Object Manager and all its parent Object Managers.
The type argument specifies the meta_type(es). It can be a string specifying one meta_type, or it can be a list of strings to specify many.
- Permission
- Python only
objectValues(type=None)
This method returns a sequence of contained objects.
Like objectItems and objectIds, it accepts one argument, either a string or a list to restrict the results to objects of a given meta_type or set of meta_types.
<dtml-in expr="objectValues('Folder')"> <dtml-var icon> This is the icon for the: <dtml-var id> Folder<br>. <dtml-else> There are no Folders. </dtml-in>
Anonymous User - July 17, 2002 9:30 pm: The above sample illustrates how to pass a meta_type to the objectValues method. But how do you pass a set of meta_types to objectValues method?
Anonymous User - July 17, 2002 9:40 pm: Use list to specify a set of meta_types, try this: <dtml-in expr="objectValues(['File','Folder'])"> ... </dtml-in>
Anonymous User - Apr. 18, 2005 11:48 pm: What do meta_types include? What is the meta_type of the External File ?
The results were restricted to Folders by passing a
meta_type to objectValues
method.
- Permission
Access contents information
objectIds(type=None)
This method returns a list of the ids of the contained objects.
Optionally, you can pass an argument specifying what object meta_type(es) to restrict the results to. This argument can be a string specifying one meta_type, or it can be a list of strings to specify many.
<dtml-in objectIds> <dtml-var sequence-item> <dtml-else> There are no sub-objects. </dtml-in>
This DTML code will display all the ids of the objects contained in the current Object Manager.
- Permission
Access contents information
module ObjectManagerItem
class ObjectManagerItem
A Zope object that can be contained within an Object Manager. Almost all Zope objects that can be managed through the web are Object Manager Items.
ObjectMangerItems have these instance attributes:
-
title
- The title of the object.
This is an optional one-line string description of the object.
-
meta_type
- A short name for the type of the object.
This is the name that shows up in product add list for the object and is used when filtering objects by type.
This attribute is provided by the object's class and should not be changed directly.
-
REQUEST
- The current web request.
title_or_id()
If the title is not blank, return it, otherwise return the id.
- Permission
- Always available
getPhysicalRoot()
Returns the top-level Zope Application object.
- Permission
- Python only
manage_workspace()
This is the web method that is called when a user selects an item in a object manager contents view or in the Zope Management navigation view.
- Permission
View management screens
getPhysicalPath()
Get the path of an object from the root, ignoring virtual hosts.
- Permission
- Always available
unrestrictedTraverse(path, default=None)
Return the object obtained by traversing the given path from the object on which the method was called. This method begins with "unrestricted" because (almost) no security checks are performed.
If an object is not found then the default
argument will be
returned.
- Permission
- Python only
getId()
The id
is the unique name of the object within its parent
object manager. This should be a string, and can contain
letters, digits, underscores, dashes, commas, and spaces.
This method replaces direct access to the id
attribute.
- Permission
- Always available
absolute_url(relative=None)
Return the absolute url to the object.
If the relative argument is provided with a true value, then the URL returned is relative to the site object. Note, if virtual hosts are being used, then the path returned is a logical, rather than a physical path.
Anonymous User - Feb. 5, 2004 4:46 am: What's the type of the 'absolute url' object returned? Is it a string, or what?
Anonymous User - Mar. 31, 2004 9:29 pm: Ummm - the text doesn't say an 'absolute url' object is returned, it says an absolute url to the object is returned...Hence, the returned value would be a string.
- Permission
- Always available
this()
This turns out to be handy in two situations. First, it provides a way to refer to an object in DTML expressions.
The second use for this is rather deep. It provides a way to acquire an object without getting the full context that it was acquired from. This is useful, for example, in cases where you are in a method of a non-item subobject of an item and you need to get the item outside of the context of the subobject.
- Permission
- Always available
restrictedTraverse(path, default=None)
Return the object obtained by traversing the given path from the object on which the method was called, performing security checks along the way.
Anonymous User - Mar. 17, 2004 12:14 pm: If the object cannot be traversed to, and the default argument is not supplied, this returns a key error. If the default argument is supplied (even if default=None) you get the default value.
If an object is not found then the default
argument will be
returned.
- Permission
- Always available
title_and_id()
If the title is not blank, return the title followed by the id in parentheses. Otherwise return the id.
- Permission
- Always available
module PropertyManager
class PropertyManager
A Property Manager object has a collection of typed attributes called properties. Properties can be managed through the web or via DTML.
In addition to having a type, properties can be writable or read-only and can have default values.
propertyItems()
Return a list of (id, property) tuples.
- Permission
Access contents information
propertyValues()
Returns a list of property values.
- Permission
Access contents information
propertyMap()
Returns a tuple of mappings, giving meta-data for properties.
The meta-data includes id
, type
, and mode
.
- Permission
Access contents information
propertyIds()
Returns a list of property ids.
- Permission
Access contents information
getPropertyType(id)
Get the type of property id
. Returns None if no such
property exists.
Anonymous User - Feb. 15, 2004 1:59 pm: how do you set a property value
furiag - Mar. 1, 2004 4:03 am: Look at the module PropertySheet: manage_changeProperties, manage_addProperty
- Permission
Access contents information
getProperty(id, d=None)
Return the value of the property id
. If the property is not
found the optional second argument or None is returned.
- Permission
Access contents information
hasProperty(id)
Returns a true value if the Property Manager has the property
id
. Otherwise returns a false value.
Anonymous User - Dec. 22, 2003 12:44 am: 1. what is this true value that the function return? 2. why is it i can use user.getProperty('email') which i use only getSecurityManager() and getUser(), shouldnt i use propertymanager as well??
Anonymous User - Dec. 3, 2004 11:38 pm: 1. before referencing to the API, you should be more or less familiar with python, if you are those questiong won't arise 2. you can use getUser(arguments).getProperty(arguments) that too is a python concept, please learn some python before seriously using zope
- Permission
Access contents information
module PropertySheet
class PropertySheet
A PropertySheet is an abstraction for organizing and working with a set of related properties. Conceptually it acts like a container for a set of related properties and meta-data describing those properties. A PropertySheet may or may not provide a web interface for managing its properties.
xml_namespace()
Return a namespace string usable as an xml namespace for this property set. This may be an empty string if there is no default namespace for a given property sheet (especially property sheets added in ZClass definitions).
- Permission
- Python only
propertyItems()
Return a list of (id, property) tuples.
- Permission
Access contents information
propertyValues()
Returns a list of actual property values.
- Permission
Access contents information
getPropertyType(id)
Get the type of property id
. Returns None if no such
property exists.
Anonymous User - May 22, 2002 7:25 am: For ZClasses: use as: context.propertysheets.propertysheetname.propertyItems() in Python scripts and as: <dtml-var "propertysheets.propertysheetname.propertyItems()"> in DTML, where propertysheetname is the name of the property sheet you've defined in the ZClass.
- Permission
- Python only
propertyInfo()
Returns a mapping containing property meta-data.
- Permission
- Python only
getProperty(id, d=None)
Get the property id
, returning the optional second
argument or None if no such property is found.
- Permission
- Python only
manage_delProperties(ids=None, REQUEST=None)
Delete one or more properties with the given ids
. The ids
argument should be a sequence (tuple or list) containing the
ids of the properties to be deleted. If ids
is empty no
action will be taken. If any of the properties named in ids
does not exist, an error will be raised.
Some objects have "special" properties defined by product
authors that cannot be deleted. If one of these properties is
named in ids
, an HTML error message is returned.
If no value is passed in for REQUEST
, the method will return
None. If a value is provided for REQUEST
(as it will be when
called via the web), the property management form for the
object will be rendered and returned.
This method may be called via the web, from DTML or from Python code.
- Permission
Manage Properties
manage_changeProperties(REQUEST=None, **kw)
Change existing object properties by passing either a mapping
object as REQUEST
containing name:value pairs or by passing
name=value keyword arguments.
Some objects have "special" properties defined by product authors that cannot be changed. If you try to change one of these properties through this method, an error will be raised.
Note that no type checking or conversion happens when this method is called, so it is the caller's responsibility to ensure that the updated values are of the correct type. This should probably change.
If a value is provided for REQUEST
(as it will be when
called via the web), the method will return an HTML message
dialog. If no REQUEST is passed, the method returns None
on
success.
This method may be called via the web, from DTML or from Python code.
- Permission
Manage Properties
manage_addProperty(id, value, type, REQUEST=None)
Add a new property with the given id
, value
and type
.
-
boolean
- 1 or 0.
-
date
- A
DateTime
value, for example12/31/1999 15:42:52 PST
. -
float
- A decimal number, for example
12.4
. -
int
- An integer number, for example,
12
. -
lines
- A list of strings, one per line.
-
long
- A long integer, for example
12232322322323232323423
. -
string
- A string of characters, for example
This is a string
. -
text
- A multi-line string, for example a paragraph.
-
tokens
- A list of strings separated by white space, for example
one two three
. -
selection
- A string selected by a pop-up menu.
-
multiple selection
- A list of strings selected by a selection list.
This method will use the passed in type
to try to convert
the value
argument to the named type. If the given value
cannot be converted, a ValueError will be raised.
The value given for selection
and multiple selection
properites may be an attribute or method name. The attribute
or method must return a sequence values.
If the given type
is not recognized, the value
and type
given are simply stored blindly by the object.
If no value is passed in for REQUEST
, the method will return
None
. If a value is provided for REQUEST
(as it will when
called via the web), the property management form for the
object will be rendered and returned.
This method may be called via the web, from DTML or from Python code.
- Permission
Manage Properties
propertyMap()
Returns a tuple of mappings, giving meta-data for properties.
- Permssion
- Python only
propertyIds()
Returns a list of property ids.
- Permission
Access contents information
hasProperty(id)
Returns true if self
has a property with the given id
,
false otherwise.
- Permission
Access contents information
module PropertySheets
class PropertySheets
A PropertySheet is an abstraction for organizing and working with a set of related properties. Conceptually it acts like a container for a set of related properties and meta-data describing those properties. PropertySheet objects are accessed through a PropertySheets object that acts as a collection of PropertySheet instances.
Objects that support property sheets (objects that support the
PropertyManager interface or ZClass objects) have a
propertysheets
attribute (a PropertySheets instance) that is the
collection of PropertySheet objects. The PropertySheets object
exposes an interface much like a Python mapping, so that
individual PropertySheet objects may be accessed via
dictionary-style key indexing.
get(name, default=None)
Return the PropertySheet identified by name
, or the value
given in default
if the named PropertySheet is not found.
- Permission
- Python only
values()
Return a sequence of all of the PropertySheet objects in the collection.
- Permission
- Python only
items()
Return a sequence containing an (id, object)
tuple for
each PropertySheet object in the collection.
- Permission
- Python only
module PythonScript
class PythonScript(Script)
Python Scripts contain python code that gets executed when you call the script by:
- Calling the script through the web by going to its location with a web browser.
- Calling the script from another script object.
- Calling the script from a method object, such as a DTML Method.
Python Scripts can contain a "safe" subset of the python language. Python Scripts must be safe because they can be potentially edited by many different users through an insecure medium like the web. The following safety issues drive the need for secure Python Scripts:
- Because many users can use Zope, a Python Script must make sure it does not allow a user to do something they are not allowed to do, like deleting an object they do not have permission to delete. Because of this requirement, Python Scripts do many security checks in the course of their execution.
- Because Python Scripts can be edited through the insecure medium of
the web, they are not allowed access to the Zope server's
file-system. Normal Python builtins like
open
are, therefore, not allowed. - Because many standard Python modules break the above two security
restrictions, only a small subset of Python modules may be imported
into a Python Scripts with the "import" statement unless they have
been validated by Zope's security policy. Currently, the following
standard python modules have been validated:
- string
- math
- whrandom and random
- Products.PythonScripts.standard
- Because it allows you to execute arbitrary python code, the python "exec" statement is not allowed in Python methods.
- Because they may represent or cause security violations, some
Python builtin functions are not allowed. The following
Python builtins are not allowed:
- open
- input
- raw_input
- eval
- execfile
- compile
- type
- coerce
- intern
- dir
- globals
- locals
- vars
- buffer
- reduce
- Other builtins are restricted in nature. The following builtins
are restricted:
- range
- Due to possible memory denial of service attacks, the range builtin is restricted to creating ranges less than 10,000 elements long.
- filter, map, tuple, list
- For the same reason, builtins that construct lists from sequences do not operate on strings.
- getattr, setattr, delattr
- Because these may enable Python code to circumvent Zope's security system, they are replaced with custom, security constrained versions.
- In order to be consistent with the Python expressions
available to DTML, the builtin functions are augmented with a
small number of functions and a class:
- test
- namespace
- render
- same_type
- DateTime
- Because the "print" statement cannot operate normally in Zope, its effect has been changed. Rather than sending text to stdout, "print" appends to an internal variable. The special builtin name "printed" evaluates to the concatenation of all text printed so far during the current execution of the script.
document_src(REQUEST=None, RESPONSE=None)
Return the text of the read
method, with content type
text/plain
set on the RESPONSE.
ZPythonScript_edit(params, body)
Change the parameters and body of the script. This method accepts two arguments:
- params
- The new value of the Python Script's parameters. Must be a comma seperated list of values in valid python function signature syntax. If it does not contain a valid signature string, a SyntaxError is raised.
- body
- The new value of the Python Script's body. Must contain valid Python syntax. If it does not contain valid Python syntax, a SyntaxError is raised.
ZPythonScript_setTitle(title)
Change the script's title. This method accepts one argument,
title
which is the new value for the script's title and must be a
string.
ZPythonScriptHTML_upload(REQUEST, file="")
Pass the text in file to the write
method.
write(text)
Change the script by parsing the text argument into parts.
Leading lines that begin with ##
are stripped off, and if
they are of the form ##name=value
, they are used to set
meta-data such as the title and parameters. The remainder of
the text is set as the body of the Python Script.
ZScriptHTML_tryParams()
Return a list of the required parameters with which to test the script.
read()
Return the body of the Python Script, with a special comment
block prepended. This block contains meta-data in the form of
comment lines as expected by the write
method.
ZPythonScriptHTML_editAction(REQUEST, title, params, body)
Change the script's main parameters. This method accepts the following arguments:
- REQUEST
- The current request.
- title
- The new value of the Python Script's title. This must be a string.
- params
- The new value of the Python Script's parameters. Must be a comma seperated list of values in valid python function signature syntax. If it does not contain a valid signature string, a SyntaxError is raised.
- body
- The new value of the Python Script's body. Must contain valid Python syntax. If it does not contain valid Python syntax, a SyntaxError is raised.
Anonymous User - June 1, 2004 5:59 am: There is no comment button in the next statement, so I will provide one here. Note that there is a bug in the manage_addPythonScript method!!! To create a script you must use the following construction: Folder.manage_addProduct['PythonScripts'].manage_addPythonScript(...) instead of Folder.manage_addPythonScript(...) I think this should be corrected in the following releases!
ObjectManager Constructor
manage_addPythonScript(id, REQUEST=None)
Add a Python script to a folder.
module Request
class Request
The request object encapsulates all of the information regarding the current request in Zope. This includes, the input headers, form data, server data, and cookies.
Anonymous User - June 14, 2004 1:25 pm: how can I retrieve the raw request data?
bahriesz - Mar. 11, 2005 4:52 am: One question. How do we set the http status of the Request reply back to browser?. This is needed in situation where we defined our own http status. Those you are familiar with snakelets framework, there is request.send_error(code, message).
The request object is a mapping object that represents a collection of variable to value mappings. In addition, variables are divided into five categories:
- Environment variables
These variables include input headers, server data, and other request-related data. The variable names are as specified in the CGI specification
- Form data
These are data extracted from either a URL-encoded query string or body, if present.
Anonymous User - Mar. 11, 2004 4:12 pm: Is there some way to just get the form data name/value pairs from the REQUEST object?
neaj - July 7, 2004 4:57 pm: REQUEST.form (it's a dictionary).
Anonymous User - Aug. 2, 2004 9:55 pm: Great tip. Very helpful when using Formulator.
Anonymous User - Feb. 27, 2005 9:54 am: Any details about cookies? How to get cookie value/content? This description is incomplete (i.e. where is reference of REQUEST.cookies.has_key??)
- Cookies
- Lazy Data
These are callables which are deferred until explicitly referenced, at which point they are resolved (called) and the result stored as "other" data, ie regular request data.
Thus, they are "lazy" data items. An example is SESSION objects.
Lazy data in the request may only be set by the Python method set_lazy(name,callable) on the REQUEST object. This method is not callable from DTML or through the web.
- Other
The request object may be used as a mapping object, in which case values will be looked up in the order: environment variables, other variables, form data, and then cookies.
These special variables are set in the Request:
-
PARENTS
- A list of the objects traversed to get to the
published object. So,
PARENTS[0]
would be the ancestor of the published object. -
REQUEST
- The Request object.
-
RESPONSE
- The Response object.
-
PUBLISHED
- The actual object published as a result of url traversal.
-
URL
- The URL of the Request without query string.
- URLn
URL0
is the same asURL
.URL1
is the same asURL0
with the last path element removed.URL2
is the same asURL1
with the last element removed. Etcetera.For example if URL=
http://localhost/foo/bar
, then URL1=http://localhost/foo
and URL2=http://localhost
.- URLPATHn
URLPATH0
is the path portion ofURL
,URLPATH1
is the path portion ofURL1
, and so on.For example if URL=
http://localhost/foo/bar
, then URLPATH1=/foo
and URLPATH2=/
.- BASEn
BASE0
is the URL up to but not including the Zope application object.BASE1
is the URL of the Zope application object.BASE2
is the URL of the Zope application object with an additional path element added in the path to the published object. Etcetera.For example if URL=
http://localhost/Zope.cgi/foo/bar
, then BASE0=http://localhost
, BASE1=http://localhost/Zope.cgi
, and BASE2=http://localhost/Zope.cgi/foo
.- BASEPATHn
BASEPATH0
is the path portion ofBASE0
,BASEPATH1
is the path portion ofBASE1
, and so on.BASEPATH1
is the externally visible path to the root Zope folder, equivalent to CGI'sSCRIPT_NAME
, but virtual-host aware.For example if URL=
http://localhost/Zope.cgi/foo/bar
, then BASEPATH0='/, BASEPATH1=
/Zope.cgi', and BASEPATH2=/Zope.cgi/foo
.Anonymous User - July 22, 2004 10:08 am: Very poor explanation. It does not even explain in a single sentence what a "request" is; thus the name is meaningless, or worse, confusing. It looks like the thing should be called INFO_CONTAINER
laotseu - July 29, 2004 5:38 pm: select * from AnonymousUser where clue > 0; ... duh ! zero records found...
Anonymous User - May 6, 2002 8:30 am: compared to what i know or see with dtml-var REQUEST, this list is incomplete, if not very, very sparse at least a ref to a complete list would be ok
get_header(name, default=None)
Return the named HTTP header, or an optional default argument
or None if the header is not found. Note that both original
and CGI header names without the leading HTTP_
are
recognized, for example, Content-Type
, CONTENT_TYPE
and
HTTP_CONTENT_TYPE
should all return the Content-Type header,
if available.
- Permission
- Always available
items()
Returns a sequence of (key, value) tuples for all the keys in the REQUEST object.
Anonymous User - May 18, 2005 7:35 pm: Some common keys are ['ACTUAL_URL', 'AUTHENTICATED_USER', 'AUTHENTICATION_PATH', 'BASE1', 'BASE2', 'BASE3', 'BASE4', 'GATEWAY_INTERFACE', 'HTTP_ACCEPT', 'HTTP_ACCEPT_CHARSET', 'HTTP_ACCEPT_ENCODING', 'HTTP_ACCEPT_LANGUAGE', 'HTTP_COOKIE', 'HTTP_HOST', 'HTTP_KEEP_ALIVE', 'HTTP_REFERER', 'HTTP_USER_AGENT', 'PARENTS', 'PATH_INFO', 'PATH_TRANSLATED', 'PUBLISHED', 'REMOTE_ADDR', 'REQUEST_METHOD', 'RESPONSE', 'SCRIPT_NAME', 'SERVER_NAME', 'SERVER_PORT', 'SERVER_PROTOCOL', 'SERVER_SOFTWARE', 'SERVER_URL', 'SESSION', 'TraversalRequestNameStack', 'URL', 'URL1', 'URL2', 'URL3', '__cp', 'traverse_subpath', 'tree-s']
- Permission
- Always available
keys()
Returns a sorted sequence of all keys in the REQUEST object.
- Permission
- Always available
setVirtualRoot(path, hard=0)
Alters URL
, URLn
, URLPATHn
, BASEn
, BASEPATHn
, and
absolute_url()
so that the current object has path path
.
If hard
is true, PARENTS
is emptied.
Provides virtual hosting support. Intended to be called from publishing traversal hooks.
- Permission
- Always available
values()
Returns a sequence of values for all the keys in the REQUEST object.
- Permission
- Always available
set(name, value)
Create a new name in the REQUEST object and assign it a value.
This name and value is stored in the Other
category.
- Permission
- Always available
has_key(key)
Returns a true value if the REQUEST object contains key, returns a false value otherwise.
- Permission
- Always available
setServerURL(protocol=None, hostname=None, port=None)
Sets the specified elements of SERVER_URL
, also affecting
URL
, URLn
, BASEn
, and absolute_url()
.
Anonymous User - June 18, 2005 9:12 pm: cool
Provides virtual hosting support.
- Permission
- Always available
module Response
class Response
The Response object represents the response to a Zope request.
setHeader(name, value)
Sets an HTTP return header "name" with value "value", clearing the previous value set for the header, if one exists. If the literal flag is true, the case of the header name is preserved, otherwise word-capitalization will be performed on the header name on output.
- Permission
- Always available
setCookie(name, value, **kw)
Set an HTTP cookie on the browser
The response will include an HTTP header that sets a cookie on cookie-enabled browsers with a key "name" and value "value". This overwrites any previously set value for the cookie in the Response object.
Anonymous User - May 1, 2002 6:59 am: great, but where is the getCookie method? In particular how do I force it to look for a key in the cookie, as opposed to the headers or elsewhere?
Anonymous User - May 7, 2002 7:29 pm: apparently you may reference cookies like any other dtml variable, but within dtml. still trying to figure out how to reference dtml variables within python
Anonymous User - May 30, 2002 5:09 pm: You *get* cookies from the REQUEST, not the RESPONSE.
Anonymous User - June 14, 2002 12:48 pm: To reference a dtml variable called 'test', within python: request = container.REQUEST RESPONSE = request.RESPONSE test = request.test
Anonymous User - 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. domain=DOMAIN_NAME When searching the cookie list for valid cookies, a comparison of the domain attributes of the cookie is made with the Internet domain name of the host from which the URL will be fetched. If there is a tail match, then the cookie will go through path matching to see if it should be sent. "Tail matching" means that domain attribute is matched against the tail of the fully qualified domain name of the host. A domain attribute of "acme.com" would match host names "anvil.acme.com" as well as "shipping.crate.acme.com". Only hosts within the specified domain can set a cookie for a domain and domains must have at least two (2) or three (3) periods in them to prevent domains of the form: ".com", ".edu", and "va.us". Any domain that fails within one of the seven special top level domains listed below only require two periods. Any other domain requires at least three. The seven special top level domains are: "COM", "EDU", "NET", "ORG", "GOV", "MIL", and "INT". The default value of domain is the host name of the server which generated the cookie response. path=PATH The path attribute is used to specify the subset of URLs in a domain for which the cookie is valid. If a cookie has already passed domain matching, then the pathname component of the URL is compared with the path attribute, and if there is a match, the cookie is considered valid and is sent along with the URL request. The path "/foo" would match "/foobar" and "/foo/bar.html". The path "/" is the most general path. If the path is not specified, it as assumed to be the same path as the document being described by the header which contains the cookie. secure If a cookie is marked secure, it will only be transmitted if the communications channel with the host is a secure one. Currently this means that secure cookies will only be sent to HTTPS (HTTP over SSL) servers. If secure is not specified, a cookie is considered safe to be sent in the clear over unsecured channels.
- Permission
- Always available
addHeader(name, value)
Set a new HTTP return header with the given value, while retaining any previously set headers with the same name.
- Permission
- Always available
appendHeader(name, value, delimiter=,)
Sets an HTTP return header "name" with value "value", appending it following a comma if there was a previous value set for the header.
- Permission
- Always available
write(data)
HTML data may be returned using a stream-oriented interface. This allows the browser to display partial results while computation of a response to proceed.
The published object should first set any output headers or cookies on the response object.
Note that published objects must not generate any errors after beginning stream-oriented output.
- Permission
- Always available
setStatus(status, reason=None)
Sets the HTTP status code of the response; the argument may either be an integer or one of the following strings:
OK, Created, Accepted, NoContent, MovedPermanently, MovedTemporarily, NotModified, BadRequest, Unauthorized, Forbidden, NotFound, InternalError, NotImplemented, BadGateway, ServiceUnavailable
that will be converted to the correct integer value.
- Permission
- Always available
setBase(base)
Set the base URL for the returned document.
- Permission
- Always available
expireCookie(name, **kw)
Cause an HTTP cookie to be removed from the browser
The response will include an HTTP header that will remove the cookie corresponding to "name" on the client, if one exists. This is accomplished by sending a new cookie with an expiration date that has already passed. Note that some clients require a path to be specified - this path must exactly match the path given when creating the cookie. The path can be specified as a keyword argument.
Anonymous User - Mar. 1, 2005 6:22 pm: ,,
- Permission
- Always available
appendCookie(name, value)
Returns an HTTP header that sets a cookie on cookie-enabled browsers with a key "name" and value "value". If a value for the cookie has previously been set in the response object, the new value is appended to the old one separated by a colon.
- Permission
- Always available
redirect(location, lock=0)
Cause a redirection without raising an error. If the "lock" keyword argument is passed with a true value, then the HTTP redirect response code will not be changed even if an error occurs later in request processing (after redirect() has been called).
Anonymous User - Mar. 1, 2004 4:08 pm: You can also set the http response status with an additional arg. For example: redirect('http://www.google.com/', status=301, lock=1).
- Permission
- Always available
Script
Script module
This provides generic script support
class Script
Web-callable script base interface.
ZScriptHTML_tryAction(REQUEST, argvars)
Apply the test parameters provided by the dictionary argvars
.
This will call the current script with the given arguments and
return the result.
module SessionInterfaces
Session API
class SessionDataManagerErr
Error raised during some session data manager operations, as explained in the API documentation of the Session Data Manager.
Anonymous User - July 17, 2002 5:24 am: Transient Object API link above is broken!
This exception may be caught in PythonScripts. A successful import of the exception for PythonScript use would need to be:
from Products.Sessions import SessionDataManagerErr
class BrowserIdManagerInterface
Zope Browser Id Manager interface.
A Zope Browser Id Manager is responsible for assigning ids to site visitors, and for servicing requests from Session Data Managers related to the browser id.
getBrowserId(self, create=1)
If create=0, returns a the current browser id or None if there is no browser id associated with the current request. If create=1, returns the current browser id or a newly-created browser id if there is no browser id associated with the current request. This method is useful in conjunction with getBrowserIdName if you wish to embed the browser-id-name/browser-id combination as a hidden value in a POST-based form. The browser id is opaque, has no business meaning, and its length, type, and composition are subject to change.
Permission required: Access contents information
Raises: BrowserIdManagerErr if ill-formed browser id is found in REQUEST.
isBrowserIdFromCookie(self)
Returns true if browser id comes from a cookie.
Permission required: Access contents information
Raises: BrowserIdManagerErr. If there is no current browser id.
isBrowserIdNew(self)
Returns true if browser id is new
. A browser id is new
when it is first created and the client has therefore not sent it
back to the server in any request.
Permission required: Access contents information
Raises: BrowserIdManagerErr. If there is no current browser id.
encodeUrl(self, url)
Encodes a provided URL with the current request's browser id
and returns the result. For example, the call
encodeUrl(http://foo.com/amethod
) might return
http://foo.com/amethod?_ZopeId=as9dfu0adfu0ad
.
Permission required: Access contents information
Raises: BrowserIdManagerErr. If there is no current browser id.
flushBrowserIdCookie(self)
Deletes the browser id cookie from the client browser, iff the
cookies
browser id namespace is being used.
Permission required: Access contents information
Raises: BrowserIdManagerErr. If the cookies
namespace isn't
a browser id namespace at the time of the call.
getBrowserIdName(self)
Returns a string with the name of the cookie/form variable which is
used by the current browser id manager as the name to look up when
attempting to obtain the browser id value. For example, _ZopeId
.
Permission required: Access contents information
isBrowserIdFromForm(self)
Returns true if browser id comes from a form variable (query string or post).
Permission required: Access contents information
Raises: BrowserIdManagerErr. If there is no current browser id.
hasBrowserId(self)
Returns true if there is a browser id for this request.
Permission required: Access contents information
setBrowserIdCookieByForce(self, bid)
Sets the browser id cookie to browser id bid
by force.
Useful when you need to chain
browser id cookies across domains
for the same user (perhaps temporarily using query strings).
Permission required: Access contents information
Raises: BrowserIdManagerErr. If the cookies
namespace isn't
a browser id namespace at the time of the call.
class BrowserIdManagerErr
Error raised during some browser id manager operations, as explained in the API documentation of the Browser Id Manager.
This exception may be caught in PythonScripts. A successful import of the exception for PythonScript use would need to be:
from Products.Sessions import BrowserIdManagerErr
class SessionDataManagerInterface
Zope Session Data Manager interface.
A Zope Session Data Manager is responsible for maintaining Session Data Objects, and for servicing requests from application code related to Session Data Objects. It also communicates with a Browser Id Manager to provide information about browser ids.
getSessionDataByKey(self, key)
Returns a Session Data Object associated with key
. If there is
no Session Data Object associated with key
return None.
Permission required: Access arbitrary user session data
getSessionData(self, create=1)
Returns a Session Data Object associated with the current browser id. If there is no current browser id, and create is true, returns a new Session Data Object. If there is no current browser id and create is false, returns None.
Permission required: Access session data
getBrowserIdManager(self)
Returns the nearest acquirable browser id manager.
Raises SessionDataManagerErr if no browser id manager can be found.
Permission required: Access session data
hasSessionData(self)
Returns true if a Session Data Object associated with the current browser id is found in the Session Data Container. Does not create a Session Data Object if one does not exist.
Permission required: Access session data
module TransienceInterfaces
class TransientObject
A transient object is a temporary object contained in a transient object container.
Most of the time you'll simply treat a transient object as a dictionary. You can use Python sub-item notation:
SESSION['foo']=1 foo=SESSION['foo'] del SESSION['foo']
When using a transient object from Python-based Scripts or DTML
you can use the get
, set
, and delete
methods instead.
Methods of transient objects are not protected by security assertions.
Anonymous User - Aug. 13, 2002 7:15 am: Please explain.
It's necessary to reassign mutuable sub-items when you change them. For example:
l=SESSION['myList'] l.append('spam') SESSION['myList']=l
This is necessary in order to save your changes. Note that this caveat is true even for mutable subitems which inherit from the Persistence.Persistent class.
delete(self, k)
- Permission
- Always available
setLastAccessed(self)
Cause the last accessed time to be set to now.
- Permission
- Always available
getCreated(self)
Return the time the transient object was created in integer seconds-since-the-epoch form.
- Permission
- Always available
values(self)
Return sequence of value elements.
- Permission
- Always available
has_key(self, k)
Return true if item referenced by key k exists.
- Permission
- Always available
getLastAccessed(self)
Return the time the transient object was last accessed in integer seconds-since-the-epoch form.
- Permission
- Always available
getId(self)
Returns a meaningful unique id for the object.
- Permission
- Always available
update(self, d)
Merge dictionary d into ourselves.
- Permission
- Always available
clear(self)
- Permission
- Always available
items(self)
Return sequence of (key, value) elements.
- Permission
- Always available
keys(self)
Return sequence of key elements.
- Permission
- Always available
get(self, k, default=marker)
Return value associated with key k. If k does not exist and default is not marker, return default, else raise KeyError.
- Permission
- Always available
set(self, k, v)
Call __setitem__ with key k, value v.
- Permission
- Always available
getContainerKey(self)
Returns the key under which the object is "filed" in its container. getContainerKey will often return a differnt value than the value returned by getId.
- Permission
- Always available
invalidate(self)
Invalidate (expire) the transient object.
Causes the transient object container's "before destruct" method related to this object to be called as a side effect.
- Permission
- Always available
class MaxTransientObjectsExceeded
An exception importable from the Products.Transience.Transience module
which is raised when an attempt is made to add an item to a
TransientObjectContainer that is full
.
This exception may be caught in PythonScripts through a normal import. A successful import of the exception can be achieved via:
from Products.Transience import MaxTransientObjectsExceeded
class TransientObjectContainer
TransientObjectContainers hold transient objects, most often, session data.
You will rarely have to script a transient object
container. You'll almost always deal with a TransientObject
itself which you'll usually get as REQUEST.SESSION
.
Anonymous User - Dec. 31, 2003 11:27 am: but help! sometimes you might want to script one. How should you create a transient object container from within a script?
new(self, k)
Creates a new subobject of the type supported by this container with key "k" and returns it.
If an object already exists in the container with key "k", a KeyError is raised.
"k" must be a string, else a TypeError is raised.
If the container is full
, a MaxTransientObjectsExceeded will
be raised.
- Permission
Create Transient Objects
setDelNotificationTarget(self, f)
Cause the before destruction
function to be f
.
If f
is not callable and is a string, treat it as a Zope path to
a callable function.
before destruction
functions need accept a single argument: item
,
which is the item being destroyed.
- Permission
Manage Transient Object Container
getTimeoutMinutes(self)
Return the number of minutes allowed for subobject inactivity before expiration.
- Permission
View management screens
has_key(self, k)
Return true if container has value associated with key k, else return false.
- Permission
Access Transient Objects
setAddNotificationTarget(self, f)
Cause the after add
function to be f
.
If f
is not callable and is a string, treat it as a Zope path to
a callable function.
after add
functions need accept a single argument: item
, which
is the item being added to the container.
- Permission
Manage Transient Object Container
getId(self)
Returns a meaningful unique id for the object.
- Permission
- Always available
setTimeoutMinutes(self, timeout_mins)
Set the number of minutes of inactivity allowable for subobjects before they expire.
- Permission
Manage Transient Object Container
new_or_existing(self, k)
If an object already exists in the container with key "k", it is returned.
Otherwiser, create a new subobject of the type supported by this container with key "k" and return it.
"k" must be a string, else a TypeError is raised.
If the container is full
, a MaxTransientObjectsExceeded exception
be raised.
- Permission
Create Transient Objects
get(self, k, default=None)
Return value associated with key k. If value associated with k does not exist, return default.
- Permission
Access Transient Objects
getAddNotificationTarget(self)
Returns the current after add
function, or None.
- Permission
View management screens
getDelNotificationTarget(self)
Returns the current before destruction
function, or None.
- Permission
View management screens
module UserFolder
class UserFolder
User Folder objects are containers for user objects. Programmers can work with collections of user objects using the API shared by User Folder implementations.
userFolderEditUser(name, password, roles, domains, **kw)
API method for changing user object attributes. Note that not all user folder implementations support changing of user object attributes. Implementations that do not support changing of user object attributes will raise an error for this method.
- Permission
- Manage users
userFolderDelUsers(names)
API method for deleting one or more user objects. Note that not all user folder implementations support deletion of user objects. Implementations that do not support deletion of user objects will raise an error for this method.
- Permission
- Manage users
userFolderAddUser(name, password, roles, domains, **kw)
API method for creating a new user object. Note that not all user folder implementations support dynamic creation of user objects. Implementations that do not support dynamic creation of user objects will raise an error for this method.
Anonymous User - June 4, 2002 2:09 pm: Please document the argument types; for example, roles must be a list (e.g., '[Manager]') and not a string. Zope will accept 'Manager' and create a user, but it's an invalid entry--when you click on it, Zope gives an error. Also, please explain the **kw (keywords) argment.
Anonymous User - May 27, 2004 1:04 am: I have scoured the net looking for the proper use of userFolderAddUser(). How are Zope users supposed to know that the roles and domains arguments are supposed to be a tuple or list? I figured it out by trial and error. I even looked at the source code, but still had trouble finding out such basic usage info. The pydoc is no better (since its based in source comments).
- Permission
- Manage users
getUsers()
Returns a sequence of all user objects which reside in the user folder.
- Permission
- Manage users
getUserNames()
Returns a sequence of names of the users which reside in the user folder.
- Permission
- Manage users
getUser(name)
Returns the user object specified by name. If there is no
user named name
in the user folder, return None.
- Permission
- Manage users
module Vocabulary
class Vocabulary
A Vocabulary manages words and language rules for text indexing. Text indexing is done by the ZCatalog and other third party Products.
words()
insert(word)
Insert a word in the Vocabulary.
query(pattern)
Query Vocabulary for words matching pattern.
ObjectManager Constructor
manage_addVocabulary(id, title, globbing=None, REQUEST=None)
Add a Vocabulary object to an ObjectManager.
module ZCatalog
class ZCatalog
A ZCatalog contains arbitrary index like references to Zope
objects. ZCatalog's can index either Field
values of object,
Text
values, or KeyWord
values:
ZCatalogs have three types of indexes:
- Text
- Text indexes index textual content. The index can be used to search for objects containing certain words.
- Field
- Field indexes index atomic values. The index can be used to search for objects that have certain properties.
- Keyword
- Keyword indexes index sequences of values. The index can be used to search for objects that match one or more of the search terms.
The ZCatalog can maintain a table of extra data about cataloged objects. This information can be used on search result pages to show information about a search result.
The meta-data table schema is used to build the schema for ZCatalog Result objects. The objects have the same attributes as the column of the meta-data table.
ZCatalog does not store references to the objects themselves, but rather to a unique identifier that defines how to get to the object. In Zope, this unique identifier is the object's relative path to the ZCatalog (since two Zope objects cannot have the same URL, this is an excellent unique qualifier in Zope).
schema()
Returns a sequence of names that correspond to columns in the meta-data table.
__call__(REQUEST=None, **kw)
Search the catalog, the same way as searchResults
.
uncatalog_object(uid)
Uncatalogs the object with the unique identifier uid
.
getobject(rid, REQUEST=None)
Return a cataloged object given a data_record_id_
Anonymous User - June 2, 2004 8:56 pm: What about getObject()?
indexes()
Returns a sequence of names that correspond to indexes.
getpath(rid)
Return the path to a cataloged object given a
data_record_id_
index_objects()
Returns a sequence of actual index objects.
searchResults(REQUEST=None, **kw)
Search the catalog. Search terms can be passed in the REQUEST or as keyword arguments.
Search queries consist of a mapping of index names to search
parameters. You can either pass a mapping to searchResults as
the variable REQUEST
or you can use index names and search
parameters as keyword arguments to the method, in other words:
searchResults(title='Elvis Exposed', author='The Great Elvonso')
searchResults({'title': 'Elvis Exposed', 'author': 'The Great Elvonso'})
In these examples, title
and author
are indexes. This
query will return any objects that have the title Elvis
Exposed AND also are authored by The Great Elvonso. Terms
that are passed as keys and values in a searchResults() call
are implicitly ANDed together. To OR two search results, call
searchResults() twice and add concatenate the results like this:
results = ( searchResults(title='Elvis Exposed') + searchResults(author='The Great Elvonso') )
This will return all objects that have the specified title OR the specified author.
There are some special index names you can pass to change the behavior of the search query:
- sort_on
- This parameters specifies which index to sort the results on.
- sort_order
- You can specify
reverse
ordescending
. Default behavior is to sort ascending.
There are some rules to consider when querying this method:
- an empty query mapping (or a bogus REQUEST) returns all items in the catalog.
- results from a query involving only field/keyword
indexes, e.g. {'id':'foo'} and no
sort_on
will be returned unsorted. - results from a complex query involving a field/keyword
index and a text index,
e.g. {'id':
foo
,'PrincipiaSearchSource':'bar'} and nosort_on
will be returned unsorted. - results from a simple text index query
e.g.{'PrincipiaSearchSource':'foo'} will be returned
sorted in descending order by
score
. A text index cannot beused as asort_on
parameter, and attempting to do so will raise an error.
Depending on the type of index you are querying, you may be able to provide more advanced search parameters that can specify range searches or wildcards. These features are documented in The Zope Book.
uniqueValuesFor(name)
returns the unique values for a given FieldIndex named name
.
catalog_object(obj, uid)
Catalogs the object obj
with the unique identifier uid
.
ObjectManager Constructor
manage_addZCatalog(id, title, vocab_id=None)
vocab_id
is the name of a Vocabulary object this catalog should
use. A value of None will cause the Catalog to create its own
private vocabulary.
module ZSQLMethod
class ZSQLMethod
ZSQLMethods abstract SQL code in Zope.
SQL Methods behave like methods of the folders they are accessed in. In particular, they can be used from other methods, like Documents, ExternalMethods, and even other SQL Methods.
Database methods support the Searchable Object Interface. Search interface wizards can be used to build user interfaces to them. They can be used in joins and unions. They provide meta-data about their input parameters and result data.
For more information, see the searchable-object interface specification.
Database methods support URL traversal to access and invoke
methods on individual record objects. For example, suppose you
had an employees
database method that took a single argument
employee_id
. Suppose that employees had a service_record
method (defined in a record class or acquired from a
folder). The service_record
method could be accessed with a
URL like:
employees/employee_id/1234/service_record
Anonymous User - Apr. 12, 2005 1:33 am: fdhjgk
module ZTUtils
ZTUtils: Page Template Utilities
The classes in this module are available from Page Templates.
class Batch
Batch - a section of a large sequence.
You can use batches to break up large sequences (such as search results) over several pages.
Batches provide Page Templates with similar functions as those
built-in to <dtml-in>
.
You can access elements of a batch just as you access elements of a list. For example:
>>> b=Batch(range(100), 10) >>> b[5] 4 >>> b[10] IndexError: list index out of range
Batches have these public attributes:
- start
- The first element number (counting from 1).
- first
- The first element index (counting from 0). Note that this is that same as start - 1.
- end
- The last element number (counting from 1).
- orphan
- The desired minimum batch size. This controls how sequences are split into batches. If a batch smaller than the orphan size would occur, then no split is performed, and a batch larger than the batch size results.
- overlap
- The number of elements that overlap between batches.
- length
- The actual length of the batch. Note that this can be different than size due to orphan settings.
- size
- The desired size. Note that this can be different than the actual length of the batch due to orphan settings.
- previous
- The previous batch or None if this is the first batch.
- next
- The next batch or None if this is the last batch.
__init__(self, sequence, size, start=0, end=0, orphan=0, overlap=0)
Creates a new batch given a sequence and a desired batch size.
- sequence
- The full sequence.
- size
- The desired batch size.
- start
- The index of the start of the batch (counting from 0).
- end
- The index of the end of the batch (counting from 0).
- orphan
- The desired minimum batch size. This controls how sequences are split into batches. If a batch smaller than the orphan size would occur, then no split is performed, and a batch larger than the batch size results.
- overlap
- The number of elements that overlap between batches.
module math
math: Python math
module
The math
module provides trigonometric and other math
functions. It is a standard Python module.
Since Zope 2.4 requires Python 2.1, make sure to consult the Python 2.1 documentation.
See Also
"Python math
module":http://docs.python.org/lib/module-math.html
documentation at Python.org
module random
random: Python random
module
The random
module provides pseudo-random number functions. With
it, you can generate random numbers and select random elements from
sequences. This module is a standard Python module.
Since Zope 2.4 requires Python 2.1, make sure to consult the Python 2.1 documentation.
See Also
"Python random
module":http://docs.python.org/lib/module-random.html
documentation at Python.org
module sequence
sequence: Sequence sorting module
This module provides a sort
function for use with DTML, Page
Templates, and Python-based Scripts.
Anonymous User - Dec. 17, 2003 4:23 am: Missing documentation for Namespace and mapping: def sort(sequence, sort=(), _=None, mapping=0) mapping=1 is important if sorting sequences of dictionaries. if _ is defined, sort-functions are looked up in this namespace
def sort(seq, sort)
seq
of objects by the optional sort schema
sort
.
sort
is a sequence of tuples
(key, func, direction)
that describe the sort order.
- key
- Attribute of the object to be sorted.
- func
- Defines the compare function (optional). Allowed values:
- "cmp"
- Standard Python comparison function
- "nocase"
- Case-insensitive comparison
- "strcoll" or "locale"
- Locale-aware string comparison
- "strcoll_nocase" or "locale_nocase"
- Locale-aware case-insensitive string comparison
- other
- A specified, user-defined comparison function, should return 1, 0, -1.
- direction
- defines the sort direction for the key (optional). (allowed values: "asc", "desc")
DTML Examples
Sort child object (using the objectValues
method) by id (using
the getId
method), ignoring case:
<dtml-in expr="_.sequence.sort(objectValues(), (('getId', 'nocase'),))"> <dtml-var getId> <br> </dtml-in>
Sort child objects by title (ignoring case) and date (from newest to oldest):
<dtml-in expr="_.sequence.sort(objectValues(), (('title', 'nocase'), ('bobobase_modification_time', 'cmp', 'desc') ))"> <dtml-var title> <dtml-var bobobase_modification_time> <br> </dtml-in>
Anonymous User - Nov. 26, 2003 4:44 am: What is the python equivalent of bobobase_modification_time ?
Page Template Examples
You can use the sequence.sort
function in Python expressions
to sort objects. Here's an example that mirrors the DTML example
above:
<table tal:define="objects here/objectValues; sort_on python:(('title', 'nocase', 'asc'), ('bobobase_modification_time', 'cmp', 'desc')); sorted_objects python:sequence.sort(objects, sort_on)"> <tr tal:repeat="item sorted_objects"> <td tal:content="item/title">title</td> <td tal:content="item/bobobase_modification_time"> modification date</td> </tr> </table>
This example iterates over a sorted list of objects, drawing a table row for each object. The objects are sorted by title and modification time.
See Also
module standard
Products.PythonScripts.standard: Utility functions and classes
The functions and classes in this module are available from Python-based scripts, DTML, and Page Templates.
def structured_text(s)
Convert a string in structured-text format to HTML.
See Also
def html_quote(s)
Convert characters that have special meaning in HTML to HTML character entities.
See Also
"Python cgi
module":http://docs.python.org/lib/Functions_in_cgi_module.html
escape
function.
def url_quote_plus(s)
Like url_quote but also replace blank space characters with
+
. This is needed for building query strings in some cases.
See Also
"Python urllib
module":http://docs.python.org/lib/module-urllib.html
url_quote_plus
function.
def dollars_and_cents(number)
Show a numeric value with a dollar symbol and two decimal places.
def sql_quote(s)
Convert single quotes to pairs of single quotes. This is needed to safely include values in Standard Query Language (SQL) strings.
def whole_dollars(number)
Show a numeric value with a dollar symbol.
def url_quote(s)
Convert characters that have special meaning in URLS to HTML character entities using decimal values.
See Also
"Python urllib
module":http://docs.python.org/lib/module-urllib.html
url_quote
function.
class DTML
DTML - temporary, security-restricted DTML objects
__init__(source, **kw)
Create a DTML object with source text and keyword variables. The source text defines the DTML source content. The optinal keyword arguments define variables.
call(client=None, REQUEST={}, **kw)
To accomplish its task, DTML often needs to resolve various
names into objects. For example, when the code <dtml-var
spam> is executed, the DTML engine tries to resolve the
name spam
.
In order to resolve names, you must be pass a namespace to the DTML. This can be done several ways:
- By passing a
client
object - If the argumentclient
is passed, then names are looked up as attributes on the argument. - By passing a
REQUEST
mapping - If the argumentREQUEST
is passed, then names are looked up as items on the argument. If the object is not a mapping, an TypeError will be raised when a name lookup is attempted. - By passing keyword arguments -- names and their values can be passed as keyword arguments to the Method.
The namespace given to a DTML object is the composite of these three methods. You can pass any number of them or none at all. Names will be looked up first in the keyword argument, next in the client and finally in the mapping.
def thousands_commas(number)
Insert commas every three digits to the left of a decimal point in values containing numbers. For example, the value, "12000 widgets" becomes "12,000 widgets".
def newline_to_br(s)
Convert newlines and carriage-return and newline combinations to break tags.
module string
string: Python string
module
The string
module provides string manipulation, conversion, and
searching functions. It is a standard Python module.
Since Zope 2.4 requires Python 2.1, make sure to consult the Python 2.1 documentation.
See Also
"Python string
module":http://docs.python.org/lib/module-string.html
documentation at Python.org.