Commit f5ca408b authored by Andreas Jung's avatar Andreas Jung

string module calls -> string methods

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