1
# -*- test-case-name: twisted.web2.test.test_util -*-
3
# Copyright (c) 2005 Apple Computer, Inc. All rights reserved.
5
# Permission is hereby granted, free of charge, to any person obtaining a copy
6
# of this software and associated documentation files (the "Software"), to deal
7
# in the Software without restriction, including without limitation the rights
8
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
# copies of the Software, and to permit persons to whom the Software is
10
# furnished to do so, subject to the following conditions:
12
# The above copyright notice and this permission notice shall be included in all
13
# copies or substantial portions of the Software.
15
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23
# DRI: Wilfredo Sanchez, wsanchez@apple.com
29
This API is considered private to static.py and is therefore subject to
44
from urlparse import urlsplit, urlunsplit
45
import posixpath # Careful; this module is not documented as public API
47
from twisted.python import log
48
from twisted.python.failure import Failure
49
from twisted.internet.defer import succeed
50
from twisted.web2.stream import readStream
52
from twisted.web2.dav import davxml
55
# Reading request body
58
def allDataFromStream(stream, filter=None):
61
if not data: return None
62
result = "".join([str(x) for x in data])
67
return readStream(stream, data.append).addCallback(gotAllData)
69
def davXMLFromStream(stream):
71
# This reads the request body into a string and then parses it.
72
# A better solution would parse directly and incrementally from the
79
return davxml.WebDAVDocument.fromString(xml)
81
log.err("Bad XML:\n%s" % (xml,))
83
return allDataFromStream(stream, parse)
85
def noDataFromStream(stream):
87
if data: raise ValueError("Stream contains unexpected data.")
88
return readStream(stream, gotData)
94
def normalizeURL(url):
98
@return: the normalized representation of C{url}. The returned URL will
99
never contain a trailing C{"/"}; it is up to the caller to determine
100
whether the resource referred to by the URL is a collection and add a
101
trailing C{"/"} if so.
104
# For some silly reason, posixpath.normpath doesn't clean up '//' at the
105
# start of a filename, so let's clean it up here.
109
if char != "/": break
111
path = path[count-1:]
115
(scheme, host, path, query, fragment) = urlsplit(cleanup(url))
117
path = cleanup(posixpath.normpath(urllib.unquote(path)))
119
return urlunsplit((scheme, host, urllib.quote(path), query, fragment))
123
Appends URLs in series.
124
@param urls: URLs to join.
125
@return: the normalized URL formed by combining each URL in C{urls}. The
126
returned URL will contain a trailing C{"/"} if and only if the last
127
given URL contains a trailing C{"/"}.
129
if len(urls) > 0 and len(urls[-1]) > 0 and urls[-1][-1] == "/":
134
url = normalizeURL("/".join([url for url in urls]))
138
return url + trailing
140
def parentForURL(url):
142
Extracts the URL of the containing collection resource for the resource
143
corresponding to a given URL.
144
@param url: an absolute (server-relative is OK) URL.
145
@return: the normalized URL of the collection resource containing the
146
resource corresponding to C{url}. The returned URL will always contain
149
(scheme, host, path, query, fragment) = urlsplit(normalizeURL(url))
151
index = path.rfind("/")
159
raise ValueError("Invalid URL: %s" % (url,))
161
path = path[:index] + "/"
163
return urlunsplit((scheme, host, path, query, fragment))
169
def unimplemented(obj):
171
Throw an exception signifying that the current method is unimplemented
172
and should not have been invoked.
175
caller = inspect.getouterframes(inspect.currentframe())[1][3]
176
raise NotImplementedError("Method %s is unimplemented in subclass %s" % (caller, obj.__class__))
178
def bindMethods(module, clazz, prefixes=("preconditions_", "http_", "report_")):
180
Binds all functions in the given module (as defined by that module's
181
C{__all__} attribute) which start with any of the given prefixes as methods
183
@param module: the module in which to search for functions.
184
@param clazz: the class to bind found functions to as methods.
185
@param prefixes: a sequence of prefixes to match found functions against.
187
for submodule_name in module.__all__:
189
__import__(module.__name__ + "." + submodule_name)
191
log.err("Unable to import module %s" % (module.__name__ + "." + submodule_name,))
192
Failure().raiseException()
193
submodule = getattr(module, submodule_name)
194
for method_name in submodule.__all__:
195
for prefix in prefixes:
196
if method_name.startswith(prefix):
197
method = getattr(submodule, method_name)
198
setattr(clazz, method_name, method)