Пример #1
0
def parse_multipart_headers(iterable):
    """Parses multipart headers from an iterable that yields lines (including
    the trailing newline symbol.  The iterable has to be newline terminated:

    >>> parse_multipart_headers(['Foo: Bar\r\n', 'Test: Blub\r\n',
    ...                          '\r\n', 'More data'])
    Headers([('Foo', 'Bar'), ('Test', 'Blub')])

    :param iterable: iterable of strings that are newline terminated
    """
    result = []
    for line in iterable:
        line, line_terminated = _line_parse(line)
        if not line_terminated:
            raise ValueError('unexpected end of line in multipart header')
        if not line:
            break
        elif line[0] in ' \t' and result:
            key, value = result[-1]
            result[-1] = (key, value + '\n ' + line[1:])
        else:
            parts = line.split(':', 1)
            if len(parts) == 2:
                result.append((parts[0].strip(), parts[1].strip()))

    # we link the list to the headers, no need to create a copy, the
    # list was not shared anyways.
    return Headers.linked(result)
Пример #2
0
def parse_multipart_headers(iterable):
    """Parses multipart headers from an iterable that yields lines (including
    the trailing newline symbol).  The iterable has to be newline terminated.

    The iterable will stop at the line where the headers ended so it can be
    further consumed.

    :param iterable: iterable of strings that are newline terminated
    """
    result = []
    for line in iterable:
        line, line_terminated = _line_parse(line)
        if not line_terminated:
            raise ValueError('unexpected end of line in multipart header')
        if not line:
            break
        elif line[0] in ' \t' and result:
            key, value = result[-1]
            result[-1] = (key, value + '\n ' + line[1:])
        else:
            parts = line.split(':', 1)
            if len(parts) == 2:
                result.append((parts[0].strip(), parts[1].strip()))

    # we link the list to the headers, no need to create a copy, the
    # list was not shared anyways.
    return Headers.linked(result)
Пример #3
0
def parse_multipart_headers(iterable):
    """Parses multipart headers from an iterable that yields lines (including
    the trailing newline symbol.  The iterable has to be newline terminated:

    >>> parse_multipart_headers(['Foo: Bar\r\n', 'Test: Blub\r\n',
    ...                          '\r\n', 'More data'])
    Headers([('Foo', 'Bar'), ('Test', 'Blub')])

    :param iterable: iterable of strings that are newline terminated
    """
    result = []
    for line in iterable:
        line, line_terminated = _line_parse(line)
        if not line_terminated:
            raise ValueError('unexpected end of line in multipart header')
        if not line:
            break
        elif line[0] in ' \t' and result:
            key, value = result[-1]
            result[-1] = (key, value + '\n ' + line[1:])
        else:
            parts = line.split(':', 1)
            if len(parts) == 2:
                result.append((parts[0].strip(), parts[1].strip()))

    # we link the list to the headers, no need to create a copy, the
    # list was not shared anyways.
    return Headers.linked(result)
Пример #4
0
def lock(path):
    path = normpath(path)
    obj = get_object(path)
    token = str(uuid.uuid1())

    if repository.is_locked(obj):
        if not repository.can_unlock(obj):
            return "", 423, {}
        else:
            headers = {"Lock-Token": "urn:uuid:" + token}
            return "TODO", HTTP_OK, headers

    token = repository.lock(obj)

    xml = (
        """<?xml version="1.0" encoding="utf-8" ?>
<D:prop xmlns:D="DAV:">
    <D:lockdiscovery>
        <D:activelock>
            <D:lockscope><D:exclusive/></D:lockscope>
            <D:locktype><D:write/></D:locktype>
            <D:depth>0</D:depth>
            <D:timeout>Second-179</D:timeout>
            <D:owner>flora</D:owner>
            <D:locktoken>
                <D:href>opaquelocktoken:%s</D:href>
            </D:locktoken>
        </D:activelock>
    </D:lockdiscovery>
</D:prop>"""
        % token
    )

    hlist = [("Content-Type", "text/xml"), ("Lock-Token", "<urn:uuid:%s>" % token)]

    return Response(xml, headers=Headers.linked(hlist))  # , status ='423 Locked'
Пример #5
0
def lock(path):
    path = normpath(path)
    obj = get_object(path)
    token = str(uuid.uuid1())

    if repository.is_locked(obj):
        if not repository.can_unlock(obj):
            return "", 423, {}
        else:
            headers = {"Lock-Token": "urn:uuid:" + token}
            return "TODO", HTTP_OK, headers

    token = repository.lock(obj)

    xml = (
        """<?xml version="1.0" encoding="utf-8" ?>
<D:prop xmlns:D="DAV:">
    <D:lockdiscovery>
        <D:activelock>
            <D:lockscope><D:exclusive/></D:lockscope>
            <D:locktype><D:write/></D:locktype>
            <D:depth>0</D:depth>
            <D:timeout>Second-179</D:timeout>
            <D:owner>flora</D:owner>
            <D:locktoken>
                <D:href>opaquelocktoken:%s</D:href>
            </D:locktoken>
        </D:activelock>
    </D:lockdiscovery>
</D:prop>"""
        % token
    )

    hlist = [("Content-Type", "text/xml"), ("Lock-Token", "<urn:uuid:%s>" % token)]

    return Response(xml, headers=Headers.linked(hlist))  # , status ='423 Locked'
