summaryrefslogtreecommitdiff
path: root/paste/wsgilib.py
diff options
context:
space:
mode:
authorianb <devnull@localhost>2005-12-18 21:19:02 +0000
committerianb <devnull@localhost>2005-12-18 21:19:02 +0000
commit79320015c183266927dd776f075189752d20fa3f (patch)
tree9abc12d5417d94e20a5e96f5325bba302306e221 /paste/wsgilib.py
parent996f4fbc2119a6ff05aeb1efa55d4f3c58d45313 (diff)
downloadpaste-79320015c183266927dd776f075189752d20fa3f.tar.gz
Added -W option to tests, which will turn warnings into errors (warnings haven't actually been removed yet, though). Split response and fileapp from wsgilib. Some portions of wsgilib may still move to response module, this is just the first cut
Diffstat (limited to 'paste/wsgilib.py')
-rw-r--r--paste/wsgilib.py232
1 files changed, 17 insertions, 215 deletions
diff --git a/paste/wsgilib.py b/paste/wsgilib.py
index 933d692..8b0cf67 100644
--- a/paste/wsgilib.py
+++ b/paste/wsgilib.py
@@ -5,9 +5,12 @@
A module of many disparate routines.
"""
-# functions which moved to paste.request
+# functions which moved to paste.request and paste.response
+# Deprecated around 15 Dec 2005
from request import get_cookies, parse_querystring, parse_formvars
from request import construct_url, path_info_split, path_info_pop
+from response import HeaderDict, has_header, header_value, remove_header
+from response import error_body_response, error_response, error_response_app
from Cookie import SimpleCookie
from cStringIO import StringIO
@@ -272,160 +275,12 @@ def dump_environ(environ,start_response):
start_response("200 OK",headers)
return [output]
-def error_body_response(error_code, message, __warn=True):
- """
- Returns a standard HTML response page for an HTTP error.
- """
- if __warn:
- warnings.warn(
- 'wsgilib.error_body_response is deprecated; use the '
- 'wsgi_application method on an HTTPException object '
- 'instead', DeprecationWarning, 1)
- return '''\
-<html>
- <head>
- <title>%(error_code)s</title>
- </head>
- <body>
- <h1>%(error_code)s</h1>
- %(message)s
- </body>
-</html>''' % {
- 'error_code': error_code,
- 'message': message,
- }
-
-def error_response(environ, error_code, message,
- debug_message=None, __warn=True):
- """
- Returns the status, headers, and body of an error response.
-
- Use like::
-
- status, headers, body = wsgilib.error_response(
- '301 Moved Permanently', 'Moved to <a href="%s">%s</a>'
- % (url, url))
- start_response(status, headers)
- return [body]
- """
- if __warn:
- warnings.warn(
- 'wsgilib.error_response is deprecated; use the '
- 'wsgi_application method on an HTTPException object '
- 'instead', DeprecationWarning, 1)
- if debug_message and environ.get('paste.config', {}).get('debug'):
- message += '\n\n<!-- %s -->' % debug_message
- body = error_body_response(error_code, message, __warn=False)
- headers = [('content-type', 'text/html'),
- ('content-length', str(len(body)))]
- return error_code, headers, body
-
-def error_response_app(error_code, message, debug_message=None,
- __warn=True):
- """
- An application that emits the given error response.
- """
- if __warn:
- warnings.warn(
- 'wsgilib.error_response_app is deprecated; use the '
- 'wsgi_application method on an HTTPException object '
- 'instead', DeprecationWarning, 1)
- def application(environ, start_response):
- status, headers, body = error_response(
- environ, error_code, message,
- debug_message=debug_message, __warn=False)
- start_response(status, headers)
- return [body]
- return application
-
def send_file(filename):
- """
- Returns an application that will send the file at the given
- filename. Adds a mime type based on ``mimetypes.guess_type()``.
- """
- # @@: Should test things like last-modified, if-modified-since,
- # etc.
-
- def application(environ, start_response):
- type, encoding = mimetypes.guess_type(filename)
- # @@: I don't know what to do with the encoding.
- if not type:
- type = 'application/octet-stream'
- size = os.stat(filename).st_size
- try:
- file = open(filename, 'rb')
- except (IOError, OSError), e:
- status, headers, body = error_response(
- '403 Forbidden',
- 'You are not permitted to view this file (%s)' % e)
- start_response(status, headers)
- return [body]
- start_response('200 OK',
- [('content-type', type),
- ('content-length', str(size))])
- return _FileIter(file)
-
- return application
-
-class _FileIter:
-
- def __init__(self, fp, blocksize=4096):
- self.file = fp
- self.blocksize = blocksize
-
- def __iter__(self):
- return self
-
- def next(self):
- data = self.file.read(self.blocksize)
- if not data:
- raise StopIteration
- return data
-
- def close(self):
- self.file.close()
-
-def has_header(headers, name):
- """
- Is header named ``name`` present in headers?
- """
- name = name.lower()
- for header, value in headers:
- if header.lower() == name:
- return True
- return False
-
-def header_value(headers, name):
- """
- Returns the header's value, or None if no such header. If a
- header appears more than once, all the values of the headers
- are joined with ','
- """
- name = name.lower()
- result = [value for header, value in headers
- if header.lower() == name]
- if result:
- return ','.join(result)
- else:
- return None
-
-def remove_header(headers, name):
- """
- Removes the named header from the list of headers. Returns the
- value of that header, or None if no header found. If multiple
- headers are found, only the last one is returned.
- """
- name = name.lower()
- i = 0
- result = None
- while i < len(headers):
- if headers[i][0].lower() == name:
- result = headers[i][1]
- del headers[i]
- continue
- i += 1
- return result
-
+ warnings.warn(
+ "wsgilib.send_file has been moved to paste.fileapp.FileApp",
+ DeprecationWarning, 2)
+ import fileapp
+ return fileapp.FileApp(filename)
def capture_output(environ, start_response, application):
"""
@@ -516,69 +371,16 @@ def intercept_output(environ, application):
data.append(output.getvalue())
return data
-class ResponseHeaderDict(dict):
-
- """
- This represents response headers. It handles the normal case
- of headers as a dictionary, with case-insensitive keys.
+## Deprecation warning wrapper:
- Also there is an ``.add(key, value)`` method, which sets the key,
- or adds the value to the current value (turning it into a list if
- necessary).
+class ResponseHeaderDict(HeaderDict):
- For passing to WSGI there is a ``.headerdict()`` method which is
- like ``.items()`` but unpacks those value lists. It also handles
- encoding -- all headers are encoded in ASCII (if they are
- unicode).
-
- @@: Should that be ISO-8859-1 or UTF-8? I'm not sure what the
- spec says.
- """
-
- def __getitem__(self, key):
- return dict.__getitem__(self, self.normalize(key))
-
- def __setitem__(self, key, value):
- dict.__setitem__(self, self.normalize(key), value)
-
- def __delitem__(self, key):
- dict.__delitem__(self, self.normalize(key))
-
- def __contains__(self, key):
- return dict.__contains__(self, self.normalize(key))
-
- has_key = __contains__
-
- def pop(self, key):
- return dict.pop(self, self.normalize(key))
-
- def update(self, other):
- for key in other:
- self[self.normalize(key)] = other[key]
-
- def normalize(self, key):
- return str(key).lower().strip()
-
- def add(self, key, value):
- key = self.normalize(key)
- if key in self:
- if isinstance(self[key], list):
- self[key].append(value)
- else:
- self[key] = [self[key], value]
- else:
- self[key] = value
-
- def headeritems(self):
- result = []
- for key in self:
- if isinstance(self[key], list):
- for v in self[key]:
- result.append((key, str(v)))
- else:
- result.append((key, str(self[key])))
- return result
-
+ def __init__(self, *args, **kw):
+ warnings.warn(
+ "The class wsgilib.ResponseHeaderDict has been moved "
+ "to paste.response.ResponseHeaderDict",
+ DeprecationWarning, 2)
+ HeaderDict.__init__(self, *args, **kw)
def _warn_deprecated(new_func):
new_name = new_func.func_name