Zope Browser

4.0 · active · verified Thu Apr 16

zope.browser provides shared Zope Toolkit browser components, including base classes for browser views, browser resources, and helper utilities. It's an integral part of the Zope Toolkit, designed for building modular web applications with a strong emphasis on interfaces and component architecture. Version 4.0 is the current stable release, compatible with Python 3.9+.

Common errors

Warnings

Install

Imports

Quickstart

This example demonstrates how to define a basic `IBrowserView` and its implementation `MyBrowserView` which inherits from `zope.publisher.browser.BrowserView`. It shows how views typically access `self.context` (the object being viewed) and `self.request` (the HTTP request). The `if __name__ == '__main__':` block illustrates how a view is instantiated with dummy context and request objects for testing purposes, mimicking the behavior of the Zope publisher.

import zope.interface
import zope.schema
import zope.publisher.browser

# 1. Define an interface for the content we want to view
class IMyContent(zope.interface.Interface):
    """An interface for some content object."""
    title = zope.schema.TextLine(title="Title")

# 2. Define a simple content object that implements the interface
@zope.interface.implementer(IMyContent)
class MyContent:
    def __init__(self, title="Default Content"): # pragma: no cover
        self.title = title

# 3. Define the browser view
class MyBrowserView(zope.publisher.browser.BrowserView):
    """A simple browser view that uses context and request."""
    def __call__(self):
        # self.context is the content object
        # self.request is the HTTP request
        return f"<h1>Hello from {self.context.title}!</h1>"

    def get_message(self):
        return f"View message for {self.context.title}"

# Example of instantiating and using the view for testing/demonstration
# In a real Zope application, this would be handled by the Zope publisher.
if __name__ == "__main__":
    from zope.publisher.interfaces.http import IHTTPRequest
    from zope.interface.declarations import implementer

    @implementer(IHTTPRequest)
    class DummyRequest: # pragma: no cover
        # Minimal request object for instantiation
        pass

    content = MyContent(title="My Awesome Page")
    request = DummyRequest()
    view = MyBrowserView(context=content, request=request)

    print(view()) # Output: <h1>Hello from My Awesome Page!</h1>
    print(view.get_message()) # Output: View message for My Awesome Page

view raw JSON →