Transaction.py :  » Web-Frameworks » Webware » Webware-1.0.2 » WebKit » Python Open Source

Home
Python Open Source
1.3.1.2 Python
2.Ajax
3.Aspect Oriented
4.Blog
5.Build
6.Business Application
7.Chart Report
8.Content Management Systems
9.Cryptographic
10.Database
11.Development
12.Editor
13.Email
14.ERP
15.Game 2D 3D
16.GIS
17.GUI
18.IDE
19.Installer
20.IRC
21.Issue Tracker
22.Language Interface
23.Log
24.Math
25.Media Sound Audio
26.Mobile
27.Network
28.Parser
29.PDF
30.Project Management
31.RSS
32.Search
33.Security
34.Template Engines
35.Test
36.UML
37.USB Serial
38.Web Frameworks
39.Web Server
40.Web Services
41.Web Unit
42.Wiki
43.Windows
44.XML
Python Open Source » Web Frameworks » Webware 
Webware » Webware 1.0.2 » WebKit » Transaction.py
import traceback

from Common import *


class Transaction(Object):
  """The Transaction container.

  A transaction serves as:

    * A container for all objects involved in the transaction. The
      objects include application, request, response, session and
      servlet.

    * A message dissemination point. The messages include awake(),
      respond() and sleep().

  When first created, a transaction has no session. However, it will
  create or retrieve one upon being asked for session().

  The life cycle of a transaction begins and ends with Application's
  dispatchRequest().

  """


  ## Init ##

  def __init__(self, application, request=None):
    Object.__init__(self)
    self._application = application
    self._request = request
    self._response = None
    self._session = None
    self._servlet = None
    self._error = None
    self._nested = 0

  def __repr__(self):
    names = self.__dict__.keys()
    names.sort()
    s = []
    for name in names:
      attr = getattr(self, name)
      if isinstance(attr, Object) or isinstance(attr, Exception):
        s.append('%s=%r' % (name, attr))
    s = ' '.join(s)
    return '<%s %s>' % (self.__class__.__name__, s)


  ## Access ##

  def application(self):
    return self._application

  def request(self):
    return self._request

  def response(self):
    return self._response

  def setResponse(self, response):
    self._response = response

  def hasSession(self):
    """Return true if the transaction has a session."""
    id = self._request.sessionId()
    return id and self._application.hasSession(id)

  def session(self):
    """Return the session for the transaction.

    A new transaction is created if necessary. Therefore, this method
    never returns None. Use hasSession() if you want to find out if
    a session already exists.

    """
    if not self._session:
      self._session = self._application.createSessionForTransaction(self)
      self._session.awake(self) # give the new servlet a chance to set up
    return self._session

  def setSession(self, session):
    self._session = session

  def servlet(self):
    """Return the current servlet that is processing.

    Remember that servlets can be nested.

    """
    return self._servlet

  def setServlet(self, servlet):
    self._servlet = servlet
    if servlet and self._request:
      servlet._serverSidePath = self._request.serverSidePath()

  def duration(self):
    """Return the duration, in seconds, of the transaction.

    This is basically the response end time minus the request start time.

    """
    return self._response.endTime() - self._request.time()

  def errorOccurred(self):
    """Check whether a server error occured."""
    return isinstance(self._error, Exception)

  def error(self):
    """Return Exception instance if there was any."""
    return self._error

  def setError(self, err):
    """Set Exception instance.

    Invoked by the application if an Exception is raised to the
    application level.

    """
    self._error = err


  ## Transaction stages ##

  def awake(self):
    """Send awake() to the session (if there is one) and the servlet.

    Currently, the request and response do not partake in the
    awake()-respond()-sleep() cycle. This could definitely be added
    in the future if any use was demonstrated for it.

    """
    if not self._nested and self._session:
      self._session.awake(self)
    self._servlet.awake(self)
    self._nested += 1

  def respond(self):
    if self._session:
      self._session.respond(self)
    self._servlet.respond(self)

  def sleep(self):
    """Send sleep() to the session and the servlet.

    Note that sleep() is sent in reverse order as awake()
    (which is typical for shutdown/cleanup methods).

    """
    self._nested -= 1
    self._servlet.sleep(self)
    if not self._nested and self._session:
      self._session.sleep(self)
      self._application.sessions().storeSession(self._session)


  ## Debugging ##

  def dump(self, file=None):
    """Dump debugging info to stdout."""
    if file is None:
      file = sys.stdout
    wr = file.write
    wr('>> Transaction: %s\n' % self)
    for attr in dir(self):
      wr('%s: %s\n' % (attr, getattr(self, attr)))
    wr('\n')


  ## Die ##

  def die(self):
    """End transaction.

    This method should be invoked when the entire transaction is
    finished with. Currently, this is invoked by AppServer. This method
    removes references to the different objects in the transaction,
    breaking cyclic reference chains and allowing either older versions
    of Python to collect garbage, or newer versions to collect it faster.

    """
    for name in self.__dict__.keys():
      attr = getattr(self,  name)
      if isinstance(attr, Object) and not name.startswith('_app'):
        attr.resetKeyBindings()
      delattr(self, name)


  ## Exception handling ##

  _exceptionReportAttrNames = \
    'application request response session servlet'.split()

  def writeExceptionReport(self, handler):
    handler.writeTitle(self.__class__.__name__)
    handler.writeAttrs(self, self._exceptionReportAttrNames)

    for name in self._exceptionReportAttrNames:
      obj = getattr(self, '_' + name, None)
      if obj:
        try:
          obj.writeExceptionReport(handler)
        except Exception:
          handler.writeln('<p>Uncaught exception while asking'
            ' <b>%s</b> to write report:</p>\n<pre>' % name)
          traceback.print_exc(file=handler)
          handler.writeln('</pre>')
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.