Back to index

python-weblib  1.3.9
Public Member Functions | Public Attributes | Private Member Functions
pyweblib.forms.Form Class Reference

List of all members.

Public Member Functions

def __init__
def checkRequestMethod
def getContentType
def addField
def getInputValue
def hiddenInputFields
def getInputFields

Public Attributes

 field
 declaredFieldNames
 inputFieldNames
 env
 inf
 request_method
 script_name
 http_accept_charset
 http_accept_language
 accept_language
 http_accept_encoding
 accept_charset

Private Member Functions

def _parseFormUrlEncoded
def _parseMultipartFormData

Detailed Description

Class for declaring and processing a whole <form>

Definition at line 794 of file forms.py.


Constructor & Destructor Documentation

def pyweblib.forms.Form.__init__ (   self,
  inf,
  env 
)
Initialize a Form
inf                 Read from this file object if method is POST.
env                 Dictionary holding the environment vars.

Definition at line 799 of file forms.py.

00799 
00800   def __init__(self,inf,env):
00801     """
00802     Initialize a Form
00803     inf                 Read from this file object if method is POST.
00804     env                 Dictionary holding the environment vars.
00805     """
00806     # Dictionary of Field objects
00807     self.field = {}
00808     # Ordered list of input field names
00809     self.declaredFieldNames = []
00810     # List of parameters names received
00811     self.inputFieldNames = []
00812     # Save the environment vars
00813     self.env = env
00814     # input file object
00815     self.inf = inf or sys.stdin
00816     # Save request method
00817     self.request_method = env['REQUEST_METHOD']
00818     self.script_name = env['SCRIPT_NAME']
00819     # Initialize the AcceptHeaderDict objects
00820     self.http_accept_charset = helper.AcceptCharsetDict('HTTP_ACCEPT_CHARSET',env)
00821     self.http_accept_language = helper.AcceptHeaderDict('HTTP_ACCEPT_LANGUAGE',env)
00822     self.accept_language = self.http_accept_language.keys()
00823     self.http_accept_encoding = helper.AcceptHeaderDict('HTTP_ACCEPT_ENCODING',env)
00824     # Set the preferred character set
00825     self.accept_charset = self.http_accept_charset.preferred()
00826     # Determine query string and content length dependent on request method
00827     self.checkRequestMethod()
00828     return # Form.__init__()


Member Function Documentation

def pyweblib.forms.Form._parseFormUrlEncoded (   self,
  maxContentLength,
  ignoreEmptyFields,
  ignoreUndeclaredFields,
  stripValues,
  unquote 
) [private]

Definition at line 888 of file forms.py.

00888 
00889   def _parseFormUrlEncoded(self,maxContentLength,ignoreEmptyFields,ignoreUndeclaredFields,stripValues,unquote):
00890 
00891     if self.request_method=='POST':
00892       query_string = self.inf.read(int(self.env['CONTENT_LENGTH']))
00893     elif self.request_method=='GET':
00894       query_string = self.env.get('QUERY_STRING','')
00895 
00896     self.inf.close()
00897 
00898     inputlist = query_string.split('&')
00899 
00900     contentLength = 0
00901 
00902     # Loop over all name attributes declared
00903     for param in inputlist:
00904 
00905       if param:
00906 
00907         # Einzelne Parametername/-daten-Paare auseinandernehmen
00908         try:
00909           name,value = param.split('=',1)
00910         except ValueError:
00911           raise InvalidFormEncoding(param)
00912         name = unquote(name).strip()
00913 
00914         if not name in self.declaredFieldNames:
00915           if ignoreUndeclaredFields:
00916             continue
00917           else:
00918             raise UndeclaredFieldName(name)
00919 
00920         value = unquote(value)
00921         if stripValues:
00922           value = value.strip()
00923 
00924         contentLength += len(value)
00925         # Gesamtlaenge der Daten noch zulaessig?
00926         if contentLength > maxContentLength:
00927           raise ContentLengthExceeded(contentLength,maxContentLength)
00928 
00929         f = self.field[name]
00930 
00931         # input is empty string?
00932         if value or (not ignoreEmptyFields):
00933           # Input is stored in field instance
00934           f.setValue(value)
00935           # Add name of field to list of input keys
00936           if not name in self.inputFieldNames:
00937             self.inputFieldNames.append(name)
00938 
00939     return #_parseFormUrlEncoded()
00940 

