### Install Buildout Package
Source: https://github.com/zopefoundation/zope/blob/master/docs/zdgbook/GettingStarted.rst
Installs the zc.buildout package using pip. This is a prerequisite for using Buildout to manage Zope projects.
```shell
$ pip install zc.buildout
```
--------------------------------
### Run Zope Instance
Source: https://github.com/zopefoundation/zope/blob/master/docs/zdgbook/GettingStarted.rst
Starts the Zope application instance using the runwsgi script.
```shell
$ bin/runwsgi etc/zope.ini
```
--------------------------------
### Buildout Execution Command
Source: https://github.com/zopefoundation/zope/blob/master/docs/zdgbook/GettingStarted.rst
The command to run buildout, which processes the buildout.cfg file to install and configure the project dependencies and parts.
```bash
$ buildout
```
--------------------------------
### Setup Zope Virtual Environment with Buildout
Source: https://github.com/zopefoundation/zope/blob/master/docs/INSTALL.rst
Creates a virtual environment for Zope and installs buildout tools. This example assumes Zope version 5.0 and requires a `buildout.cfg` file to be created in the same directory.
```console
python3.10 -m venv zope
cd zope
# create buildout.cfg in this folder, see examples below
bin/pip install -U pip wheel zc.buildout
bin/buildout
```
--------------------------------
### Run Buildout
Source: https://github.com/zopefoundation/zope/blob/master/docs/zdgbook/GettingStarted.rst
Executes the buildout command to download dependencies and build the Zope system based on the configuration file.
```shell
$ cd poll/poll_build
$ buildout
```
--------------------------------
### Zope Application Execution Command
Source: https://github.com/zopefoundation/zope/blob/master/docs/zdgbook/GettingStarted.rst
Command to start the Zope application server using the specified configuration file.
```bash
$ bin/runwsgi etc/zope.ini
```
--------------------------------
### Create Zope WSGI Instance
Source: https://github.com/zopefoundation/zope/blob/master/docs/zdgbook/GettingStarted.rst
Creates a WSGI instance for the Zope application using the mkwsgiinstance script generated by buildout.
```shell
$ bin/mkwsgiinstance -d .
```
--------------------------------
### Buildout Configuration for Zope 4
Source: https://github.com/zopefoundation/zope/blob/master/docs/zdgbook/GettingStarted.rst
Defines the buildout configuration to install Zope 4 and its dependencies. It specifies the versioning and the parts to build, including the 'zope4' part which uses zc.recipe.egg.
```zc.buildout
[buildout]
extends = https://zopefoundation.github.io/Zope/releases/master/versions-prod.cfg
parts =
zope4
[zope4]
recipe = zc.recipe.egg
eggs =
Zope
Paste
```
--------------------------------
### Zope Release: Initial Setup and Dependency Management
Source: https://github.com/zopefoundation/zope/blob/master/docs/maintenance.rst
Installs necessary tools for the release process and updates project dependencies using buildout.
```shell
$ bin/pip install -U wheel tox twine
```
```shell
# Create releases for packages mentioned in buildout.cfg
# Enter them into versions-prod.cfg and run buildout to update requirements-txt
$ bin/buildout
```
--------------------------------
### Zope Initialize Callback
Source: https://github.com/zopefoundation/zope/blob/master/docs/zdgbook/GettingStarted.rst
Defines the initialize function in src/poll/main/__init__.py, which is called by Zope during application startup to register components.
```python
def initialize(registrar):
pass
```
--------------------------------
### Create Project Directory Structure
Source: https://github.com/zopefoundation/zope/blob/master/docs/zdgbook/GettingStarted.rst
Sets up the initial directory structure for a Zope application project, separating build-related files from the main Python package.
```shell
$ mkdir poll
$ mkdir poll/poll_build
$ mkdir poll/poll.main
```
--------------------------------
### Install Sphinx
Source: https://github.com/zopefoundation/zope/blob/master/docs/zdgbook/README.txt
Installs the Sphinx documentation generator using easy_install. It is recommended to use a virtual environment for this installation to avoid conflicts with global Python packages.
```shell
easy_install Sphinx
```
--------------------------------
### Setup.py for Poll Application
Source: https://github.com/zopefoundation/zope/blob/master/docs/zdgbook/GettingStarted.rst
Defines the metadata for the poll.main Python package, including its name, version, packages, and dependencies. It specifies 'src' as the package directory and 'poll' as a namespace package.
```python
from setuptools import setup, find_packages
setup(
name="poll.main",
version="0.1",
packages=find_packages("src"),
package_dir={"" : "src"},
namespace_packages=["poll"],
install_requires=["setuptools",
"Zope"],
)
```
--------------------------------
### Zope Site Configuration Inclusion
Source: https://github.com/zopefoundation/zope/blob/master/docs/zdgbook/GettingStarted.rst
Includes the 'poll.main' package into the Zope site configuration. This directive makes the application's components available within the Zope instance.
```xml
```
--------------------------------
### ZPT for POLL Application Index Page
Source: https://github.com/zopefoundation/zope/blob/master/docs/zdgbook/GettingStarted.rst
Defines the basic HTML structure for the main index page of the POLL application. It displays a welcome message.
```html
Welcome to POLL!
Welcome to POLL!
```
--------------------------------
### Sample Data Setup
Source: https://github.com/zopefoundation/zope/blob/master/src/Products/Five/viewlet/README.txt
Demonstrates creating a custom container and populating it with sample files ('mypage.html', 'data.xml', 'test.txt'). This setup is used to test the view and viewlet functionality.
```python
container = Container()
obj_id = self.folder._setObject('container', container)
container = self.folder[obj_id]
container['mypage.html'] = File('Hello World!')
container['data.xml'] = File('Hello World!')
container['test.txt'] = File('Hello World!')
```
--------------------------------
### Package Initialization
Source: https://github.com/zopefoundation/zope/blob/master/docs/zdgbook/GettingStarted.rst
Registers the PollMain class and its constructors with the Zope registrar. This code is typically placed in the package's __init__.py file.
```python
from poll.main.app import PollMain, manage_addPollMain, addPollMain
def initialize(registrar):
registrar.registerClass(
PollMain,
constructors=(manage_addPollMain, addPollMain)
)
```
--------------------------------
### Build Zope Documentation Locally
Source: https://github.com/zopefoundation/zope/blob/master/docs/INSTALL.rst
Steps to build Zope's documentation locally. This involves downloading the source, setting up a virtual environment, installing dependencies including documentation extras, and running the documentation build process.
```console
$ wget https://pypi.org/packages/source/Z/Zope/Zope-5.0.tar.gz
$ tar xfz Zope-5.0.tar.gz
$ cd Zope-5.0
$ python3.10 -m venv .
$ bin/pip install -U pip wheel
$ bin/pip install Zope[docs] -c ./constraints.txt
$ cd docs
$ make html
```
--------------------------------
### Buildout Configuration for Local Development
Source: https://github.com/zopefoundation/zope/blob/master/docs/zdgbook/GettingStarted.rst
Configures buildout to recognize the local 'poll.main' package for development and includes it in the Zope 4 eggs. This ensures buildout uses the local version instead of fetching from PyPI.
```ini
[buildout]
develop = ../poll.main
extends = https://zopefoundation.github.io/Zope/releases/master/versions-prod.cfg
parts =
zope4
[zope4]
recipe = zc.recipe.egg
eggs =
Zope
Paste
poll.main
```
--------------------------------
### Buildout Configuration with plone.recipe.zope2instance
Source: https://github.com/zopefoundation/zope/blob/master/docs/INSTALL.rst
Configures Zope using `plone.recipe.zope2instance` for automated instance setup, including user credentials and HTTP address. It also shows how to integrate WSGI servers like `gunicorn`.
```ini
[buildout]
extends =
https://zopefoundation.github.io/Zope/releases/5.0/versions-prod.cfg
parts =
zopeinstance
[zopeinstance]
recipe = plone.recipe.zope2instance
eggs =
Zope
Paste
user = admin:adminpassword
http-address = 8080
zodb-temporary-storage = off
# Example with gunicorn integration:
# recipe = plone.recipe.zope2instance
# eggs =
# gunicorn
# user = admin:adminpassword
# http-address = 8080
# zodb-temporary-storage = off
# wsgi = /path/to/zope.ini
```
--------------------------------
### Get mkwsgiinstance Help
Source: https://github.com/zopefoundation/zope/blob/master/docs/operation.rst
Displays all available command-line options for the `mkwsgiinstance` script. This is useful for understanding advanced configuration or troubleshooting instance creation.
```bash
$ bin/mkwsgiinstance --help
```
--------------------------------
### Declare Namespace Package
Source: https://github.com/zopefoundation/zope/blob/master/docs/zdgbook/GettingStarted.rst
Adds code to src/poll/__init__.py to declare 'poll' as a namespace package, allowing multiple packages to contribute to the 'poll' namespace.
```python
__import__('pkg_resources').declare_namespace(__name__)
```
--------------------------------
### ZCML Configuration for Poll Package
Source: https://github.com/zopefoundation/zope/blob/master/docs/zdgbook/GettingStarted.rst
Registers the 'poll' package within Zope using Zope Configuration Markup Language (ZCML). It specifies the package and the initialize function.
```zc.ml
```
--------------------------------
### Dynamic Template Rendering Example
Source: https://github.com/zopefoundation/zope/blob/master/src/Products/Five/browser/tests/provider.txt
Simulates an HTTP GET request to a page that uses a dynamically provided template, showing the rendered output with data from the Python adapter.
```APIDOC
print(http(r'''
GET /test_folder_1_/content_obj/template_based.html HTTP/1.1
'''))
HTTP/1.1 200 OK
...
A simple template: A string for you
```
--------------------------------
### Minimal buildout.cfg for Zope Scripts
Source: https://github.com/zopefoundation/zope/blob/master/docs/INSTALL.rst
A basic buildout configuration file (`buildout.cfg`) that sets up the necessary components to create the built-in `mkwsgiinstance` script for Zope.
```ini
[buildout]
extends =
https://zopefoundation.github.io/Zope/releases/5.0/versions-prod.cfg
parts =
zopescripts
[zopescripts]
recipe = zc.recipe.egg
interpreter = zopepy
eggs =
Zope
Paste
```
--------------------------------
### PollMain Class and Add Function
Source: https://github.com/zopefoundation/zope/blob/master/docs/zdgbook/GettingStarted.rst
Defines the core PollMain class inheriting from OFS.Folder and provides a function to add instances of this class to a Zope context. It also declares a PageTemplateFile for the management form.
```python
from OFS.Folder import Folder
from Products.PageTemplates.PageTemplateFile import PageTemplateFile
class PollMain(Folder):
meta_type = "POLL"
manage_addPollMain = PageTemplateFile("manage_addPollMain_form", globals())
def addPollMain(context, id):
"" " ""
context._setObject(id, PollMain(id))
return "POLL Installed: %s" % id
```
--------------------------------
### Zope Setup and Component Hooks
Source: https://github.com/zopefoundation/zope/blob/master/src/Products/Five/component/makesite.txt
Initializes testing modules and sets up Zope component hooks for functional testing. Requires zope.testing and zope.component.
```python
from zope.testing.module import setUp, tearDown
setUp(test, name='Products.Five.component.makesite')
import Products.Five
from Zope2.App.zcml import load_config
load_config('configure.zcml', package=Products.Five)
from zope.component.hooks import setHooks
setHooks()
```
--------------------------------
### Zope Test Fixture Setup
Source: https://github.com/zopefoundation/zope/blob/master/docs/zdgbook/TestingAndDebugging.rst
Illustrates creating a Zope test fixture to set up a Zope environment for testing. It covers adding Zope's library to the Python path, importing Zope modules, obtaining an application object, and managing transactions with `setUp` and `tearDown` methods.
```python
import os, os.path, sys, string
try:
import unittest
except ImportError:
fix_path()
import unittest
class MyTest(unittest.TestCase):
def setUp(self):
# Get the Zope application object and store it in an
# instance variable for use by test methods
import Zope
self.app=Zope.app()
def tearDown(self):
# Abort the transaction and shut down the Zope database
# connection.
get_transaction().abort()
self.app._p_jar.close()
# At this point your test methods can perform tests using
# self.app which refers to the Zope application object.
...
def fix_path():
# Add Zope's lib/python directory to the Python path
file=os.path.join(os.getcwd(), sys.argv[0])
dir=os.path.join('lib', 'python')
i=string.find(file, dir)
sys.path.insert(0, file[:i+len(dir)])
def test_suite():
return unittest.makeSuite(MyTest, 'my test')
def main():
unittest.TextTestRunner().run(test_suite())
if __name__=="__main__":
fix_path()
main()
```
--------------------------------
### Install Zope with Full Requirements
Source: https://github.com/zopefoundation/zope/blob/master/docs/INSTALL.rst
Installs Zope using a comprehensive requirements file. This method might install more packages than strictly necessary for the core functionality.
```console
$ bin/pip install \
-r https://zopefoundation.github.io/Zope/releases/5.0/requirements-full.txt
```
--------------------------------
### Manage Zope Service with systemctl
Source: https://github.com/zopefoundation/zope/blob/master/docs/operation.rst
Demonstrates common systemctl commands to start, restart, check the status, and stop a Zope service managed by systemd.
```console
[root@server]# systemctl start zopeinstance
[root@server]# systemctl restart zopeinstance
[root@server]# systemctl status zopeinstance
[root@server]# systemctl stop zopeinstance
```
--------------------------------
### ZODB Initialization and Basic Usage Example
Source: https://github.com/zopefoundation/zope/blob/master/docs/zdgbook/ZODBPersistentComponents.rst
Demonstrates how to initialize ZODB using FileStorage, open a database connection, access the root object, store a Python list, and commit the transaction to make changes persistent. This example is useful for understanding ZODB's core operations outside of the Zope framework.
```python
from ZODB import FileStorage, DB
# Create a FileStorage backend
storage = FileStorage.FileStorage('mydatabase.fs')
# Create a database instance using the storage
db = DB( storage )
# Open a connection to the database
connection = db.open()
# Get the root object, which acts as a dictionary for persistent objects
root = connection.root()
# Store a Python list as a persistent object
root['employees'] = ['Bob', 'Mary', 'Jo']
# Commit the current transaction to save changes
# Note: get_transaction() is typically available in a Zope environment or via transaction management libraries.
# For standalone scripts, explicit transaction management might be needed.
# get_transaction().commit()
```
--------------------------------
### Run Zope Instance in Foreground
Source: https://github.com/zopefoundation/zope/blob/master/docs/operation.rst
Demonstrates how to start a Zope instance in the foreground using the zopeinstance fg command, which keeps the process attached to the console.
```console
$ bin/zopeinstance fg
...
Serving on http://127.0.0.1:8080
```
--------------------------------
### Manage Zope Instance Daemon with zopeinstance
Source: https://github.com/zopefoundation/zope/blob/master/docs/operation.rst
Shows how to start, check status, and stop a Zope instance running as a daemon using the zopeinstance script provided by plone.recipe.zope2instance.
```console
$ bin/zopeinstance start
...
daemon process started, pid=60116
$ bin/zopeinstance status
program running; pid=60116
$ bin/zopeinstance stop
...
daemon process stopped
```
--------------------------------
### Install Sphinx Documentation Generator
Source: https://github.com/zopefoundation/zope/blob/master/docs/zopebook/README.txt
Installs the Sphinx documentation generator using the easy_install package manager. It is recommended to use a virtual environment to manage Python packages.
```shell
easy_install Sphinx
```
--------------------------------
### Example: Checking Interface Implementation
Source: https://github.com/zopefoundation/zope/blob/master/docs/zdgbook/ComponentsAndInterfaces.rst
Illustrates how to use Zope's interface checking methods.
```python
>>> # Check if a class implements an interface
>>> IHello.implementedBy(HelloComponent)
True
>>> # Check if an instance provides an interface
>>> IHello.providedBy(my_hello_instance)
True
```
--------------------------------
### Install Zope with pip
Source: https://github.com/zopefoundation/zope/blob/master/docs/INSTALL.rst
Installs Zope and its dependencies using pip within a virtual environment. This example assumes Zope version 5.0 and installs the WSGI extras.
```console
python3.10 -m venv zope
cd zope
bin/pip install -U pip wheel
bin/pip install Zope[wsgi]
```
--------------------------------
### Testing HTTP GET with URL Parameters
Source: https://github.com/zopefoundation/zope/blob/master/src/Testing/ZopeTestCase/zopedoctest/FunctionalDocTest.txt
Illustrates testing HTTP GET requests that include URL-encoded parameters. This example verifies that parameters containing special characters, like '?', are correctly handled and passed to the server.
```python
response = http(r"""
GET /test_folder_1_?foo=bla%3Fbaz HTTP/1.1
""")
response.status
>>> 200
response.headers == {
'content-length': '5', 'content-type': 'text/plain; utf-8'}
>>> True
response.getBody() == b'index'
>>> True
```
--------------------------------
### Create Zope Instance with mkwsgiinstance
Source: https://github.com/zopefoundation/zope/blob/master/docs/operation.rst
Uses the `mkwsgiinstance` script to create a Zope instance home directory. The `-d` flag specifies the target directory. This process prompts for administrator credentials.
```bash
$ bin/mkwsgiinstance -d .
```
--------------------------------
### Browser Initialization and Login
Source: https://github.com/zopefoundation/zope/blob/master/src/Products/Five/component/makesite.txt
Sets up a test browser instance and logs in with manager credentials. Requires Testing.testbrowser.
```python
from Testing.testbrowser import Browser
browser = Browser()
browser.login('manager', 'r00t')
```
--------------------------------
### Zope Documentation: Building Locally
Source: https://github.com/zopefoundation/zope/blob/master/docs/maintenance.rst
Builds the Sphinx documentation locally after bootstrapping and running buildout.
```shell
# Build the documentation HTML output
$ bin/tox -edocs
```
--------------------------------
### PollMain Class with Index Page Attribute
Source: https://github.com/zopefoundation/zope/blob/master/docs/zdgbook/GettingStarted.rst
Adds an 'index_html' attribute to the PollMain class, associating it with the 'index_html.zpt' PageTemplateFile. This makes the ZPT accessible as the default view for the POLL object.
```python
class PollMain(Folder):
meta_type = "POLL"
index_html = PageTemplateFile("index_html", globals())
```
--------------------------------
### Debug Zope with zconsole
Source: https://github.com/zopefoundation/zope/blob/master/docs/operation.rst
Shows how to connect to the Zope database using the zconsole script for debugging and inspection. Includes examples of accessing application objects and performing transaction operations like adding users.
```console
$ bin/zconsole debug etc/zope.conf
>>> app
>>> app.acl_users
>>> import transaction
>>> transaction.begin()
>>> app.acl_users._doAddUser('foo', 'bar', ['Manager'], [])
>>> transaction.commit()
```
--------------------------------
### ZPT Form for Adding POLL
Source: https://github.com/zopefoundation/zope/blob/master/docs/zdgbook/GettingStarted.rst
This ZPT (Zope Page Template) defines the HTML structure for the management form used to add a new POLL object. It includes input fields for 'id' and 'title' and a submit button.
```html
Header
Form Title
Footer
```
--------------------------------
### Install Python Development Package (Ubuntu)
Source: https://github.com/zopefoundation/zope/blob/master/docs/INSTALL.rst
Installs the necessary Python development package on Ubuntu systems, which is required for building Zope extensions from source.
```console
$ sudo apt-get install python3-dev
```
--------------------------------
### Add Zope Users
Source: https://github.com/zopefoundation/zope/blob/master/docs/operation.rst
Explains how to add new users to a Zope instance using the addzopeuser command. It covers basic usage and specifying a custom configuration file path.
```console
$ bin/addzopeuser user password
$ bin/addzopeuser --configuration /path/to/etc/zope.conf user password
```
--------------------------------
### Object Clone Operation (Second Example)
Source: https://github.com/zopefoundation/zope/blob/master/src/OFS/tests/event.txt
Provides another example of cloning an object, demonstrating the sequence of events and method calls, similar to the first cloning example.
```python
>>> res = folder.manage_clone(folder.blueberry, 'strawberry')
ObjectCopiedEvent strawberry
ObjectWillBeAddedEvent strawberry
ObjectAddedEvent strawberry
old manage_afterAdd strawberry strawberry folder
ContainerModifiedEvent folder
ObjectClonedEvent strawberry
old manage_afterClone strawberry strawberry
>>> res.getId()
'strawberry'
```
--------------------------------
### METAL: define-macro Example
Source: https://github.com/zopefoundation/zope/blob/master/docs/zopebook/AppendixC.rst
An example demonstrating the definition of a simple macro named 'copyright'. This macro contains static HTML content.
```HTML
Copyright 2009, Foobar Inc.
```
--------------------------------
### METAL: define-slot Example
Source: https://github.com/zopefoundation/zope/blob/master/docs/zopebook/AppendixC.rst
An example showing a macro definition that includes a slot named 'name'. This slot provides a default value ('World') that can be overridden.
```HTML
Hello World
```
--------------------------------
### Zope Acquisition Introductory Example
Source: https://github.com/zopefoundation/zope/blob/master/docs/zdgbook/Acquisition.rst
Demonstrates the core concept of Zope acquisition using ExtensionClass and Acquisition mix-in classes. It shows how an object can acquire attributes from its parent or environment when accessed through a containment hierarchy.
```python
import ExtensionClass, Acquisition
class C(ExtensionClass.Base):
color = 'red'
class A(Acquisition.Implicit):
def report(self):
print self.color
a = A()
c = C()
c.a = A()
c.a.report() # prints 'red'
d = C()
d.color = 'green'
d.a = a
d.a.report() # prints 'green'
a.report() # raises an attribute error
```
--------------------------------
### Configure Zope Instance Daemon with systemd (plone.recipe.zope2instance)
Source: https://github.com/zopefoundation/zope/blob/master/docs/operation.rst
Provides a systemd service configuration example for Zope instances managed by plone.recipe.zope2instance. It assumes a specific buildout location and user, and uses the instance's start/stop script.
```cfg
[Unit]
Description=Zope client zopeinstance
After=network.target
[Service]
Type=forking
User=zope
ExecStart=/opt/zopeinstance/bin/zopeinstance start
```
--------------------------------
### METAL: fill-slot Example
Source: https://github.com/zopefoundation/zope/blob/master/docs/zopebook/AppendixC.rst
An example demonstrating how to use a macro ('hello') and customize its 'name' slot with new content ('Kevin Bacon'). This requires a 'metal:use-macro' statement.
```HTML
Hello Kevin Bacon
```
--------------------------------
### Zope Acquisition Filtering Example
Source: https://github.com/zopefoundation/zope/blob/master/docs/zdgbook/Acquisition.rst
Demonstrates how to use a filter function with `aq_acquire` to control attribute acquisition. The example shows a custom filter that only returns an object if it has an 'isNice' attribute.
```python
from Acquisition import Explicit
class HandyForTesting:
def __init__(self, name):
self.name = name
def __str__(self):
return "%s(%s)" % (self.name, self.__class__.__name__)
__repr__ = __str__
class E(Explicit, HandyForTesting): pass
class Nice(HandyForTesting):
isNice = 1
def __str__(self):
return HandyForTesting.__str__(self) + ' and I am nice!'
__repr__ = __str__
a = E('a')
a.b = E('b')
a.b.c = E('c')
a.p = Nice('spam')
a.b.p = E('p')
def find_nice(self, ancestor, name, object, extra):
return hasattr(object,'isNice') and object.isNice
print(a.b.c.aq_acquire('p', find_nice))
```
--------------------------------
### TALES Python Expressions: Examples
Source: https://github.com/zopefoundation/zope/blob/master/docs/zopebook/AppendixC.rst
Provides practical examples of using TALES Python expressions for random choice selection, string manipulation, mathematical operations, and float formatting.
```TAL
a random number between one and five
```
```TAL
User Name
```
```TAL
12.2323
```
```TAL
13.56
```
--------------------------------
### Zope Release: Tagging and Uploading to PyPI
Source: https://github.com/zopefoundation/zope/blob/master/docs/maintenance.rst
Tags the release in Git, builds distribution packages (sdist, wheel), and uploads them to PyPI using twine.
```shell
# Upload tagged release to PyPI
# Using zest.releaser:
$ bin/release
# Manual process:
$ git tag -as -m "- tagging release "
$ git push --tags
$ bin/zopepy setup.py egg_info -Db '' sdist bdist_wheel
$ bin/twine upload dist/Zope-*
```
--------------------------------
### Generated HTML for Zope Batching Example
Source: https://github.com/zopefoundation/zope/blob/master/docs/zopebook/AdvDTML.rst
The HTML output generated by the first DTML batching example. It displays a single batch of 10 items with introductory and concluding text, and a 'Next' navigation link.
```HTML
Zope
These words are displayed at the top of a batch:
- Iteration number: 0
- Iteration number: 1
- Iteration number: 2
- Iteration number: 3
- Iteration number: 4
- Iteration number: 5
- Iteration number: 6
- Iteration number: 7
- Iteration number: 8
- Iteration number: 9
These words are displayed at the bottom of a batch.
(Next 10 results)
```
--------------------------------
### Systemctl Commands for Zope Instance Management
Source: https://github.com/zopefoundation/zope/blob/master/docs/operation.rst
Standard systemctl commands to control the Zope instance service. These commands allow starting, stopping, restarting, and checking the status of the Zope service.
```console
systemctl start zopeinstance
systemctl restart zopeinstance
systemctl status zopeinstance
systemctl stop zopeinstance
```
--------------------------------
### Create a Simple Zope Browser View
Source: https://github.com/zopefoundation/zope/blob/master/src/Products/Five/doc/manual.txt
Provides an example of a basic Zope browser view class inheriting from `BrowserView`. Such views require an `__init__` method accepting context and request, and can define methods to be accessed via the browser.
```python
from zope.publisher.browser import BrowserView
class SimpleFolderView(BrowserView):
def eagle(self):
"""Test
"""
return "The eagle has landed: %s" % self.context.keys()
```
--------------------------------
### DTML Sendmail with MIME Attachment Example
Source: https://github.com/zopefoundation/zope/blob/master/docs/zopebook/AppendixA.rst
An example demonstrating how to send an email with a file attachment using DTML. It combines the 'sendmail' and 'mime' tags, specifying content type, disposition, and filename for the attachment.
```dtml
To:
Subject: Resume
Hi, please take a look at my resume.
```
--------------------------------
### Sessioning Configuration with Products.Sessions and Products.TemporaryFolder
Source: https://github.com/zopefoundation/zope/blob/master/docs/migrations/zope4/removed.rst
Guidance on enabling sessioning in Zope. This includes adding the `Products.Sessions` egg for basic infrastructure and configuring `Products.TemporaryFolder` for temporary session data storage, with a ZODB configuration example.
```APIDOC
Products.Sessions:
Description: Provides basic session infrastructure.
Usage: Add to buildout's 'eggs' attribute.
Products.TemporaryFolder:
Description: Provides temporary folder solution for session data storage (non-production).
Warning: Known to randomly lose session data, do not use in production.
Usage: Add to buildout's 'eggs' attribute.
ZODB Configuration Example:
name Temporary database (for sessions)
mount-point /temp_folder
container-class Products.TemporaryFolder.TemporaryContainer
Alternative (Minimal): Add a Folder object named 'temp_folder' at ZODB root. High risk of conflict errors.
```
--------------------------------
### Access Viewlets by Key and Get Method
Source: https://github.com/zopefoundation/zope/blob/master/src/Products/Five/viewlet/README.txt
Illustrates how to access individual viewlets managed by a ViewletManager using dictionary-like key access and the `get()` method. It also covers the expected behavior when a viewlet is not found.
```python
print(leftColumn['weather'])
print(leftColumn.get('weather'))
from zope.interface.interfaces import ComponentLookupError
try:
leftColumn['stock']
except ComponentLookupError as exc:
print('No provider with name `stock` found.' in str(exc))
else:
print('ComponentLookupError not raised.')
print(leftColumn.get('stock') is None)
```
--------------------------------
### Simple Page Template Example
Source: https://github.com/zopefoundation/zope/blob/master/docs/zopebook/ZPT.rst
Demonstrates creating a basic dynamic page using Zope's Page Template language with TAL content binding. It shows how to replace placeholder content with dynamic data from the template's title attribute.
```html
This is the Title.
```
--------------------------------
### TALES Conditional Example with Exists
Source: https://github.com/zopefoundation/zope/blob/master/docs/zopebook/AppendixC.rst
Shows a practical example of using a TALES 'exists' expression within a 'tal:condition' attribute to conditionally render an HTML element based on the presence of a request form variable.
```HTML
Please enter a number between 0 and 5
```
--------------------------------
### Setup Zope Test Fixtures and Resources
Source: https://github.com/zopefoundation/zope/blob/master/src/Products/Five/browser/tests/resource.txt
Configures the Zope test environment by loading ZCML configurations and setting up a traversable folder. It also identifies resource files (PNG, PT, PY, CSS) within a specified directory using glob patterns, preparing the context for subsequent resource tests.
```python
>>> import Products.Five.browser.tests
>>> from Zope2.App import zcml
>>> zcml.load_config("configure.zcml", Products.Five)
>>> zcml.load_config('resource.zcml', package=Products.Five.browser.tests)
>>> from Products.Five.tests.testing import manage_addFiveTraversableFolder
>>> manage_addFiveTraversableFolder(self.folder, 'testoid', 'Testoid')
>>> import os, glob
>>> _prefix = os.path.dirname(Products.Five.browser.tests.__file__)
>>> dir_resource_names = [os.path.basename(r) for r in (
... glob.glob('%s/*.png' % _prefix) +
... glob.glob('%s/*.pt' % _prefix) +
... glob.glob('%s/[a-z]*.py' % _prefix) +
... glob.glob('%s/*.css' % _prefix))]
```
--------------------------------
### DTML Variable Lookup Error Example
Source: https://github.com/zopefoundation/zope/blob/master/docs/zopebook/AdvDTML.rst
Illustrates a DTML variable lookup that fails because the variable is not found in the namespace stack. This example highlights how DTML generates an error when a requested variable is absent, emphasizing the importance of variable availability.
```DTML
```
--------------------------------
### Example Debugging Scenario: Fixing AttributeError
Source: https://github.com/zopefoundation/zope/blob/master/docs/zdgbook/TestingAndDebugging.rst
Presents a practical example of debugging a Python class method within Zope. It highlights how to identify and fix an `AttributeError` caused by an unassigned instance variable using the interactive debugger.
```python
class News(...):
...
def postnews(self, news, author="Anonymous"):
# Bug: 'author' is not assigned to an instance variable
self.news = news
def quote(self):
# This method will raise AttributeError if 'author' is not set
return '%s said, "%s"' % (self.author, self.news)
# To debug, simulate a request that calls postnews and then quote:
# >>> import ZPublisher
# >>> ZPublisher.Zope('/News/postnews?new=test_news&author=Alice', d=1)
# ... (pdb session starts)
# At the pdb prompt, you can inspect self.author and self.news.
# After fixing the postnews method (e.g., self.author = author),
# you can continue execution to test the quote method.
```
--------------------------------
### Instantiate and Render Content Provider
Source: https://github.com/zopefoundation/zope/blob/master/src/Products/Five/browser/tests/provider.txt
Demonstrates manually instantiating a content provider and calling its `render` method. This shows the basic lifecycle and output generation of a provider.
```python
box = MessageBox(None, None, None)
box.render() == 'My Message
'
```
--------------------------------
### Registering Test Pages and Loading ZCML
Source: https://github.com/zopefoundation/zope/blob/master/src/Products/Five/browser/tests/pages.txt
Sets up the testing environment by loading ZCML configurations and registering test pages. This involves importing necessary modules from Products.Five and Zope2.App.
```python
>>> import Products.Five.browser.tests
>>> from Zope2.App import zcml
>>> zcml.load_config("configure.zcml", Products.Five)
>>> zcml.load_config('pages.zcml', package=Products.Five.browser.tests)
```
--------------------------------
### Zope Doctest Examples
Source: https://github.com/zopefoundation/zope/blob/master/src/Testing/ZopeTestCase/zopedoctest/ZopeDocTest.txt
Illustrative doctest examples verifying Zope's testing infrastructure. These snippets demonstrate accessing application objects, user data, and manipulating object properties within the Zope testing environment.
```python
>>> from Testing.ZopeTestCase import folder_name, user_name
>>> from AccessControl import getSecurityManager
>>> folder_name in self.app.objectIds()
True
>>> 'acl_users' in self.folder.objectIds()
True
>>> user = self.folder.acl_users.getUserById(user_name)
>>> user is None
False
>>> getSecurityManager().getUser().getId() == user_name
True
>>> 'object' in self.folder.objectIds()
True
>>> ob = self.folder.object
>>> print(ob.title_or_id())
object
>>> ob.manage_changeProperties(title='Foo')
>>> print(ob.title_or_id())
Foo
>>> self.folder.manage_delObjects('object')
>>> 'object' in self.folder.objectIds()
False
```
--------------------------------
### Build HTML Documentation with Make
Source: https://github.com/zopefoundation/zope/blob/master/docs/zopebook/README.txt
Generates the HTML version of the documentation using the 'make' command. This process converts the source files into a browsable HTML format.
```shell
make html
```
--------------------------------
### TAL Error Handling Script Example
Source: https://github.com/zopefoundation/zope/blob/master/docs/zopebook/AppendixC.rst
An example of a Python script used with tal:on-error to handle specific exceptions. The script receives an 'error' object containing type, value, and traceback, and can return HTML content or raise further exceptions.
```Python
## Script (Python) "errHandler"
##bind namespace=_
##
error=_['error']
if error.type==ZeroDivisionError:
return "Can't divide by zero.
"
else
return """An error ocurred.
Error type: %s
Error value: %s
""" % (error.type, error.value)
```
--------------------------------
### Testing HTTP GET Requests and Responses
Source: https://github.com/zopefoundation/zope/blob/master/src/Testing/ZopeTestCase/zopedoctest/FunctionalDocTest.txt
Demonstrates how to use the `http` function within doctests to simulate GET requests to Zope resources. It shows how to check the HTTP status code, response headers, and the response body, including handling potential errors.
```python
response = http(r"""
GET /test_folder_1_/index_html HTTP/1.1
""", handle_errors=False)
response.status
>>> 200
response.headers == {
'content-length': '5', 'content-type': 'text/plain; utf-8'}
>>> True
response.getBody() == b'index'
>>> True
```
--------------------------------
### Define and Implement Adapters
Source: https://github.com/zopefoundation/zope/blob/master/src/Products/Five/doc/manual.txt
Provides examples for defining a new interface (`INewInterface`) and creating an adapter class (`MyAdapter`) that implements it. The adapter's constructor takes a `context` object, which is the object being adapted.
```Python
from zope.interface import Interface
class IMyInterface(Interface):
"""This is an interface.
"""
def someMethod():
"""This method does amazing stuff.
"""
from zope.interface import implementer
from interfaces import IMyInterface
@implementer(IMyInterface)
class MyClass(object):
def someMethod(self):
return "I am alive! Alive!"
class INewInterface(Interface):
"""The interface we adapt to.
"""
def anotherMethod():
"""This method does more stuff.
"""
from zope.interface import implementer
from interfaces import INewInterface
@implementer(INewInterface)
class MyAdapter:
def __init__(self, context):
self.context = context
def anotherMethod(self):
return "We have adapted: %s" % self.context.someMethod()
```
--------------------------------
### Bjoern WSGI Server Configuration with plone.recipe.zope2instance
Source: https://github.com/zopefoundation/zope/blob/master/docs/operation.rst
Example of configuring a Zope instance to use the Bjoern WSGI server via the plone.recipe.zope2instance buildout recipe. It includes the necessary egg for Bjoern integration and points to a Bjoern configuration file.
```ini
[zopeinstance]
recipe = plone.recipe.zope2instanceeggs =
dataflake.wsgi.bjoern
zodb-temporary-storage = off
user = admin:password
http-address = 8080
wsgi = ${buildout:directory}/etc/bjoern.ini
```