ZopeMag's mascot the ZOPE fish


Article Finder
People
Issue 6 - Revision 8  /   January 18, 2003 


 
  ZopeMag Links:
Latest Issue
About the Fish
Issue 10
Issue 09
Issue 08
Issue 07
Issue 06
Issue 05
Issue 04
Issue 03
Issue 02
Issue 01
 
 
Downloads
     
  Letter from the Editor:
   Issue 6

Interviews:
Each issue we interview important people in the Zope world.

  Alan Runyan

Articles:
Throughout the quarter we cover topics of interest to Zope developers, designers, and users.

  Intro to Archetypes

  Customized User Folders Revisited

  Plone Workflows

  Enriching Zope UIs With XML

Product Review:
Too many Products, too little time? ZopeMag keeps you up-to-date which Zope Products are worthwhile downloading.

  Formulator
  ZStyleSheets


Guides:
This quarter we bring you a new miniGuide and our first SuperGuide. These Guides give you the background knowledge you need to mastering Zope.

  miniGuide to importing a Website
  SuperGuide for Zope Newbies.
 
 
Downloads
     
  URLs / Download
Products we talk about in this issues Articles and Reviews

  Formulator
  ZSQL Catalog
     

Illustration by Lia Avant
Archetypes Cover
Archetypes:

Archetypes: (Part I)
- An Introduction
- - - - - - - - - - - -

By Sidnei da Silva | October 6, 2003

print

Abstract

In this article, you're going to learn:

  • what Archetypes is and how can it help you
  • what an Archetypes schema is and how to create one
  • how to turn an Archetypes schema into a Zope Product
  • how to make the Product you created installable.
____
 
 
Sidebar - Definitions
Schema: A schema in Archetypes is simply the abstraction of the properties akin to your object. It is built using field objects. Each field is responsible for representing one type of data, such as an integer with IntegerField, a string with StringField and so on.
Actions: in CMF are usually presented to the user in an action box. In Plone these actions are presented as green tabs just above the content area. Each action has a title, an expression that is evaluated to generate a URL (the action target), a condition expression that can be used to select which users are able to see the action, a permission and a category. Common categories include 'object', 'folder', 'user', and 'portal'.
Unique IDs are only available to Archetypes-based objects (as compared with Zope objects in general). Archetypes Unique Ids are unique to the whole site, and immutable, as opposed to object ids.
References: References to other Archetypes objects are implemented using Unique IDs
Dublin Core Metadata Initiative (DCMI) : is an open forum engaged in the development of interoperable online metadata standards which support a broad range of purposes and business models. DCMI's activities include consensus-driven working groups, global workshops, conferences, standards liaison, and educational efforts to promote widespread acceptance of metadata standards and practices.
Factory Type Information (FTI): FTI, a.k.a. Factory Type Information, is used by CMF to register factories for content types. In an FTI you can specify the portal_type name, the actions for this type and so on.
 
____
Requirements
  • an average Python version (basic modules and operations) and, of course, knowledge of Python
  • installation of Zope Products
  • have Archetypes (1.0.1+) installed and running
  • have CMFPlone (1.0.5+) installed and running.
What is Archetypes?

Archetypes (formerly known as CMFTypes) is a framework designed to facilitate the building of applications for Plone and CMF. Its main purpose is to provide a common method for building content objects, based on schema definitions. Fields can be grouped for editing, making it very simple to create wizard-like forms.

Motivation

Why does one need a special application for generating content objects? Since CMF is a very powerful framework for creating content management systems, like many other frameworks it puts a considerable load on the developer to satisfy its interfaces and implement all the things needed to make a system interface with it. Frameworks by definition are generic, which has the downside of often being too generic to be usable out-of-the-box by the average developer.

Archetypes aims to help the developer by lowering the bar just enough to make it reachable by the developer who knows what he wants but can't put in the time to learn all the requirements for creating content objects with CMF.

What does Archetypes offer you?

Archetypes is able to do all the heavy lifting needed to bootstrap a content type, allowing the developer to focus on other things such as business rules, planning, scaling and designing. It provides the following features:

  • Auto-generation of editing and presentation views
  • Registration of content types with the CMF tools
  • Easy installation of the generated content objects
  • Configurability of CMF actions
  • Basic storage transparency
  • Unique IDs
  • References
  • Basic security bootstrap