Here is the caller graph for this function:

def pyweblib.forms.Form._parseMultipartFormData (   self,
  maxContentLength,
  ignoreEmptyFields,
  ignoreUndeclaredFields,
  stripValues,
  unquote 
) [private]

Definition at line 941 of file forms.py.

00941 
00942   def _parseMultipartFormData(self,maxContentLength,ignoreEmptyFields,ignoreUndeclaredFields,stripValues,unquote):
00943 
00944     import cgi
00945     ctype, pdict = cgi.parse_header(self.env['CONTENT_TYPE'])
00946     parts = cgi.parse_multipart(self.inf,pdict)
00947 
00948     contentLength = 0
00949 
00950     for name in parts.keys():
00951 
00952       if not name in self.declaredFieldNames:
00953         if ignoreUndeclaredFields:
00954           continue
00955         else:
00956           raise UndeclaredFieldName(name)
00957 
00958       for value in parts[name]:
00959 
00960 #        if stripValues:
00961 #     value = value.strip()
00962 
00963         contentLength += len(value)
00964         # Gesamtlaenge der Daten noch zulaessig?
00965         if contentLength > maxContentLength:
00966           raise ContentLengthExceeded(contentLength,maxContentLength)
00967 
00968         f = self.field[name]
00969 
00970         # input is empty string?
00971         if value or (not ignoreEmptyFields):
00972           # Input is stored in field instance
00973           f.setValue(value)
00974           # Add name of field to list of input keys
00975           if not name in self.inputFieldNames:
00976             self.inputFieldNames.append(name)
00977 
00978     return # _parseMultipartFormData()
00979 

Here is the call graph for this function:

Here is the caller graph for this function:

def pyweblib.forms.Form.addField (   self,
  f 
)
Add a input field object f to the form.

Definition at line 845 of file forms.py.

00845 
00846   def addField(self,f):
00847     """
00848     Add a input field object f to the form.
00849     """
00850     f.setCharset(self.accept_charset)
00851     self.field[f.name] = f
00852     if not f.name in self.declaredFieldNames:
00853       self.declaredFieldNames.append(f.name)
00854     return # Form.addField()

Checks whether the HTTP request method is accepted

Definition at line 829 of file forms.py.

00829 
00830   def checkRequestMethod(self):
00831     """
00832     Checks whether the HTTP request method is accepted
00833     """
00834     if not self.request_method in ['POST','GET']:
00835       raise InvalidRequestMethod(self.request_method)

Determine the HTTP content type of HTTP request

Definition at line 836 of file forms.py.

00836 
00837   def getContentType(self):
00838     """
00839     Determine the HTTP content type of HTTP request
00840     """
00841     if self.request_method=='POST':
00842       return self.env.get('CONTENT_TYPE','application/x-www-form-urlencoded').lower() or None
00843     elif self.request_method=='GET':
00844       return 'application/x-www-form-urlencoded'

Here is the caller graph for this function:

def pyweblib.forms.Form.getInputFields (   self,
  ignoreEmptyFields = 0,
  ignoreUndeclaredFields = 0,
  stripValues = 1,
  unquotePlus = 0 
)
Process user's <form> input and store the values in each
field instance's content attribute.

When a processing error occurs FormException (or derivatives)
are raised.

ignoreEmptyFields=0         Ignore fields with empty input.
ignoreUndeclaredFields=0    Ignore fields with names not declared.
                        Normally UndeclaredFieldName is raised.
stripValues=1               If true leading and trailing whitespaces
                        are stripped from all input values.
unquotePlus=0
   If non-zero urllib.unquote_plus() is used instead of urllib.unquote().

Definition at line 986 of file forms.py.