Пример #6
0
 def fixing_start_response(status, headers, exc_info=None):
     self.fix_headers(environ, Headers.linked(headers), status)
     return start_response(status, headers, exc_info)
Пример #7
0
 def fixing_start_response(status, headers, exc_info=None):
     self.fix_headers(environ, Headers.linked(headers), status)
     return start_response(status, headers, exc_info)
Пример #8
0
    def open(self, *args, **kwargs):
        """Takes the same arguments as the :class:`EnvironBuilder` class with
        some additions:  You can provide a :class:`EnvironBuilder` or a WSGI
        environment as only argument instead of the :class:`EnvironBuilder`
        arguments and two optional keyword arguments (`as_tuple`, `buffered`)
        that change the type of the return value or the way the application is
        executed.

        .. versionchanged:: 0.5
           If a dict is provided as file in the dict for the `data` parameter
           the content type has to be called `content_type` now instead of
           `mimetype`.  This change was made for consistency with
           :class:`werkzeug.FileWrapper`.

            The `follow_redirects` parameter was added to :func:`open`.

        Additional parameters:

        :param as_tuple: Returns a tuple in the form ``(environ, result)``
        :param buffered: Set this to True to buffer the application run.
                         This will automatically close the application for
                         you as well.
        :param follow_redirects: Set this to True if the `Client` should
                                 follow HTTP redirects.
        """
        as_tuple = kwargs.pop('as_tuple', False)
        buffered = kwargs.pop('buffered', False)
        follow_redirects = kwargs.pop('follow_redirects', False)
        environ = None
        if not kwargs and len(args) == 1:
            if isinstance(args[0], EnvironBuilder):
                environ = args[0].get_environ()
            elif isinstance(args[0], dict):
                environ = args[0]
        if environ is None:
            builder = EnvironBuilder(*args, **kwargs)
            try:
                environ = builder.get_environ()
            finally:
                builder.close()

        response = self.run_wsgi_app(environ, buffered=buffered)

        # handle redirects
        redirect_chain = []
        while 1:
            status_code = int(response[1].split(None, 1)[0])
            if status_code not in (301, 302, 303, 305, 307) \
               or not follow_redirects:
                break
            new_location = Headers.linked(response[2])['location']
            new_redirect_entry = (new_location, status_code)
            if new_redirect_entry in redirect_chain:
                raise ClientRedirectError('loop detected')
            redirect_chain.append(new_redirect_entry)
            environ, response = self.resolve_redirect(response, new_location,
                                                      environ, buffered=buffered)

        if self.response_wrapper is not None:
            response = self.response_wrapper(*response)
        if as_tuple:
            return environ, response
        return response
Пример #9
0
    def open(self, *args, **kwargs):
        """Takes the same arguments as the :class:`EnvironBuilder` class with
        some additions:  You can provide a :class:`EnvironBuilder` or a WSGI
        environment as only argument instead of the :class:`EnvironBuilder`
        arguments and two optional keyword arguments (`as_tuple`, `buffered`)
        that change the type of the return value or the way the application is
        executed.

        .. versionchanged:: 0.5
           If a dict is provided as file in the dict for the `data` parameter
           the content type has to be called `content_type` now instead of
           `mimetype`.  This change was made for consistency with
           :class:`werkzeug.FileWrapper`.

            The `follow_redirects` parameter was added to :func:`open`.

        Additional parameters:

        :param as_tuple: Returns a tuple in the form ``(environ, result)``
        :param buffered: Set this to True to buffer the application run.
                         This will automatically close the application for
                         you as well.
        :param follow_redirects: Set this to True if the `Client` should
                                 follow HTTP redirects.
        """
        as_tuple = kwargs.pop('as_tuple', False)
        buffered = kwargs.pop('buffered', False)
        follow_redirects = kwargs.pop('follow_redirects', False)
        environ = None
        if not kwargs and len(args) == 1:
            if isinstance(args[0], EnvironBuilder):
                environ = args[0].get_environ()
            elif isinstance(args[0], dict):
                environ = args[0]
        if environ is None:
            builder = EnvironBuilder(*args, **kwargs)
            try:
                environ = builder.get_environ()
            finally:
                builder.close()

        response = self.run_wsgi_app(environ, buffered=buffered)

        # handle redirects
        redirect_chain = []
        while 1:
            status_code = int(response[1].split(None, 1)[0])
            if status_code not in (301, 302, 303, 305, 307) \
               or not follow_redirects:
                break
            new_location = Headers.linked(response[2])['location']
            new_redirect_entry = (new_location, status_code)
            if new_redirect_entry in redirect_chain:
                raise ClientRedirectError('loop detected')
            redirect_chain.append(new_redirect_entry)
            environ, response = self.resolve_redirect(response,
                                                      new_location,
                                                      environ,
                                                      buffered=buffered)

        if self.response_wrapper is not None:
            response = self.response_wrapper(*response)
        if as_tuple:
            return environ, response
        return response