genericHttpTransaction.py :  » Web-Frameworks » Maki » maki-20030512 » spb » 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 » Maki 
Maki » maki 20030512 » spb » genericHttpTransaction.py
# Copyright (c) 2001 Samuel Brauer.  All Rights Reserved.  NO WARRANTY.
# $Revision: 1.9 $
# FIXME: document this further...

BUFFERSIZE = 1024 * 512  # for file uploads
from spb.sessionVars import *

import string
import whrandom
import time
import cPickle

error_template = """<html>
<head>
<title>%(errno)s - %(errdesc)s</title>
</head>
<body bgcolor="white">
<h1>%(errno)s Error</h1>
<p>
<h2>%(errdesc)s</h2>
<p>
%(message)s
</body>
</html>"""

class SubclassResponsibilityError(Exception):
  def __init__(self, args=None):
    self.args = args

class Transaction:
  def __init__(self, raw_transaction):
    raise SubclassResponsibilityError

  def getRawTransaction(self):
    """Returns the "raw" transaction object (class depends on backend)"""
    raise SubclassResponsibilityError

  def getBackendName(self):
    """Returns a string naming the backend webserver framework, such as "mod_python", "webware", etc"""
    raise SubclassResponsibilityError

  def getRealPath(self):
    """Returns the server-side path to the requested resource"""
    raise SubclassResponsibilityError

  def getEnvironNames(self):
    """Returns a list of environment variable names"""
    raise SubclassResponsibilityError

  def getEnvironValue(self, name, default=None):
    """Returns the value of the named environment variable"""
    raise SubclassResponsibilityError

  def getFormNames(self):
    """Returns a list of form/query variable names.  
    Note that this will include file parameters (if the 
    request was a multipart upload)."""
    raise SubclassResponsibilityError

  def getFormValue(self, name, default=None):
    """Returns the value of the named form parameter"""
    raise SubclassResponsibilityError

  def getFormValues(self, name, keepNulls=0):
    """Returns a (possibly empty) list of the values associated with the named form parameter.  If keepNulls, then null (or None) values (possibly from normalized empty strings) are included in the list."""
    raise SubclassResponsibilityError

  def getFilename(self, name):
    raise SubclassResponsibilityError

  def getFile(self, name):
    """Returns a file handle, or None"""
    raise SubclassResponsibilityError

  def getCookieNames(self):
    """Return names of cookies FROM THE REQUEST."""
    raise SubclassResponsibilityError

  def getCookieValue(self, name, default=None):
    """Return value of cookie FROM THE REQUEST."""
    raise SubclassResponsibilityError
  
  def setCookieValue(self, name, val, path=None, expires=None, domain=None, secure=0):
    """Set a cookie value.
    If specified, "expires" should be a number of seconds."""
    raise SubclassResponsibilityError
  
  def setHeader(self, name, value):
    raise SubclassResponsibilityError

  def sendHeaders(self):
    # in addition to sending the http headers, this method
    # should also call finalizeSession()
    raise SubclassResponsibilityError
  
  def sendRedirect(self, locationString):
    raise SubclassResponsibilityError
  
  def setResponseContentType(self, contentType):
    raise SubclassResponsibilityError
  
  def writeOutput(self, data):
    """Write 'data' to the response output stream"""
    raise SubclassResponsibilityError
  

  def writeResponseOutput(self, data, contentType="text/html"):
    self.setResponseContentType(contentType)
    self.sendHeaders()
    self.writeOutput(data)

  def get(self, name, default=None):
    "Short 'alias' for getFormValue()"
    return self.getFormValue(name, default)

  def hasFormValue(self, name):
    if(self.getFormValue(name)): return 1
    return 0

  def hasEnvironValue(self, name):
    if(self.getEnvironValue(name)): return 1
    return 0

  def hasCookieValue(self, name):
    if(self.getCookieValue(name)): return 1
    return 0

  def getFormIntValue(self, name, default=None, base=10):
    val = self.getFormValue(name)
    if(val == None): return default
    try:
      nval = int(val, base)
    except:
      nval = default
    return nval

  def getFormFloatValue(self, name, default=None):
    val = self.getFormValue(name)
    if(val == None): return default
    try:
      nval = float(val)
    except:
      nval = default
    return nval

  def getFormDict(self):
    d = {}
    for key in self.getFormNames():
      d[key] = self.getFormValues(key)
    return d

  def getEnvironDict(self):
    d = {}
    for key in self.getEnvironNames():
      d[key] = self.getEnvironValue(key)
    return d

  def getCookieDict(self):
    d = {}
    for key in self.getCookieNames():
      d[key] = self.getCookieValue(key)
    return d
  
  def unsetCookie(self, name, path=None, domain=None, secure=0):
    self.setCookieValue(name, "", expires=0, path=path, domain=domain, secure=secure)
  
  def delCookieValue(self, name, path=None, domain=None, secure=0):
    """DEPRECATED in favor of unsetCookie"""
    self.unsetCookie(name, path, domain, secure)

  def normalizeString(self, val):
    """Use this method to normalize values from the request"""
    if(not(val)): return None
    out = val.strip()
    if(not(out)): return None
    return out

  def saveFile(self, name, targetFilename):
    """If "name" corresponds to an uploaded file, then open a
    file on the server specified by the fully-qualified filename
    "targetFilename" and write the file.
    Return 1 if file "name" existed and was saved successfully.
    Return 0 if no file existed for "name".
    An exception may be raised if file I/O fails.
    """
    if(not self.get(name)): return 0
    upfile = self.getFile(name)
    if(upfile):
      targetfile = open(targetFilename, "w")
      try:
        while(1):
          buffer = upfile.read(BUFFERSIZE)
          if(buffer): targetfile.write(buffer)
          else: break
      finally:
        targetfile.close()
        upfile.close()
      return 1
    else:
      return 0

  def sendError(self, errno, errdesc, message="", filename=None):
    self.setHeader("Status", "%s %s" % (str(errno), errdesc))
    if(filename):
      f = open(filename)
      self.writeResponseOutput(f.read())
      f.close()
    else:
      data = {}
      data["errno"] = str(errno)
      data["errdesc"] = str(errdesc)
      data["message"] = str(message)
      self.writeResponseOutput(error_template % data)

  def getSessionValue(self, name, default=None):
    self.initSession()
    return self.session.get(name, default)

  def putSessionValue(self, name, value):
    self.initSession()
    self.session[name] = value

  def initSession(self):
    if(hasattr(self, "session")): return
    self.session = {}
    session_id = self.getCookieValue(SESSION_ID_COOKIE_NAME)
    if(session_id):
      try:
        f = open(SESSION_DIRECTORY + session_id)
        self.session = cPickle.load(f)
        f.close()
      except:
        pass
    else:
      session_id = self.generateSessionID()
      self.setCookieValue(SESSION_ID_COOKIE_NAME, session_id, path="/")
    self.session_id = session_id

  def finalizeSession(self):
    if(not hasattr(self, "session")): return
    f = open(SESSION_DIRECTORY + self.session_id, "w")
    cPickle.dump(self.session, f)
    f.close()

  def generateSessionID(self):
    pool = string.lowercase[:26] + string.digits
    s = ""
    for i in range(16):
      idx = whrandom.randint(1, len(pool)) - 1
      s += pool[idx]
    s += str(time.time())
    return s
    



www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.