[Zope-Checkins] CVS: Zope3/lib/python/Zope/Publisher/HTTP - BrowserPayload.py:1.1.2.10 HTTPRequest.py:1.1.2.20 HTTPResponse.py:1.1.2.12

Martijn Pieters mj@zope.com
Wed, 13 Feb 2002 00:03:40 -0500


Update of /cvs-repository/Zope3/lib/python/Zope/Publisher/HTTP
In directory cvs.zope.org:/tmp/cvs-serv14206/Publisher/HTTP

Modified Files:
      Tag: Zope-3x-branch
	BrowserPayload.py HTTPRequest.py HTTPResponse.py 
Log Message:
Optimizations and code style updates:

  - Use isinstance on type checks

  - Test UnicodeType and StringType through StringTypes

  - Remove use of the string module

  - Use startswith and endswith instead of slices.

  - Fix weird tests where isinstance suffices.


=== Zope3/lib/python/Zope/Publisher/HTTP/BrowserPayload.py 1.1.2.9 => 1.1.2.10 ===
         if fslist is not None:
             tuple_items={}
-            lt=type([])
+            lt=ListType
             CGI_name = isCGI_NAME
             defaults={}
             converter=seqf=None
@@ -148,7 +148,7 @@
 
 
                 # Filter out special names from form:
-                if CGI_name(key) or key[:5]=='HTTP_': continue
+                if CGI_name(key) or key.startswith('HTTP_'): continue
 
                 if flags:
 
@@ -237,7 +237,7 @@
                        else:
                           # it is not a record or list of records
                            found=mapping_object[key]
-                           if type(found) is lt:
+                           if isinstance(found, lt):
                                found.append(item)
                            else:
                                found=[found,item]
@@ -270,7 +270,7 @@
                     if mapping_object.has_key(key):
                         # it is not a record or list of records
                         found=mapping_object[key]
-                        if type(found) is lt:
+                        if isinstance(found, lt):
                             found.append(item)
                         else:
                             found=[found,item]
@@ -287,7 +287,7 @@
                         form[keys]=values
                     else:
                         #The form has the key
-                        if getattr(values, '__class__',0) is record:
+                        if isinstance(values, record):
                            # if the key is mapped to a record, get the
                            # record
                            r = form[keys]
@@ -299,12 +299,12 @@
                                  # the attribute, set it to the default
                                  setattr(r,k,v)
                                  form[keys] = r    
-                        elif values == type([]):
+                        elif isinstance(values, ListType):
                                # the key is mapped to a list
                                l = form[keys]
                                for x in values:
                                    # for each x in the list
-                                   if getattr(x, '__class__',0) is record:
+                                   if isinstance(x, record):
                                        # if the x is a record
                                        for k, v in x.__dict__.items():
                                            
@@ -348,8 +348,7 @@
                    if form.has_key(k):
                       # If the form has the split key get its value
                       item =form[k]
-                      if (hasattr(item, '__class__') and
-                          item.__class__ is record):
+                      if isinstance(item, record):
                          # if the value is mapped to a record, check if it
                          # has the attribute, if it has it, convert it to
                          # a tuple and set it
@@ -460,9 +459,8 @@
         return response
 
     def isHTML(self, str):
-        s = str.strip()
-        return (s[:6].lower() == '<html>' or
-                s[:14].lower() == '<!doctype html')
+        s = str.strip().lower()
+        return s.startswith('<html>') or s.startswith('<!doctype html')
 
     def insertBase(self, response, body):
         # Only insert a base tag if content appears to be html.
@@ -552,12 +550,12 @@
 
 
 def str_field(v):
-    if type(v) is ListType:
+    if isinstance(v, ListType):
         return map(str_field,v)
 
-    if hasattr(v,'__class__') and v.__class__ is FieldStorage:
+    if isinstance(v, FieldStorage):
         v=v.value
-    elif type(v) is not StringType:
+    elif not isinstance(v, StringType):
         if hasattr(v,'file') and v.file: v=v.file
         elif hasattr(v,'value'): v=v.value
     return v