Let's start by building a simple schema step-by-step, and then look at how to turn this into a usable product.

Building a simple Product: "Article" Building the Schema

For building a simple schema you don't need anything fancy, beyond knowing what fields you want and what they will contain. First, create a directory named "MyArticle" in your Zope "Products" directory. Then, create a file named “Article.py”. This file will contain our Article class and its schema. Now, open this file in your favorite editor and enter the following:

1 from Products.Archetypes.public import *
2
3 class Article(BaseContent):
4   """ A Simple Article """
5   schema = BaseSchema + Schema(
6            StringField('body',
7            widget=TextAreaWidget(label='Body Content')
      8          ))

This is a simple example, but it already shows the power of Archetypes and how easy it is to build new content objects. Let's look at it in detail and see what's going on.

In line 1, we import all the fields, widgets and classes made publicly available by Archetypes. Note that this is considered bad style by most Python programmers (importing * from a module), but this doesn't mean it can't be done and, of course, it makes life a lot easier: it makes a lot of stuff available to our module, although we are only going to use a small amount of it.

In line 3 you see the actual class declaration. We are saying here that our Article class will inherit from BaseContent, which is a base class provided by Archetypes that knows how to handle validation and how to access fields defined in a schema; it also handles lots of other stuff such as initialization of the object and indexing. BaseContent is for normal, non-folderish objects; for folderish objects you can use the base class BaseFolder.

In line 4 we have the docstring, which you should always provide, as it's considered good style; note that some later versions of Zope will not allow your object to be published via HTTP without a docstring.

In line 5 we start the schema definition. Note that we are using a variable called BaseSchema here. BaseSchema is the schema for BaseContent, which has some common fields such as title, id and the Dublin Core fields. Then, to these fields, we add our custom schema, which is composed of a StringField named "body", for which we will use a TextAreaWidget with the label "Body Content".

There are plenty of fields and widgets available for you to use, such as BooleanField/BooleanWidget, IntegerField/IntegerWidget, SelectionWidget, MultiSelection widget and so on. You can also define your own fields and widgets to handle special cases.

At this point the schema itself is finished, but it is not useable yet. For Archetypes to actually make use of your schema, you must register it with the Archetypes machinery. To do so, add the following line as the last line of your module:

registerType(Article)

This line tells Archetypes about your class and schema. It then processes the schema to auto-generate the methods required for accessing and changing your fields, as well as for setting security permissions.

Now, what if you want to make the content of your product "Article" searchable, and make the content be required when editing, so you don't get an empty Article body? Simply change your schema definition to the following:

schema = BaseSchema + Schema(
             StringField('body',
             searchable=1,
             required=1,
             widget=TextAreaWidget(label='Body Content'),
  ))

Having "searchable" set to true makes the field be indexed in the SearchableText index. Having "required" set to true makes the field StringField ('body',...) be required. i.e. non-empty, when the edit form is submitted.

Screenshot 1: Actions in CMF are presented in the top blue bar and in a grey action box at the left.

Screenshot 2: Actions in Plone are presented as green tabs in content space, and in blue tabs on the main navigation bar.

Making the Schema into a Product

Currently your directory structure looks like this:

Products
|
\- MyArticle
   |
             \- Article.py

We are going to create some files to turn MyArticle into a real product, so that it can be recognized by Zope and installed.

The first step is to create __init__.py in your directory, which turns the directory into a Python package. __init__.py should look as follows:

1 from Products.Archetypes.public import process_types, listTypes
2 from Products.CMFCore import utils
3
4 from Products.MyArticle.config import PROJECTNAME, \
5      ADD_CONTENT_PERMISSION
6
7 def initialize(context):
8   ##Import Types here to register them
9   import Article
10
11  content_types, constructors, ftis = process_types(
12       listTypes(PROJECTNAME), PROJECTNAME)
13
14  utils.ContentInit(
15     PROJECTNAME + ' Content',
16     content_types      = content_types,
17     permission         = ADD_CONTENT_PERMISSION,
18     extra_constructors = constructors,
19     fti                = ftis,
10     ).initialize(context)

Now for some explanation:

