Commit f5ca408b authored by Andreas Jung's avatar Andreas Jung

string module calls -> string methods

parent 96c788d4
...@@ -10,9 +10,8 @@ ...@@ -10,9 +10,8 @@
# FOR A PARTICULAR PURPOSE # FOR A PARTICULAR PURPOSE
# #
############################################################################## ##############################################################################
__version__='$Revision: 1.45 $'[11:-2] __version__='$Revision: 1.46 $'[11:-2]
from string import join, split, find, rfind, lower, upper
from urllib import quote from urllib import quote
UNSPECIFIED_ROLES='' UNSPECIFIED_ROLES=''
...@@ -162,7 +161,7 @@ class BaseRequest: ...@@ -162,7 +161,7 @@ class BaseRequest:
def __str__(self): def __str__(self):
L1 = self.items() L1 = self.items()
L1.sort() L1.sort()
return join(map(lambda item: "%s:\t%s" % item, L1), "\n") return '\n'.join(map(lambda item: "%s:\t%s" % item, L1))
__repr__=__str__ __repr__=__str__
...@@ -182,7 +181,7 @@ class BaseRequest: ...@@ -182,7 +181,7 @@ class BaseRequest:
if path[:1]=='/': path=path[1:] if path[:1]=='/': path=path[1:]
if path[-1:]=='/': path=path[:-1] if path[-1:]=='/': path=path[:-1]
clean=[] clean=[]
for item in split(path, '/'): for item in path.split('/'):
# Make sure that certain things that dont make sense # Make sure that certain things that dont make sense
# cannot be traversed. # cannot be traversed.
if item in ('REQUEST', 'aq_self', 'aq_base'): if item in ('REQUEST', 'aq_self', 'aq_base'):
...@@ -195,7 +194,7 @@ class BaseRequest: ...@@ -195,7 +194,7 @@ class BaseRequest:
path=clean path=clean
# How did this request come in? (HTTP GET, PUT, POST, etc.) # How did this request come in? (HTTP GET, PUT, POST, etc.)
method=req_method=upper(request_get('REQUEST_METHOD', 'GET')) method=req_method=request_get('REQUEST_METHOD', 'GET').upper()
no_acquire_flag=0 no_acquire_flag=0
...@@ -261,7 +260,7 @@ class BaseRequest: ...@@ -261,7 +260,7 @@ class BaseRequest:
hasattr(object.__call__,'__roles__')): hasattr(object.__call__,'__roles__')):
roles=object.__call__.__roles__ roles=object.__call__.__roles__
if request._hacked_path: if request._hacked_path:
i=rfind(URL,'/') i=URL.rfind('/')
if i > 0: response.setBase(URL[:i]) if i > 0: response.setBase(URL[:i])
break break
if not entry_name: continue if not entry_name: continue
...@@ -407,7 +406,7 @@ class BaseRequest: ...@@ -407,7 +406,7 @@ class BaseRequest:
if user is not None: if user is not None:
if validated_hook is not None: validated_hook(self, user) if validated_hook is not None: validated_hook(self, user)
request['AUTHENTICATED_USER']=user request['AUTHENTICATED_USER']=user
request['AUTHENTICATION_PATH']=join(steps[:-i],'/') request['AUTHENTICATION_PATH']='/'.join(steps[:-i])
# Remove http request method from the URL. # Remove http request method from the URL.
request['URL']=URL request['URL']=URL
......
...@@ -12,11 +12,10 @@ ...@@ -12,11 +12,10 @@
############################################################################## ##############################################################################
'''CGI Response Output formatter '''CGI Response Output formatter
$Id: BaseResponse.py,v 1.11 2002/01/02 15:01:20 andreasjung Exp $''' $Id: BaseResponse.py,v 1.12 2002/01/02 15:56:04 andreasjung Exp $'''
__version__='$Revision: 1.11 $'[11:-2] __version__='$Revision: 1.12 $'[11:-2]
import types, sys import types, sys
from string import find, rfind, lower, upper, strip, split, join, translate
from types import StringType, InstanceType from types import StringType, InstanceType
from zExceptions import Unauthorized from zExceptions import Unauthorized
......
...@@ -31,7 +31,7 @@ that allows one to simply make a single web request. ...@@ -31,7 +31,7 @@ that allows one to simply make a single web request.
The module also provides a command-line interface for calling objects. The module also provides a command-line interface for calling objects.
""" """
__version__='$Revision: 1.43 $'[11:-2] __version__='$Revision: 1.44 $'[11:-2]
import sys, re, socket, mimetools import sys, re, socket, mimetools
from httplib import HTTP from httplib import HTTP
...@@ -41,7 +41,7 @@ from random import random ...@@ -41,7 +41,7 @@ from random import random
from base64 import encodestring from base64 import encodestring
from urllib import urlopen, quote from urllib import urlopen, quote
from types import FileType, ListType, DictType, TupleType from types import FileType, ListType, DictType, TupleType
from string import strip, split, atoi, join, rfind, translate, maketrans, replace, lower from string import translate, maketrans
from urlparse import urlparse from urlparse import urlparse
class Function: class Function:
...@@ -59,7 +59,7 @@ class Function: ...@@ -59,7 +59,7 @@ class Function:
self.headers=headers self.headers=headers
if not headers.has_key('Host') and not headers.has_key('host'): if not headers.has_key('Host') and not headers.has_key('host'):
headers['Host']=urlparse(url)[1] headers['Host']=urlparse(url)[1]
self.func_name=url[rfind(url,'/')+1:] self.func_name=url[url.rfind('/')+1:]
self.__dict__['__name__']=self.func_name self.__dict__['__name__']=self.func_name
self.func_defaults=() self.func_defaults=()
...@@ -73,7 +73,7 @@ class Function: ...@@ -73,7 +73,7 @@ class Function:
mo = urlregex.match(url) mo = urlregex.match(url)
if mo is not None: if mo is not None:
host,port,rurl=mo.group(1,2,3) host,port,rurl=mo.group(1,2,3)
if port: port=atoi(port[1:]) if port: port=int(port[1:])
else: port=80 else: port=80
self.host=host self.host=host
self.port=port self.port=port
...@@ -117,7 +117,7 @@ class Function: ...@@ -117,7 +117,7 @@ class Function:
url=self.rurl url=self.rurl
if query: if query:
query=join(query,'&') query='&'.join(query)
method=method or 'POST' method=method or 'POST'
if method == 'PUT': if method == 'PUT':
headers['Content-Length']=str(len(query)) headers['Content-Length']=str(len(query))
...@@ -133,8 +133,9 @@ class Function: ...@@ -133,8 +133,9 @@ class Function:
not headers.has_key('Authorization')): not headers.has_key('Authorization')):
headers['Authorization']=( headers['Authorization']=(
"Basic %s" % "Basic %s" %
replace(encodestring('%s:%s' % (self.username,self.password)), encodestring('%s:%s' % (self.username,self.password)).replace(
'\012','')) '\012','')
)
try: try:
h=HTTP() h=HTTP()
...@@ -196,10 +197,10 @@ class Function: ...@@ -196,10 +197,10 @@ class Function:
for n,v in self.headers.items(): for n,v in self.headers.items():
rq.append('%s: %s' % (n,v)) rq.append('%s: %s' % (n,v))
if self.username and self.password: if self.username and self.password:
c=replace(encodestring('%s:%s' % (self.username,self.password)),'\012','') c=encodestring('%s:%s' % (self.username,self.password)).replace('\012','')
rq.append('Authorization: Basic %s' % c) rq.append('Authorization: Basic %s' % c)
rq.append(MultiPart(d).render()) rq.append(MultiPart(d).render())
rq=join(rq,'\r\n') rq='\r\n'.join(rq)
try: try:
sock=socket.socket(socket.AF_INET,socket.SOCK_STREAM) sock=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
...@@ -210,14 +211,14 @@ class Function: ...@@ -210,14 +211,14 @@ class Function:
line=reply.readline() line=reply.readline()
try: try:
[ver, ec, em] = split(line, None, 2) [ver, ec, em] = line.split(None, 2)
except ValueError: except ValueError:
raise 'BadReply','Bad reply from server: '+line raise 'BadReply','Bad reply from server: '+line
if ver[:5] != 'HTTP/': if ver[:5] != 'HTTP/':
raise 'BadReply','Bad reply from server: '+line raise 'BadReply','Bad reply from server: '+line
ec=atoi(ec) ec=int(ec)
em=strip(em) em=em.strip()
headers=mimetools.Message(reply,0) headers=mimetools.Message(reply,0)
response=reply.read() response=reply.read()
finally: finally:
...@@ -295,7 +296,7 @@ def marshal_list(n,l,tname='list', lt=type([]), tt=type(())): ...@@ -295,7 +296,7 @@ def marshal_list(n,l,tname='list', lt=type([]), tt=type(())):
raise TypeError, 'Invalid recursion in data to be marshaled.' raise TypeError, 'Invalid recursion in data to be marshaled.'
r.append(marshal_whatever("%s:%s" % (n,tname) ,v)) r.append(marshal_whatever("%s:%s" % (n,tname) ,v))
return join(r,'&') return '&'.join(r)
def marshal_tuple(n,l): def marshal_tuple(n,l):
return marshal_list(n,l,'tuple') return marshal_list(n,l,'tuple')
...@@ -317,7 +318,7 @@ def querify(items): ...@@ -317,7 +318,7 @@ def querify(items):
query=[] query=[]
for k,v in items: query.append(marshal_whatever(k,v)) for k,v in items: query.append(marshal_whatever(k,v))
return query and join(query,'&') or '' return query and '&'.join(query) or ''
NotFound ='bci.NotFound' NotFound ='bci.NotFound'
InternalError='bci.InternalError' InternalError='bci.InternalError'
...@@ -400,9 +401,9 @@ class MultiPart: ...@@ -400,9 +401,9 @@ class MultiPart:
elif dt==FileType or hasattr(val,'read'): elif dt==FileType or hasattr(val,'read'):
if hasattr(val,'name'): if hasattr(val,'name'):
fn=replace(val.name, '\\', '/') fn=val.name.replace( '\\', '/')
fn=fn[(rfind(fn,'/')+1):] fn=fn[(fn.rfind('/')+1):]
ex=lower(fn[(rfind(fn,'.')+1):]) ex=(fn[(fn.rfind('.')+1):]).lower()
if self._extmap.has_key(ex): if self._extmap.has_key(ex):
ct=self._extmap[ex] ct=self._extmap[ex]
else: else:
...@@ -454,12 +455,12 @@ class MultiPart: ...@@ -454,12 +455,12 @@ class MultiPart:
b=self._boundary b=self._boundary
for d in self._data: p.append(d.render()) for d in self._data: p.append(d.render())
t.append('--%s\n' % b) t.append('--%s\n' % b)
t.append(join(p,'\n--%s\n' % b)) t.append(('\n--%s\n' % b).join(p))
t.append('\n--%s--\n' % b) t.append('\n--%s--\n' % b)
t=join(t,'') t=''.join(t)
s.append('Content-Length: %s\r\n\r\n' % len(t)) s.append('Content-Length: %s\r\n\r\n' % len(t))
s.append(t) s.append(t)
return join(s,'') return ''.join(s)
else: else:
for n,v in h.items(): for n,v in h.items():
...@@ -475,11 +476,11 @@ class MultiPart: ...@@ -475,11 +476,11 @@ class MultiPart:
b=self._boundary b=self._boundary
for d in self._data: p.append(d.render()) for d in self._data: p.append(d.render())
s.append('--%s\n' % b) s.append('--%s\n' % b)
s.append(join(p,'\n--%s\n' % b)) s.append(('\n--%s\n' % b).join(p))
s.append('\n--%s--\n' % b) s.append('\n--%s--\n' % b)
return join(s,'') return ''.join(s)
else: else:
return join(s+self._data,'') return ''.join(s+self._data)
_extmap={'': 'text/plain', _extmap={'': 'text/plain',
...@@ -526,7 +527,6 @@ The headers of the response are written to standard error. ...@@ -526,7 +527,6 @@ The headers of the response are written to standard error.
def main(): def main():
import getopt import getopt
from string import split
user=None user=None
...@@ -535,11 +535,11 @@ def main(): ...@@ -535,11 +535,11 @@ def main():
url=args[0] url=args[0]
u =filter(lambda o: o[0]=='-u', optlist) u =filter(lambda o: o[0]=='-u', optlist)
if u: if u:
[user, pw] = split(u[0][1],':') [user, pw] = u[0][1].split(':')
kw={} kw={}
for arg in args[1:]: for arg in args[1:]:
[name,v]=split(arg,'=') [name,v]=arg.split('=')
if name[-5:]==':file': if name[-5:]==':file':
name=name[:-5] name=name[:-5]
if v=='-': v=sys.stdin if v=='-': v=sys.stdin
...@@ -554,7 +554,7 @@ def main(): ...@@ -554,7 +554,7 @@ def main():
f=Function(url) f=Function(url)
if user: f.username, f.password = user, pw if user: f.username, f.password = user, pw
headers, body = apply(f,(),kw) headers, body = apply(f,(),kw)
sys.stderr.write(join(map(lambda h: "%s: %s\n" % h, headers.items()),"") sys.stderr.write(''.join(map(lambda h: "%s: %s\n" % h, headers.items()))
+"\n\n") +"\n\n")
print body print body
......
...@@ -10,16 +10,17 @@ ...@@ -10,16 +10,17 @@
# FOR A PARTICULAR PURPOSE # FOR A PARTICULAR PURPOSE
# #
############################################################################## ##############################################################################
__version__='$Revision: 1.13 $'[11:-2] __version__='$Revision: 1.14 $'[11:-2]
import re import re
from string import atoi, atol, atof, join, split, strip from types import ListType, TupleType, UnicodeType
from types import ListType, TupleType
def field2string(v): def field2string(v):
if hasattr(v,'read'): v=v.read() if hasattr(v,'read'): return v.read()
else: v=str(v) elif isinstance(v,UnicodeType) :
return v return v
else:
return str(v)
def field2text(v, nl=re.compile('\r\n|\n\r').search): def field2text(v, nl=re.compile('\r\n|\n\r').search):
if hasattr(v,'read'): v=v.read() if hasattr(v,'read'): v=v.read()
...@@ -38,12 +39,12 @@ def field2text(v, nl=re.compile('\r\n|\n\r').search): ...@@ -38,12 +39,12 @@ def field2text(v, nl=re.compile('\r\n|\n\r').search):
r.append(v[s:]) r.append(v[s:])
return join(r,'\n') return '\n'.join(r)
def field2required(v): def field2required(v):
if hasattr(v,'read'): v=v.read() if hasattr(v,'read'): v=v.read()
else: v=str(v) else: v=str(v)
if strip(v): return v if v.strip(): return v
raise ValueError, 'No input for required field<p>' raise ValueError, 'No input for required field<p>'
def field2int(v): def field2int(v):
...@@ -52,7 +53,7 @@ def field2int(v): ...@@ -52,7 +53,7 @@ def field2int(v):
if hasattr(v,'read'): v=v.read() if hasattr(v,'read'): v=v.read()
else: v=str(v) else: v=str(v)
if v: if v:
try: return atoi(v) try: return int(v)
except ValueError: except ValueError:
raise ValueError, ( raise ValueError, (
"An integer was expected in the value '%s'" % v "An integer was expected in the value '%s'" % v
...@@ -65,7 +66,7 @@ def field2float(v): ...@@ -65,7 +66,7 @@ def field2float(v):
if hasattr(v,'read'): v=v.read() if hasattr(v,'read'): v=v.read()
else: v=str(v) else: v=str(v)
if v: if v:
try: return atof(v) try: return float(v)
except ValueError: except ValueError:
raise ValueError, ( raise ValueError, (
"A floating-point number was expected in the value '%s'" % v "A floating-point number was expected in the value '%s'" % v
...@@ -83,7 +84,7 @@ def field2long(v): ...@@ -83,7 +84,7 @@ def field2long(v):
if v[-1:] in ('L', 'l'): if v[-1:] in ('L', 'l'):
v = v[:-1] v = v[:-1]
if v: if v:
try: return atol(v) try: return long(v)
except ValueError: except ValueError:
raise ValueError, ( raise ValueError, (
"A long integer was expected in the value '%s'" % v "A long integer was expected in the value '%s'" % v
...@@ -93,7 +94,7 @@ def field2long(v): ...@@ -93,7 +94,7 @@ def field2long(v):
def field2tokens(v): def field2tokens(v):
if hasattr(v,'read'): v=v.read() if hasattr(v,'read'): v=v.read()
else: v=str(v) else: v=str(v)
return split(v) return v.split()
def field2lines(v): def field2lines(v):
if type(v) in (ListType, TupleType): if type(v) in (ListType, TupleType):
...@@ -101,7 +102,7 @@ def field2lines(v): ...@@ -101,7 +102,7 @@ def field2lines(v):
for item in v: for item in v:
result.append(str(item)) result.append(str(item))
return result return result
return split(field2text(v),'\n') return field2text(v).split('\n')
def field2date(v): def field2date(v):
from DateTime import DateTime from DateTime import DateTime
......
...@@ -19,9 +19,9 @@ flag-interface and some support functions for implementing this functionality. ...@@ -19,9 +19,9 @@ flag-interface and some support functions for implementing this functionality.
For an implementation example, see the File class in OFS/Image.py. For an implementation example, see the File class in OFS/Image.py.
""" """
__version__='$Revision: 1.5 $'[11:-2] __version__='$Revision: 1.6 $'[11:-2]
import re, string, sys import re, sys
import Interface import Interface
WHITESPACE = re.compile('\s*', re.MULTILINE) WHITESPACE = re.compile('\s*', re.MULTILINE)
...@@ -45,13 +45,13 @@ def parseRange(header): ...@@ -45,13 +45,13 @@ def parseRange(header):
header = WHITESPACE.sub('', header) header = WHITESPACE.sub('', header)
# A range header only can specify a byte range # A range header only can specify a byte range
try: spec, sets = string.split(header, '=') try: spec, sets = header.split('=')
except ValueError: return None except ValueError: return None
if spec != 'bytes': if spec != 'bytes':
return None return None
# The sets are delimited by commas. # The sets are delimited by commas.
sets = string.split(sets, ',') sets = sets.split(',')
# Filter out empty values, things like ',,' are allowed in the spec # Filter out empty values, things like ',,' are allowed in the spec
sets = filter(None, sets) sets = filter(None, sets)
# We need at least one set # We need at least one set
...@@ -59,7 +59,7 @@ def parseRange(header): ...@@ -59,7 +59,7 @@ def parseRange(header):
return None return None
for set in sets: for set in sets:
try: start, end = string.split(set, '-') try: start, end = set.split('-')
except ValueError: return None except ValueError: return None
# Catch empty sets # Catch empty sets
......
...@@ -11,10 +11,9 @@ ...@@ -11,10 +11,9 @@
# #
############################################################################## ##############################################################################
__version__='$Revision: 1.59 $'[11:-2] __version__='$Revision: 1.60 $'[11:-2]
import re, sys, os, string, urllib, time, whrandom, cgi import re, sys, os, urllib, time, whrandom, cgi
from string import lower, atoi, rfind, split, strip, join, upper, find
from BaseRequest import BaseRequest from BaseRequest import BaseRequest
from HTTPResponse import HTTPResponse from HTTPResponse import HTTPResponse
from cgi import FieldStorage, escape from cgi import FieldStorage, escape
...@@ -159,7 +158,7 @@ class HTTPRequest(BaseRequest): ...@@ -159,7 +158,7 @@ class HTTPRequest(BaseRequest):
""" Treat the current publishing object as a VirtualRoot """ """ Treat the current publishing object as a VirtualRoot """
other = self.other other = self.other
if type(path) is type(''): if type(path) is type(''):
path = filter(None, split(path, '/')) path = filter(None, path.split( '/'))
self._script[:] = map(quote, path) self._script[:] = map(quote, path)
del self._steps[:] del self._steps[:]
parents = other['PARENTS'] parents = other['PARENTS']
...@@ -171,7 +170,7 @@ class HTTPRequest(BaseRequest): ...@@ -171,7 +170,7 @@ class HTTPRequest(BaseRequest):
def physicalPathToVirtualPath(self, path): def physicalPathToVirtualPath(self, path):
""" Remove the path to the VirtualRoot from a physical path """ """ Remove the path to the VirtualRoot from a physical path """
if type(path) is type(''): if type(path) is type(''):
path = split(path, '/') path = path.split( '/')
rpp = self.other.get('VirtualRootPhysicalPath', ('',)) rpp = self.other.get('VirtualRootPhysicalPath', ('',))
i = 0 i = 0
for name in rpp[:len(path)]: for name in rpp[:len(path)]:
...@@ -188,7 +187,7 @@ class HTTPRequest(BaseRequest): ...@@ -188,7 +187,7 @@ class HTTPRequest(BaseRequest):
path.insert(0, '') path.insert(0, '')
else: else:
path.insert(0, self['SERVER_URL']) path.insert(0, self['SERVER_URL'])
return join(path, '/') return '/'.join(path)
def physicalPathFromURL(self, URL): def physicalPathFromURL(self, URL):
""" Convert a URL into a physical path in the current context. """ Convert a URL into a physical path in the current context.
...@@ -196,9 +195,9 @@ class HTTPRequest(BaseRequest): ...@@ -196,9 +195,9 @@ class HTTPRequest(BaseRequest):
hosting context, a ValueError is raised.""" hosting context, a ValueError is raised."""
other = self.other other = self.other
bad_server_url = 0 bad_server_url = 0
path = filter(None, split(URL, '/')) path = filter(None, URL.split( '/'))
if find(URL, '://') >= 0: if URL.find( '://') >= 0:
path = path[2:] path = path[2:]
# Check the path against BASEPATH1 # Check the path against BASEPATH1
...@@ -216,8 +215,8 @@ class HTTPRequest(BaseRequest): ...@@ -216,8 +215,8 @@ class HTTPRequest(BaseRequest):
def _resetURLS(self): def _resetURLS(self):
other = self.other other = self.other
other['URL'] = join([other['SERVER_URL']] + self._script + other['URL'] = '/'.join([other['SERVER_URL']] + self._script +
self._steps, '/') self._steps)
for x in self._urls: for x in self._urls:
del self.other[x] del self.other[x]
self._urls = () self._urls = ()
...@@ -249,20 +248,20 @@ class HTTPRequest(BaseRequest): ...@@ -249,20 +248,20 @@ class HTTPRequest(BaseRequest):
################################################################ ################################################################
# Get base info first. This isn't likely to cause # Get base info first. This isn't likely to cause
# errors and might be useful to error handlers. # errors and might be useful to error handlers.
b=script=strip(get_env('SCRIPT_NAME','')) b=script=get_env('SCRIPT_NAME','').strip()
# _script and the other _names are meant for URL construction # _script and the other _names are meant for URL construction
self._script = map(quote, filter(None, split(script, '/'))) self._script = map(quote, filter(None, script.split( '/')))
while b and b[-1]=='/': b=b[:-1] while b and b[-1]=='/': b=b[:-1]
p = rfind(b,'/') p = b.rfind('/')
if p >= 0: b=b[:p+1] if p >= 0: b=b[:p+1]
else: b='' else: b=''
while b and b[0]=='/': b=b[1:] while b and b[0]=='/': b=b[1:]
server_url=get_env('SERVER_URL',None) server_url=get_env('SERVER_URL',None)
if server_url is not None: if server_url is not None:
other['SERVER_URL'] = server_url = strip(server_url) other['SERVER_URL'] = server_url = server_url.strip()
else: else:
if have_env('HTTPS') and ( if have_env('HTTPS') and (
environ['HTTPS'] == "on" or environ['HTTPS'] == "ON"): environ['HTTPS'] == "on" or environ['HTTPS'] == "ON"):
...@@ -273,7 +272,7 @@ class HTTPRequest(BaseRequest): ...@@ -273,7 +272,7 @@ class HTTPRequest(BaseRequest):
else: protocol = 'http' else: protocol = 'http'
if have_env('HTTP_HOST'): if have_env('HTTP_HOST'):
host = strip(environ['HTTP_HOST']) host = environ['HTTP_HOST'].strip()
hostname, port = splitport(host) hostname, port = splitport(host)
# NOTE: some (DAV) clients manage to forget the port. This # NOTE: some (DAV) clients manage to forget the port. This
...@@ -288,7 +287,7 @@ class HTTPRequest(BaseRequest): ...@@ -288,7 +287,7 @@ class HTTPRequest(BaseRequest):
# port=s_port # port=s_port
else: else:
hostname = strip(environ['SERVER_NAME']) hostname = environ['SERVER_NAME'].strip()
port = environ['SERVER_PORT'] port = environ['SERVER_PORT']
self.setServerURL(protocol=protocol, hostname=hostname, port=port) self.setServerURL(protocol=protocol, hostname=hostname, port=port)
server_url = other['SERVER_URL'] server_url = other['SERVER_URL']
...@@ -329,7 +328,6 @@ class HTTPRequest(BaseRequest): ...@@ -329,7 +328,6 @@ class HTTPRequest(BaseRequest):
getattr=getattr, getattr=getattr,
setattr=setattr, setattr=setattr,
search_type=re.compile('(:[a-zA-Z][a-zA-Z0-9_]+|\\.[xy])$').search, search_type=re.compile('(:[a-zA-Z][a-zA-Z0-9_]+|\\.[xy])$').search,
rfind=string.rfind,
): ):
"""Process request inputs """Process request inputs
...@@ -396,7 +394,7 @@ class HTTPRequest(BaseRequest): ...@@ -396,7 +394,7 @@ class HTTPRequest(BaseRequest):
# a re search. # a re search.
l=rfind(key,':') l=key.rfind(':')
if l >= 0: if l >= 0:
mo = search_type(key,l) mo = search_type(key,l)
if mo: l=mo.start(0) if mo: l=mo.start(0)
...@@ -434,7 +432,7 @@ class HTTPRequest(BaseRequest): ...@@ -434,7 +432,7 @@ class HTTPRequest(BaseRequest):
elif type_name == 'ignore_empty': elif type_name == 'ignore_empty':
if not item: flags=flags|EMPTY if not item: flags=flags|EMPTY
l=rfind(key,':') l=key.rfind(':')
if l < 0: break if l < 0: break
mo=search_type(key,l) mo=search_type(key,l)
if mo: l = mo.start(0) if mo: l = mo.start(0)
...@@ -452,8 +450,8 @@ class HTTPRequest(BaseRequest): ...@@ -452,8 +450,8 @@ class HTTPRequest(BaseRequest):
#Split the key and its attribute #Split the key and its attribute
if flags&REC: if flags&REC:
key=split(key,".") key=key.split(".")
key, attr=join(key[:-1],"."), key[-1] key, attr=".".join(key[:-1]), key[-1]
# defer conversion # defer conversion
if flags&CONVERTED: if flags&CONVERTED:
...@@ -632,13 +630,13 @@ class HTTPRequest(BaseRequest): ...@@ -632,13 +630,13 @@ class HTTPRequest(BaseRequest):
if tuple_items: if tuple_items:
for key in tuple_items.keys(): for key in tuple_items.keys():
# Split the key and get the attr # Split the key and get the attr
k=split(key, ".") k=key.split( ".")
k,attr=join(k[:-1], "."), k[-1] k,attr='.'.join(k[:-1]), k[-1]
a = attr a = attr
# remove any type_names in the attr # remove any type_names in the attr
while not a=='': while not a=='':
a=split(a, ":") a=a.split( ":")
a,new=join(a[:-1], ":"), a[-1] a,new=':'.join(a[:-1]), a[-1]
attr = new attr = new
if form.has_key(k): if form.has_key(k):
# If the form has the split key get its value # If the form has the split key get its value
...@@ -688,7 +686,7 @@ class HTTPRequest(BaseRequest): ...@@ -688,7 +686,7 @@ class HTTPRequest(BaseRequest):
# namespace (e.g. the host, port or script name dont # namespace (e.g. the host, port or script name dont
# match that of the current request), a ValueError will # match that of the current request), a ValueError will
# be raised. # be raised.
if find(url, self.script) != 0: if url.find(self.script) != 0:
raise ValueError, 'Different namespace.' raise ValueError, 'Different namespace.'
path=url[len(self.script):] path=url[len(self.script):]
while path and path[0]=='/': path=path[1:] while path and path[0]=='/': path=path[1:]
...@@ -746,7 +744,7 @@ class HTTPRequest(BaseRequest): ...@@ -746,7 +744,7 @@ class HTTPRequest(BaseRequest):
should all return the Content-Type header, if available. should all return the Content-Type header, if available.
""" """
environ=self.environ environ=self.environ
name=upper(join(split(name,"-"),"_")) name=('_'.join(name.split("-"))).upper()
val=environ.get(name, None) val=environ.get(name, None)
if val is not None: if val is not None:
return val return val
...@@ -783,7 +781,7 @@ class HTTPRequest(BaseRequest): ...@@ -783,7 +781,7 @@ class HTTPRequest(BaseRequest):
path = [''] + path[:n] path = [''] + path[:n]
else: else:
path = [other['SERVER_URL']] + path[:n] path = [other['SERVER_URL']] + path[:n]
other[key] = URL = join(path, '/') other[key] = URL = '/'.join(path)
self._urls = self._urls + (key,) self._urls = self._urls + (key,)
return URL return URL
...@@ -813,7 +811,7 @@ class HTTPRequest(BaseRequest): ...@@ -813,7 +811,7 @@ class HTTPRequest(BaseRequest):
v.insert(0, '') v.insert(0, '')
else: else:
v.insert(0, other['SERVER_URL']) v.insert(0, other['SERVER_URL'])
other[key] = URL = join(v, '/') other[key] = URL = '/'.join(v)
self._urls = self._urls + (key,) self._urls = self._urls + (key,)
return URL return URL
...@@ -960,10 +958,10 @@ class HTTPRequest(BaseRequest): ...@@ -960,10 +958,10 @@ class HTTPRequest(BaseRequest):
global base64 global base64
auth=self._auth auth=self._auth
if auth: if auth:
if lower(auth[:6]) == 'basic ': if auth[:6].lower() == 'basic ':
if base64 is None: import base64 if base64 is None: import base64
[name,password] = split( [name,password] = \
base64.decodestring(split(auth)[-1]), ':') base64.decodestring(split(auth)[-1]).split(':')
return name, password return name, password
...@@ -1100,14 +1098,13 @@ class record: ...@@ -1100,14 +1098,13 @@ class record:
def __str__(self): def __str__(self):
L1 = self.__dict__.items() L1 = self.__dict__.items()
L1.sort() L1.sort()
return join(map(lambda item: "%s: %s" % item, L1), ", ") return ", ".join(map(lambda item: "%s: %s" % item, L1))
def __repr__(self): def __repr__(self):
L1 = self.__dict__.items() L1 = self.__dict__.items()
L1.sort() L1.sort()
return join( return ', '.join(
map(lambda item: "%s: %s" % (item[0], repr(item[1])), L1) map(lambda item: "%s: %s" % (item[0], repr(item[1])), L1))
, ", ")
# Flags # Flags
SEQUENCE=1 SEQUENCE=1
......
...@@ -12,16 +12,16 @@ ...@@ -12,16 +12,16 @@
############################################################################## ##############################################################################
'''CGI Response Output formatter '''CGI Response Output formatter
$Id: HTTPResponse.py,v 1.52 2001/11/28 15:51:20 matt Exp $''' $Id: HTTPResponse.py,v 1.53 2002/01/02 15:56:04 andreasjung Exp $'''
__version__='$Revision: 1.52 $'[11:-2] __version__='$Revision: 1.53 $'[11:-2]
import string, types, sys, re import types, sys, re
from string import find, rfind, lower, upper, strip, split, join, translate from string import translate, maketrans
from types import StringType, InstanceType, LongType from types import StringType, InstanceType, LongType
from BaseResponse import BaseResponse from BaseResponse import BaseResponse
from zExceptions import Unauthorized from zExceptions import Unauthorized
nl2sp=string.maketrans('\n',' ') nl2sp=maketrans('\n',' ')
status_reasons={ status_reasons={
100: 'Continue', 100: 'Continue',
...@@ -76,13 +76,13 @@ status_codes={} ...@@ -76,13 +76,13 @@ status_codes={}
# Add mappings for builtin exceptions and # Add mappings for builtin exceptions and
# provide text -> error code lookups. # provide text -> error code lookups.
for key, val in status_reasons.items(): for key, val in status_reasons.items():
status_codes[lower(join(split(val, ' '), ''))]=key status_codes[''.join(val.split(' ')).lower()]=key
status_codes[lower(val)]=key status_codes[val.lower()]=key
status_codes[key]=key status_codes[key]=key
status_codes[str(key)]=key status_codes[str(key)]=key
en=filter(lambda n: n[-5:]=='Error', dir(__builtins__)) en=filter(lambda n: n[-5:]=='Error', dir(__builtins__))
for name in map(lower, en): for name in en:
status_codes[name]=500 status_codes[name.lower()]=500
status_codes['nameerror']=503 status_codes['nameerror']=503
status_codes['keyerror']=503 status_codes['keyerror']=503
status_codes['redirect']=300 status_codes['redirect']=300
...@@ -165,7 +165,7 @@ class HTTPResponse(BaseResponse): ...@@ -165,7 +165,7 @@ class HTTPResponse(BaseResponse):
return return
if type(status) is types.StringType: if type(status) is types.StringType:
status=lower(status) status=status.lower()
if status_codes.has_key(status): status=status_codes[status] if status_codes.has_key(status): status=status_codes[status]
else: status=500 else: status=500
self.status=status self.status=status
...@@ -182,7 +182,7 @@ class HTTPResponse(BaseResponse): ...@@ -182,7 +182,7 @@ class HTTPResponse(BaseResponse):
literal flag is true, the case of the header name is preserved, literal flag is true, the case of the header name is preserved,
otherwise word-capitalization will be performed on the header otherwise word-capitalization will be performed on the header
name on output.''' name on output.'''
key=lower(name) key=name.lower()
if accumulate_header(key): if accumulate_header(key):
self.accumulated_headers=( self.accumulated_headers=(
"%s%s: %s\n" % (self.accumulated_headers, name, value)) "%s%s: %s\n" % (self.accumulated_headers, name, value))
...@@ -232,7 +232,7 @@ class HTTPResponse(BaseResponse): ...@@ -232,7 +232,7 @@ class HTTPResponse(BaseResponse):
body=str(body) body=str(body)
l=len(body) l=len(body)
if ((l < 200) and body[:1]=='<' and find(body,'>')==l-1 and if ((l < 200) and body[:1]=='<' and body.find('>')==l-1 and
bogus_str_search(body) is not None): bogus_str_search(body) is not None):
self.notFoundError(body[1:-1]) self.notFoundError(body[1:-1])
else: else:
...@@ -258,8 +258,8 @@ class HTTPResponse(BaseResponse): ...@@ -258,8 +258,8 @@ class HTTPResponse(BaseResponse):
content_type=self.headers['content-type'] content_type=self.headers['content-type']
if content_type == 'text/html' or latin1_alias_match( if content_type == 'text/html' or latin1_alias_match(
content_type) is not None: content_type) is not None:
body = join(split(body,'\213'),'&lt;') body = '&lt;'.join(body.split('\213'))
body = join(split(body,'\233'),'&gt;') body = '&gt;'.join(body.split('\233'))
self.setHeader('content-length', len(self.body)) self.setHeader('content-length', len(self.body))
self.insertBase() self.insertBase()
...@@ -276,7 +276,7 @@ class HTTPResponse(BaseResponse): ...@@ -276,7 +276,7 @@ class HTTPResponse(BaseResponse):
): ):
# Only insert a base tag if content appears to be html. # Only insert a base tag if content appears to be html.
content_type = split(self.headers.get('content-type', ''), ';')[0] content_type = self.headers.get('content-type', '').split(';')[0]
if content_type and (content_type != 'text/html'): if content_type and (content_type != 'text/html'):
return return
...@@ -355,14 +355,14 @@ class HTTPResponse(BaseResponse): ...@@ -355,14 +355,14 @@ class HTTPResponse(BaseResponse):
self.setHeader(name,h) self.setHeader(name,h)
def isHTML(self,str): def isHTML(self,str):
return lower(strip(str)[:6]) == '<html>' or find(str,'</') > 0 return str.strip().lower()[:6] == '<html>' or str.find('</') > 0
def quoteHTML(self,text, def quoteHTML(self,text,
subs={'&':'&amp;', "<":'&lt;', ">":'&gt;', '\"':'&quot;'} subs={'&':'&amp;', "<":'&lt;', ">":'&gt;', '\"':'&quot;'}
): ):
for ent in '&<>\"': for ent in '&<>\"':
if find(text, ent) >= 0: if text.find( ent) >= 0:
text=join(split(text,ent),subs[ent]) text=subs[ent].join(text.split(ent))
return text return text
...@@ -391,13 +391,12 @@ class HTTPResponse(BaseResponse): ...@@ -391,13 +391,12 @@ class HTTPResponse(BaseResponse):
except: pass except: pass
tb = tb.tb_next tb = tb.tb_next
n = n + 1 n = n + 1
result.append(join(traceback.format_exception_only(etype, value), result.append(' '.join(traceback.format_exception_only(etype, value)))
' '))
return result return result
def _traceback(self, t, v, tb): def _traceback(self, t, v, tb):
tb = self.format_exception(t, v, tb, 200) tb = self.format_exception(t, v, tb, 200)
tb = join(tb, '\n') tb = '\n'.join(tb)
tb = self.quoteHTML(tb) tb = self.quoteHTML(tb)
if self.debug_mode: _tbopen, _tbclose = '<PRE>', '</PRE>' if self.debug_mode: _tbopen, _tbclose = '<PRE>', '</PRE>'
else: _tbopen, _tbclose = '''<pre else: _tbopen, _tbclose = '''<pre
...@@ -533,7 +532,7 @@ class HTTPResponse(BaseResponse): ...@@ -533,7 +532,7 @@ class HTTPResponse(BaseResponse):
et = translate(str(t), nl2sp) et = translate(str(t), nl2sp)
self.setHeader('bobo-exception-type', et) self.setHeader('bobo-exception-type', et)
ev = translate(str(v), nl2sp) ev = translate(str(v), nl2sp)
if find(ev, '<html>') >= 0: if ev.find( '<html>') >= 0:
ev = 'bobo exception' ev = 'bobo exception'
self.setHeader('bobo-exception-value', ev[:255]) self.setHeader('bobo-exception-value', ev[:255])
# Get the tb tail, which is the interesting part: # Get the tb tail, which is the interesting part:
...@@ -590,8 +589,8 @@ class HTTPResponse(BaseResponse): ...@@ -590,8 +589,8 @@ class HTTPResponse(BaseResponse):
'Sorry, a site error occurred.<p>' 'Sorry, a site error occurred.<p>'
+ self._traceback(t, v, tb)), + self._traceback(t, v, tb)),
is_error=1) is_error=1)
elif (lower(strip(b)[:6])=='<html>' or elif b.strip().lower()[:6]=='<html>' or \
lower(strip(b)[:14])=='<!doctype html'): b.strip().lower()[:14]=='<!doctype html':
# error is an HTML document, not just a snippet of html # error is an HTML document, not just a snippet of html
body = self.setBody(b + self._traceback(t, '(see above)', tb), body = self.setBody(b + self._traceback(t, '(see above)', tb),
is_error=1) is_error=1)
...@@ -614,7 +613,7 @@ class HTTPResponse(BaseResponse): ...@@ -614,7 +613,7 @@ class HTTPResponse(BaseResponse):
cookie='Set-Cookie: %s="%s"' % (name, attrs['value']) cookie='Set-Cookie: %s="%s"' % (name, attrs['value'])
for name, v in attrs.items(): for name, v in attrs.items():
name=lower(name) name=name.lower()
if name=='expires': cookie = '%s; Expires=%s' % (cookie,v) if name=='expires': cookie = '%s; Expires=%s' % (cookie,v)
elif name=='domain': cookie = '%s; Domain=%s' % (cookie,v) elif name=='domain': cookie = '%s; Domain=%s' % (cookie,v)
elif name=='path': cookie = '%s; Path=%s' % (cookie,v) elif name=='path': cookie = '%s; Path=%s' % (cookie,v)
...@@ -658,20 +657,20 @@ class HTTPResponse(BaseResponse): ...@@ -658,20 +657,20 @@ class HTTPResponse(BaseResponse):
if headers.has_key('status'): if headers.has_key('status'):
del headers['status'] del headers['status']
for key, val in headers.items(): for key, val in headers.items():
if lower(key)==key: if key.lower()==key:
# only change non-literal header names # only change non-literal header names
key="%s%s" % (upper(key[:1]), key[1:]) key="%s%s" % (key[:1].upper(), key[1:])
start=0 start=0
l=find(key,'-',start) l=key.find('-',start)
while l >= start: while l >= start:
key="%s-%s%s" % (key[:l],upper(key[l+1:l+2]),key[l+2:]) key="%s-%s%s" % (key[:l],key[l+1:l+2].upper(),key[l+2:])
start=l+1 start=l+1
l=find(key,'-',start) l=key.find('-',start)
append("%s: %s" % (key, val)) append("%s: %s" % (key, val))
if self.cookies: if self.cookies:
headersl=headersl+self._cookie_list() headersl=headersl+self._cookie_list()
headersl[len(headersl):]=[self.accumulated_headers, body] headersl[len(headersl):]=[self.accumulated_headers, body]
return join(headersl,'\n') return '\n'.join(headersl)
def write(self,data): def write(self,data):
"""\ """\
......
...@@ -12,11 +12,10 @@ ...@@ -12,11 +12,10 @@
############################################################################## ##############################################################################
__doc__="""Python Object Publisher -- Publish Python objects on web servers __doc__="""Python Object Publisher -- Publish Python objects on web servers
$Id: Publish.py,v 1.154 2001/11/28 15:51:20 matt Exp $""" $Id: Publish.py,v 1.155 2002/01/02 15:56:04 andreasjung Exp $"""
__version__='$Revision: 1.154 $'[11:-2] __version__='$Revision: 1.155 $'[11:-2]
import sys, os import sys, os
from string import lower, atoi, rfind, strip
from Response import Response from Response import Response
from Request import Request from Request import Request
from maybe_lock import allocate_lock from maybe_lock import allocate_lock
...@@ -68,7 +67,7 @@ def publish(request, module_name, after_list, debug=0, ...@@ -68,7 +67,7 @@ def publish(request, module_name, after_list, debug=0,
# First check for "cancel" redirect: # First check for "cancel" redirect:
cancel='' cancel=''
if lower(strip(request_get('SUBMIT','')))=='cancel': if request_get('SUBMIT','').strip().lower()=='cancel':
cancel=request_get('CANCEL_ACTION','') cancel=request_get('CANCEL_ACTION','')
if cancel: raise 'Redirect', cancel if cancel: raise 'Redirect', cancel
...@@ -81,7 +80,7 @@ def publish(request, module_name, after_list, debug=0, ...@@ -81,7 +80,7 @@ def publish(request, module_name, after_list, debug=0,
bobo_before() bobo_before()
# Get a nice clean path list: # Get a nice clean path list:
path=strip(request_get('PATH_INFO')) path=request_get('PATH_INFO').strip()
request['PARENTS']=parents=[object] request['PARENTS']=parents=[object]
......
...@@ -90,18 +90,18 @@ Examples ...@@ -90,18 +90,18 @@ Examples
s s
$Id: Test.py,v 1.38 2001/11/28 15:51:21 matt Exp $ $Id: Test.py,v 1.39 2002/01/02 15:56:04 andreasjung Exp $
''' '''
__version__='$Revision: 1.38 $'[11:-2] __version__='$Revision: 1.39 $'[11:-2]
import sys, traceback, profile, os, getopt, string import sys, traceback, profile, os, getopt
from time import clock from time import clock
repeat_count=100 repeat_count=100
TupleType=type(()) TupleType=type(())
def main(): def main():
import sys, os, getopt, string import sys, os, getopt
global repeat_count global repeat_count
try: try:
...@@ -127,9 +127,9 @@ def main(): ...@@ -127,9 +127,9 @@ def main():
elif opt=='-p': elif opt=='-p':
profile=val profile=val
elif opt=='-r': elif opt=='-r':
repeat_count=string.atoi(val) repeat_count=int(val)
elif opt=='-e': elif opt=='-e':
opt=string.find(val,'=') opt=val.find('=')
if opt <= 0: raise 'Invalid argument to -e', val if opt <= 0: raise 'Invalid argument to -e', val
env[val[:opt]]=val[opt+1:] env[val[:opt]]=val[opt+1:]
...@@ -266,7 +266,7 @@ def publish(script=None,path_info='/', ...@@ -266,7 +266,7 @@ def publish(script=None,path_info='/',
env['SERVER_HOSTNAME']='bobo.server.host' env['SERVER_HOSTNAME']='bobo.server.host'
env['GATEWAY_INTERFACE']='CGI/1.1 ' env['GATEWAY_INTERFACE']='CGI/1.1 '
env['SCRIPT_NAME']=script env['SCRIPT_NAME']=script
p=string.split(path_info,'?') p=path_info.split('?')
if len(p)==1: env['PATH_INFO'] = p[0] if len(p)==1: env['PATH_INFO'] = p[0]
elif len(p)==2: [env['PATH_INFO'], env['QUERY_STRING']]=p elif len(p)==2: [env['PATH_INFO'], env['QUERY_STRING']]=p
else: raise TypeError, '' else: raise TypeError, ''
......
...@@ -20,7 +20,6 @@ information about XML-RPC and Zope. ...@@ -20,7 +20,6 @@ information about XML-RPC and Zope.
""" """
import sys import sys
from string import replace
from HTTPResponse import HTTPResponse from HTTPResponse import HTTPResponse
import xmlrpclib import xmlrpclib
...@@ -47,7 +46,7 @@ def parse_input(data): ...@@ -47,7 +46,7 @@ def parse_input(data):
# ('examples.getStateName', (41,)) # ('examples.getStateName', (41,))
params, method = xmlrpclib.loads(data) params, method = xmlrpclib.loads(data)
# Translate '.' to '/' in meth to represent object traversal. # Translate '.' to '/' in meth to represent object traversal.
method = replace(method, '.', '/') method = method.replace('.', '/')
return method, params return method, params
# See below # See below
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment