Wrap the requests library to trace it.
482070
def trace_integration(tracer=None):
    """"""
    log.info('Integrated module: {}'.format(MODULE_NAME))

    if tracer is not None:
        # The execution_context tracer should never be None - if it has not
        # been set it returns a no-op tracer. Most code in this library does
        # not handle None being used in the execution context.
        execution_context.set_opencensus_tracer(tracer)

    # Wrap the requests functions
    for func in REQUESTS_WRAP_METHODS:
        requests_func = getattr(requests, func)
        wrapped = wrap_requests(requests_func)
        setattr(requests, requests_func.__name__, wrapped)

    # Wrap Session class
    wrapt.wrap_function_wrapper(
        MODULE_NAME, 'Session.request', wrap_session_request)
1036919
def wrapAppEndpoints(app):
    
    for endpoint, func in app.view_functions.items():
        app.view_functions[endpoint] = wrapHttpEndpoint(func)
633326
def decorate_callable(self, callable_):
        """"""
        @wraps(callable_)
        def decorated(*args, **kwargs):
            # Extract timeout from request itself or use default for ioloop wrapper
            timeout = kwargs.get('timeout')
            return self.call_in_ioloop(callable_, args, kwargs, timeout)

        decorated.__doc__ = '\n\n'.join((
"""Wrapped async call. Will call in ioloop.

This call will block until the original callable has finished running on the ioloop, and
will pass on the return value. If the original callable returns a future, this call will
wait for the future to resolve and return the value or raise the exception that the future
resolves with.

Original Callable Docstring
---------------------------
""",
            textwrap.dedent(decorated.__doc__ or '')))

        return decorated
1231066
def _wrap_functions(self, client):
        

        def wrap(fn):
            def wrapper(*args, **kwargs):
                """Simple wrapper for to catch dead clients."""
                try:
                    return fn(*args, **kwargs)
                except (ConnectionError, TimeoutError):  # TO THE PENALTY BOX!
                    self._penalize_client(client)
                    raise

            return functools.update_wrapper(wrapper, fn)

        for name in dir(client):
            if name.startswith("_"):
                continue
            # Some things aren't wrapped
            if name in ("echo", "execute_command", "parse_response"):
                continue
            obj = getattr(client, name)
            if not callable(obj):
                continue
            log.debug("Wrapping %s", name)
            setattr(client, name, wrap(obj))
1300229
private static Request wrap(final Request req) {
        final AtomicBoolean seen = new AtomicBoolean(false);
        return new Request() {
            @Override
            public Iterable<String> head() throws IOException {
                return req.head();
            }

            @Override
            public InputStream body() throws IOException {
                if (!seen.getAndSet(true)) {
                    throw new IllegalStateException(
                        "It's not allowed to call body() more than once"
                    );
                }
                return req.body();
            }
        };
    }
576304
def request(self, method, uri, headers=None, bodyProducer=None):
        
        if self._parent_trace is None:
            trace = Trace(method)
        else:
            trace = self._parent_trace.child(method)

        if self._endpoint is not None:
            trace.set_endpoint(self._endpoint)

        if headers is None:
            headers = Headers({})

        # These headers are based on the headers used by finagle's tracing
        # http Codec.
        #
        # https://github.com/twitter/finagle/blob/master/finagle-http/
        #
        # Currently not implemented are X-B3-Sampled and X-B3-Flags
        # Tryfer's underlying Trace implementation has no notion of a Sampled
        # trace and I haven't figured out what flags are for.
        headers.setRawHeaders('X-B3-TraceId', [hex_str(trace.trace_id)])
        headers.setRawHeaders('X-B3-SpanId', [hex_str(trace.span_id)])

        if trace.parent_span_id is not None:
            headers.setRawHeaders('X-B3-ParentSpanId',
                                  [hex_str(trace.parent_span_id)])

        # Similar to the headers above we use the annotation 'http.uri' for
        # because that is the standard set forth in the finagle http Codec.
        trace.record(Annotation.string('http.uri', uri))
        trace.record(Annotation.client_send())

        def _finished(resp):
            # TODO: It may be advantageous here to return a wrapped response
            # whose deliverBody can wrap it's protocol and record when the
            # application has finished reading the contents.
            trace.record(Annotation.string(
                'http.responsecode',
                '{0} {1}'.format(resp.code, resp.phrase)))
            trace.record(Annotation.client_recv())
            return resp

        d = self._agent.request(method, uri, headers, bodyProducer)
        d.addBoth(_finished)

        return d
855874
def wrap(error, method, path, params, request, response)

      class << error; attr_accessor :_details; end
      error._details = ErrorDetails.new(method, path, params, request, response)

      error
    end
634823
def wrap_options(self, data, renderer_context):
        ''''''
        request = renderer_context.get("request", None)
        method = request and getattr(request, 'method')
        if method != 'OPTIONS':
            raise WrapperNotApplicable("Request method must be OPTIONS")

        wrapper = self.dict_class()
        wrapper["meta"] = data
        return wrapper
1118618
def request_middleware(api=None):
    """"""
    def decorator(middleware_method):
        apply_to_api = hug.API(api) if api else hug.api.from_object(middleware_method)

        class MiddlewareRouter(object):
            __slots__ = ()

            def process_request(self, request, response):
                return middleware_method(request, response)

        apply_to_api.http.add_middleware(MiddlewareRouter())
        return middleware_method
    return decorator
418728
def wrap_context(func):
    
    @functools.wraps(func)
    def wrapper(self, request, context):
        return func(self, request, LogFieldsContext(context))

    return wrapper
1150819
def wrap(cls, meth):
        '''
        
        '''

        async def inner(*args, **kwargs):
            sock = await meth(*args, **kwargs)
            return cls(sock)

        return inner
1344814
def send_request(req=None, method=None, requires_response=True):
    """"""
    if req is None:
        return functools.partial(send_request, method=method,
                                 requires_response=requires_response)

    @functools.wraps(req)
    def wrapper(self, *args, **kwargs):
        params = req(self, *args, **kwargs)
        _id = self.send(method, params, requires_response)
        return _id
    wrapper._sends = method
    return wrapper
598542
async def route_wrapper(self, route, request, context, request_args,
                            request_kw, *decorator_args, with_context=None,
                            **decorator_kw):
        
        # by default, do nothing, just run the wrapped function
        if with_context:
            resp = route(request, context, *request_args, **request_kw)
        else:
            resp = route(request, *request_args, **request_kw)
        if isawaitable(resp):
            resp = await resp
        return resp
229813
def trace(self, urls=None, **overrides):
        """"""
        if urls is not None:
            overrides['urls'] = urls
        return self.where(accept='TRACE', **overrides)
646213
def _wrap_class(request_handler, validator):
    
    METHODS = ['get', 'post', 'put', 'head', 'options', 'delete', 'patch']
    for name in METHODS:
        method = getattr(request_handler, name)
        setattr(request_handler, name, _auth_required(method, validator))

    return request_handler
1052193
function createRequestWrapper(req) {
        var status,
            statusText,
            responseText;
        try {
            status = req.status;
            statusText = req.statusText;
            responseText = req.responseText;
        } catch (e) {
            status = 0;
            statusText = '';
            responseText = null;
        }
        return {
            status: status,
            statusText: statusText,
            responseText: responseText,
            rawRequest: req
        };
    }
294141
def setup_default_wrappers(self):
        
        # Index
        self._after_calls['index'] = [
            wrappers.wrap_in_dict(self.request),
            wrappers.add_meta(self.request),
            wrappers.add_object_url(self.request),
        ]

        # Show
        self._after_calls['show'] = [
            wrappers.wrap_in_dict(self.request),
            wrappers.add_meta(self.request),
            wrappers.add_object_url(self.request),
        ]

        # Create
        self._after_calls['create'] = [
            wrappers.wrap_in_dict(self.request),
            wrappers.add_meta(self.request),
            wrappers.add_object_url(self.request),
        ]

        # Update
        self._after_calls['update'] = [
            wrappers.wrap_in_dict(self.request),
            wrappers.add_meta(self.request),
            wrappers.add_object_url(self.request),
        ]

        # Replace
        self._after_calls['replace'] = [
            wrappers.wrap_in_dict(self.request),
            wrappers.add_meta(self.request),
            wrappers.add_object_url(self.request),
        ]

        # Privacy wrappers
        if self._auth_enabled:
            for meth in ('index', 'show', 'create', 'update', 'replace'):
                self._after_calls[meth] += [
                    wrappers.apply_privacy(self.request),
                ]
            for meth in ('update', 'replace', 'update_many'):
                self._before_calls[meth] += [
                    wrappers.apply_request_privacy(
                        self.Model, self._json_params),
                ]