Line 1 imports some helper functions from Archetypes to make our job easier. process_types takes a list of registered types and the package name (PROJECTNAME) and returns the content_types, constructors and FTIs in the right format for use in CMF initialization. listTypes takes the package name and returns a list of types suitable to be used with process_types.

Line 4 imports some constants from a module named config. Since this module doesn't exist yet, we will now create it.

Create a file named config.py in the same subdirectory MyArticle with the following content:

PROJECTNAME = 'MyArticle'
ADD_CONTENT_PERMISSION = 'MyArticle: Add Content'

Also, go back to Article.py and make the following changes:

  • Add the line "from Products.MyArticle.config import PROJECTNAME"
  • Change the line "registerType(Article)" to "registerType(Article, PROJECTNAME)"

That's it. Now you can start up Zope and check to see if your product was imported. This check consists of two steps:

  • Make sure you didn't get an exception on starting Zope
  • Go to Control_Panel/Products inside Zope and make sure you see MyArticle listed there.

If you got this right, you're now ready to make your product installable.

Making an installer for your product

Making an installer with Archetypes is pretty simple. You just need to create an External Method with some generic boilerplate code and you're done. First, create a subdirectory named "Extensions" in your MyArticle directory. Then create a file named "Install.py" in the Extensions subdirectory. This file should look as follows:

from Products.MyArticle.config import PROJECTNAME
from Products.Archetypes.public import listTypes
from Products.Archetypes.Extensions.utils import installTypes
from StringIO import StringIO

def install(self):
    out = StringIO()

    installTypes(self, out,
                 listTypes(PROJECTNAME),
                 PROJECTNAME)

    print >> out, "Successfully installed %s." % PROJECTNAME
    return out.getvalue()

At this point, your file structure should look like this:

Products
|
\- MyArticle
   |
   \- __init__.py
   |
   \- Article.py
   |
   \- config.py
   |
   \- Extensions
      |
      \- __init__.py
      |
      \- Install.py

(Note that __init__.py has to be added to the Extension directory to allow the import of Install.py. __init__.py here is empty: it serves to make the directory into a package.)

Now, give it a try:

  • Restart Zope
  • Make sure the product got imported just fine
  • Create a Plone Site
  • Create an External Method:
    id: install_article
    module: MyArticle.Install
    function: install
    
  • Run the External Method
  • Check that it worked by looking inside portal_types to see if it contains a type named "Article".

That's it! If you got this far with no problems you can trust yourself to investigate for examples the code of some products created with Archetypes, such as ArchPackage, which is a complex Archetypes-based package, and then go on to create your own simple products.

This product can also be taken to compare the use of Archetypes with that of CMF, to get some idea of the benefit of Archetypes. ArchPackage does the same as CMFPackage, which is used on Zope.org for managing Software Product Releases (a.k.a. "downloadable products"). CMFPackage can be downloaded over CMFPackage.

Conclusion

In this article you've learned how to create a very simple Archetypes-based product and how to make it installable and usable in Zope. You also learned something about the features Archetypes provides and the usefulness of the product.

In following articles you will learn how to improve your product by adding such features as view and/or edit form customization and the setting of security permissions for the auto-generated methods.

ZopeMag has recently published the second Archetypes article. (This article requires an active ZopeMag subscription)

More information can be found in Archteypes Documentation on Plone.org, and in the CVS of Plone-Docsproject on SourceForge, including full UML diagrams showing how the different pieces of Archetypes interact.


Sidnei da Silva:

Sidnei da Silva started to work with python just after leaving the ISP he was working for, as PHP programmer and doing Sysadmin tasks. Actually, he fell into python by accident . On the company he started, X3ng , with a few friends from University, they decided to use Zope, so he's got Zope installed and started playing with ZClasses, to drop it right away a few hours later for writing python products. He used to do python programming for food, until a good friend from Texas opened his eyes: now he does python for food and a beer .


shim
shim  ZopeMag is committed to bringing you the best in Zope Documentation. shim
shim


Home   Subscribe   FAQ   Contact   Write for us   Privacy Policy   Weekly News   PyZine   opensourcexperts.com  

Reproduction of material from any of ZopeMag's pages without prior written permission is strictly prohibited. Copyright 2003 - 2005 ZopeMag Zope/Plone hosting by Nidelven IT