def request()

in clay/http.py [0:0]


def request(method, uri, headers={}, data=None, timeout=None):
    '''
    Convenience wrapper around urllib2. Returns a Response namedtuple with 'status', 'headers', and 'data' fields

    It is highly recommended to set the 'timeout' parameter to something sensible
    '''
    req = Request(uri, headers=headers, data=data, method=method)
    if not req.get_type() in ('http', 'https'):
        raise urllib2.URLError('Only http and https protocols are supported')

    try:
        with contextlib.closing(urllib2.urlopen(req, timeout=timeout)) as resp:
            resp = Response(
                status=resp.getcode(),
                headers=resp.headers,
                data=resp.read())
            log.debug('%i %s %s' % (resp.status, method, uri))
    except urllib2.HTTPError as e:
        # if there was a connection error, the underlying fd might be None and we can't read it
        if e.fp is not None:
            resp = Response(
                status=e.getcode(),
                headers=e.hdrs,
                data=e.read())
        else:
            resp = Response(
                status=e.getcode(),
                headers=e.hdrs,
                data=None)
        log.warning('%i %s %s' % (resp.status, method, uri))

    return resp