Exemplo n.º 1
0
def test_expand_items():
    d = {
        'key1': ('value1-1', 'value1-2'),
        'key2': 'value2',
    }
    items = multipart.expand_items(d)

    assert ('key1', 'value1-1') in items
    assert ('key1', 'value1-2') in items
    assert ('key2', 'value2') in items
Exemplo n.º 2
0
    def request(self, url, method, body=None, headers=None):
        if not isinstance(url, basestring):
            raise TypeError, 'Bolacha.request, parameter url must be ' \
                  'a string. Got %s' % repr(url)

        if not isinstance(method, basestring):
            raise TypeError, 'Bolacha.request, parameter method must be ' \
                  'a string. Got %s' % repr(method)

        if method not in HTTP_METHODS:
            raise TypeError, 'Bolacha.request, parameter method must be ' \
                  'a valid HTTP method. Got %s. %s' % (method,
                                                        RFC_LOCATION)

        if body is None:
            body = ''

        if not isinstance(body, (basestring, dict)):
            raise TypeError, 'Bolacha.request, parameter body must be ' \
                  'a string or dict. Got %s.' % (repr(body))

        is_urlencoded = False

        body_has_file = isinstance(body, dict) and any([is_file(value)
                                                       for key,value
                                                       in expand_items(body)])

        if isinstance(body, dict):
            if body_has_file:
                rbody = encode_multipart(BOUNDARY, body)
            else:
                rbody = urlencode(body, doseq=True)
                is_urlencoded = True
        else:
            rbody = body

        if headers is None:
            headers = {}

        if not isinstance(headers, dict):
            raise TypeError, 'Bolacha.request, parameter headers must be ' \
                  'a dict or NoneType. Got %s' % repr(headers)

        rheaders = self.headers.copy()
        rheaders.update(headers)

        if self.persistent:
            if 'set-cookie' in self.headers:
                rheaders['Cookie'] = self.headers['set-cookie']

        if 'set-cookie' in rheaders:
            del rheaders['set-cookie']

        if is_urlencoded and not 'Content-type' in rheaders:
            rheaders['Content-type'] = 'application/x-www-form-urlencoded'
        elif body_has_file:
            rheaders['Content-type'] = 'multipart/form-data; boundary=%s' % BOUNDARY
            rheaders['content-length'] = '%d' % len(rbody)

        response, content = self.http.request(url, method, rbody, rheaders)

        if self.persistent and 'set-cookie' in response:
            self.headers['set-cookie'] = response['set-cookie']

        if not self.persistent:
            if 'connection' in response:
                self.headers['connection'] = response['connection']

        return response, content