def renderHTTP(self, request):
     response = http.StatusResponse(
         responsecode.SERVICE_UNAVAILABLE,
         responsecode.RESPONSES[responsecode.SERVICE_UNAVAILABLE])
     if self.retryAfter > 0:
         response.headers.setHeader("Retry-After",
                                    time.time() + self.retryAfter)
     raise HTTPError(response)
Beispiel #2
0
 def renderHTTP(self, request):
     linked_to = (yield self.linkedResource(request))
     if linked_to:
         returnValue(linked_to)
     else:
         returnValue(
             http.StatusResponse(
                 responsecode.OK, "Link resource with missing target: %s" %
                 (self.linkURL, )))
Beispiel #3
0
def parsePOSTData(request,
                  maxMem=100 * 1024,
                  maxFields=1024,
                  maxSize=10 * 1024 * 1024):
    """
    Parse data of a POST request.

    @param request: the request to parse.
    @type request: L{txweb2.http.Request}.
    @param maxMem: maximum memory used during the parsing of the data.
    @type maxMem: C{int}
    @param maxFields: maximum number of form fields allowed.
    @type maxFields: C{int}
    @param maxSize: maximum size of file upload allowed.
    @type maxSize: C{int}

    @return: a deferred that will fire when the parsing is done. The deferred
        itself doesn't hold a return value, the request is modified directly.
    @rtype: C{defer.Deferred}
    """
    if request.stream.length == 0:
        return defer.succeed(None)

    ctype = request.headers.getHeader('content-type')

    if ctype is None:
        return defer.succeed(None)

    def updateArgs(data):
        args = data
        request.args.update(args)

    def updateArgsAndFiles(data):
        args, files = data
        request.args.update(args)
        request.files.update(files)

    def error(f):
        f.trap(fileupload.MimeFormatError)
        raise http.HTTPError(
            http.StatusResponse(responsecode.BAD_REQUEST, str(f.value)))

    if (ctype.mediaType == 'application'
            and ctype.mediaSubtype == 'x-www-form-urlencoded'):
        d = fileupload.parse_urlencoded(request.stream)
        d.addCallbacks(updateArgs, error)
        return d
    elif (ctype.mediaType == 'multipart'
          and ctype.mediaSubtype == 'form-data'):
        boundary = ctype.params.get('boundary')
        if boundary is None:
            return defer.fail(
                http.HTTPError(
                    http.StatusResponse(
                        responsecode.BAD_REQUEST,
                        "Boundary not specified in Content-Type.")))
        d = fileupload.parseMultipartFormData(request.stream, boundary, maxMem,
                                              maxFields, maxSize)
        d.addCallbacks(updateArgsAndFiles, error)
        return d
    else:
        return defer.fail(
            http.HTTPError(
                http.StatusResponse(
                    responsecode.BAD_REQUEST, "Invalid content-type: %s/%s" %
                    (ctype.mediaType, ctype.mediaSubtype))))
Beispiel #4
0
    def locateResource(self, url):
        """
        Looks up the resource with the given URL.
        @param uri: The URL of the desired resource.
        @return: a L{Deferred} resulting in the L{IResource} at the
            given URL or C{None} if no such resource can be located.
        @raise HTTPError: If C{url} is not a URL on the site that this
            request is being applied to.  The contained response will
            have a status code of L{responsecode.BAD_GATEWAY}.
        @raise HTTPError: If C{url} contains a query or fragment.
            The contained response will have a status code of
            L{responsecode.BAD_REQUEST}.
        """
        if url is None:
            return defer.succeed(None)

        #
        # Parse the URL
        #
        (_ignore_scheme, _ignore_host, path, query, fragment) = urlsplit(url)

        if query or fragment:
            raise http.HTTPError(
                http.StatusResponse(
                    responsecode.BAD_REQUEST,
                    "URL may not contain a query or fragment: %s" % (url, )))

        # Look for cached value
        cached = self._resourcesByURL.get(path, None)
        if cached is not None:
            return defer.succeed(cached)

        segments = unquote(path).split("/")
        assert segments[0] == "", "URL path didn't begin with '/': %s" % (
            path, )

        # Walk the segments up to see if we can find a cached resource to start from
        preSegments = segments[:-1]
        postSegments = segments[-1:]
        cachedParent = None
        while (len(preSegments)):
            parentPath = "/".join(preSegments) + "/"
            cachedParent = self._resourcesByURL.get(parentPath, None)
            if cachedParent is not None:
                break
            else:
                postSegments.insert(0, preSegments.pop())

        if cachedParent is None:
            cachedParent = self.site.resource
            postSegments = segments[1:]

        def notFound(f):
            f.trap(http.HTTPError)
            if f.value.response.code != responsecode.NOT_FOUND:
                return f
            return None

        d = defer.maybeDeferred(self._getChild,
                                None,
                                cachedParent,
                                postSegments,
                                updatepaths=False)
        d.addCallback(self._rememberResource, path)
        d.addErrback(notFound)
        return d
Beispiel #5
0
 def error(f):
     f.trap(fileupload.MimeFormatError)
     raise http.HTTPError(
         http.StatusResponse(responsecode.BAD_REQUEST, str(f.value)))