=== Zope3/lib/python/Zope/Publisher/HTTP/HTTPRequest.py 1.1.2.19 => 1.1.2.20 ===
 """
 
-import re, sys, os, string, time, whrandom, cgi
+import re, sys, os, time, whrandom, cgi
 from urllib import quote, unquote, splittype, splitport
+from types import StringType
 
 from Zope.Publisher.BaseRequest import BaseRequest
 from Zope.Publisher.Browser.IBrowserPublisher import IBrowserPublisher 
@@ -138,7 +139,7 @@
 
     def setVirtualRoot(self, path, hard=0):
         """ Treat the current publishing object as a VirtualRoot """
-        if type(path) is type(''):
+        if isinstance(path, StringType):
             path = filter(None, path.split('/'))
         self._script[:] = map(quote, path)
         del self.quoted_steps[:]
@@ -150,7 +151,7 @@
 
     def physicalPathToVirtualPath(self, path):
         """ Remove the path to the VirtualRoot from a physical path """
-        if type(path) is type(''):
+        if isinstance(path, StringType):
             path = path.split('/')
         rpp = self.other.get('VirtualRootPhysicalPath', ('',))
         i = 0
@@ -269,12 +270,12 @@
         else:
             server_url = self._deduceServerURL()
 
-        if server_url[-1:] == '/':
+        if server_url.endswith('/'):
             server_url = server_url[:-1]
 
         if b: self.base="%s/%s" % (server_url,b)
         else: self.base=server_url
-        while script[:1]=='/': script=script[1:]
+        while script.startswith('/'): script=script[1:]
         if script: script="%s/%s" % (server_url,script)
         else:      script=server_url
         self.URL = self.script = script
@@ -310,7 +311,7 @@
         val = environ.get(name, None)
         if val is not None:
             return val
-        if name[:5] != 'HTTP_':
+        if not name.startswith('HTTP_'):
             name='HTTP_%s' % name
         return environ.get(name, default)
 
@@ -372,19 +373,19 @@
         if v is not _marker:
             return v
 
-        if key[:1]=='U':
+        if key.startswith('U'):
             match = URLmatch(key)
             if match is not None:
                 pathonly, n = match.groups()
                 return self.computeURLn(key, int(n), pathonly)
 
-        if key[:1]=='B':
+        if key.startswith('B'):
             match = BASEmatch(key)
             if match is not None:
                 pathonly, n = match.groups()
                 return self.computeBASEn(key, int(n), pathonly)
 
-        if isCGI_NAME(key) or key[:5] == 'HTTP_':
+        if isCGI_NAME(key) or key.startswith('HTTP_'):
             environ=self.environ
             if environ.has_key(key) and (not hide_key(key)):
                 return environ[key]
@@ -409,7 +410,7 @@
         keys.update(self.common)
 
         for key in self.environ.keys():
-            if (isCGI_NAME(key) or key[:5] == 'HTTP_') and \
+            if (isCGI_NAME(key) or key.startswith('HTTP_')) and \
                (not hide_key(key)):
                     keys[key] = 1
 
@@ -469,7 +470,7 @@
         global base64
         auth=self._auth
         if auth:
-            if auth[:6].lower() == 'basic ':
+            if auth.lower().startswith('basic '):
                 if base64 is None: import base64
                 name, password = base64.decodestring(
                     auth.split()[-1]).split(':')
@@ -493,7 +494,7 @@
     # or HTTP_CGI_AUTHORIZATION hacks.
     dict={}
     for key, val in env.items():
-        while key[:9]=='REDIRECT_':
+        while key.startswith('REDIRECT_'):
             key=key[9:]
         dict[key]=val
     if dict.has_key('HTTP_CGI_AUTHORIZATION'):


=== Zope3/lib/python/Zope/Publisher/HTTP/HTTPResponse.py 1.1.2.11 => 1.1.2.12 ===
 __version__='$Revision$'[11:-2]
 
-import string, sys, re
+import sys, re
 from types import StringType, ClassType
 from cgi import escape
 
 from Zope.Publisher.BaseResponse import BaseResponse
 from Zope.Publisher.Exceptions import Redirect
 
-nl2sp = string.maketrans('\n',' ')
-
 status_reasons={
 100: 'Continue',
 101: 'Switching Protocols',
@@ -78,9 +76,8 @@
     status_codes[val.lower()] = key
     status_codes[key]=key
     status_codes[str(key)]=key
-en=filter(lambda n: n[-5:]=='Error', dir(__builtins__))
-for name in map(string.lower, en):
-    status_codes[name]=500
+[status_codes[name.lower()]
+    for name in dir(__builtins__) if name.endswith('Error')]
 
 
 accumulate_header={'set-cookie': 1}.has_key
@@ -145,7 +142,7 @@
         if status is None:
             status = 200
         else:
-            if type(status) is StringType:
+            if isinstance(status, StringType):
                 status = status.lower()
             if status_codes.has_key(status):
                 status=status_codes[status]
@@ -193,7 +190,7 @@
 
     def updateContentLength(self):
         blen = str(len(self.body))
-        if blen[-1:] == 'L':
+        if blen.endswith('L'):
             blen = blen[:-1]
         self.setHeader('content-length', blen)