00986 
00987   ):
00988     """
00989     Process user's <form> input and store the values in each
00990     field instance's content attribute.
00991 
00992     When a processing error occurs FormException (or derivatives)
00993     are raised.
00994 
00995     ignoreEmptyFields=0         Ignore fields with empty input.
00996     ignoreUndeclaredFields=0    Ignore fields with names not declared.
00997                                 Normally UndeclaredFieldName is raised.
00998     stripValues=1               If true leading and trailing whitespaces
00999                                 are stripped from all input values.
01000     unquotePlus=0
01001        If non-zero urllib.unquote_plus() is used instead of urllib.unquote().
01002     """
01003 
01004     unquote = {0:urllib.unquote_plus,1:urllib.unquote_plus}[unquotePlus]
01005 
01006     # Calculate maxContentLength
01007     maxContentLength = 0
01008     for name,f in self.field.items():
01009       maxContentLength += f.maxValues*f.maxLen
01010 
01011     content_type = self.getContentType()
01012     if content_type.startswith('application/x-www-form-urlencoded'):
01013       # Parse user's input
01014       self._parseFormUrlEncoded(maxContentLength,ignoreEmptyFields,ignoreUndeclaredFields,stripValues,unquote)
01015     elif content_type.startswith('multipart/form-data'):
01016       self._parseMultipartFormData(maxContentLength,ignoreEmptyFields,ignoreUndeclaredFields,stripValues,unquote)
01017     else:
01018       raise FormException('Invalid content type %s received' % (repr(content_type)))
01019 
01020 
01021     # Are all required parameters present?
01022     missing_params = []
01023     for n,f in self.field.items():
01024       if f.required and not (f.name in self.inputFieldNames):
01025         missing_params.append((f.name,f.text))
01026     if missing_params:
01027       raise ParamsMissing(missing_params)
01028 
01029     return # Form.getInputFields()

Here is the call graph for this function:

Here is the caller graph for this function:

def pyweblib.forms.Form.getInputValue (   self,
  name,
  default = [] 
)
Return input value of a field defined by name if presented
in form input. Return default else.

Definition at line 855 of file forms.py.

00855 
00856   def getInputValue(self,name,default=[]):
00857     """
00858     Return input value of a field defined by name if presented
00859     in form input. Return default else.
00860     """
00861     if name in self.inputFieldNames:
00862       return self.field[name].value
00863     else:
00864       return default

def pyweblib.forms.Form.hiddenInputFields (   self,
  outf = sys.stdout,
  ignoreFieldNames = None 
)
Output all parameters as hidden fields.

outf
File object for output.
ignoreFieldNames
Names of parameters to be excluded.

Definition at line 865 of file forms.py.

00865 
00866   def hiddenInputFields(self,outf=sys.stdout,ignoreFieldNames=None):
00867     """
00868     Output all parameters as hidden fields.
00869 
00870     outf
00871         File object for output.
00872     ignoreFieldNames
00873         Names of parameters to be excluded.
00874     """
00875     ignoreFieldNames=ignoreFieldNames or []
00876     for f in [
00877       self.field[p]
00878       for p in self.declaredFieldNames
00879       if (p in self.inputFieldNames) and not (p in ignoreFieldNames)
00880     ]:
00881       for v in f.value:
00882         outf.write(
00883           '<input type="hidden" name="%s" value="%s">\n\r' % (
00884             f.name.encode(f.charset),escapeHTML(v.encode(f.charset))
00885           )
00886         )
00887     return # Form.hiddenInputFields()

Here is the call graph for this function:


Member Data Documentation

Definition at line 824 of file forms.py.

Definition at line 821 of file forms.py.

Definition at line 808 of file forms.py.

Definition at line 812 of file forms.py.

Definition at line 806 of file forms.py.

Definition at line 819 of file forms.py.

Definition at line 822 of file forms.py.

Definition at line 820 of file forms.py.

Definition at line 814 of file forms.py.

Definition at line 810 of file forms.py.

Definition at line 816 of file forms.py.

Definition at line 817 of file forms.py.


The documentation for this class was generated from the following file: