wrap a WSGI-style function to a HTTPRequest event handler
544906
def statichttp(container = None):
    ""
    def decorator(func):
        @functools.wraps(func)
        def handler(event):
            return _handler(container, event, func)
        if hasattr(func, '__self__'):
            handler.__self__ = func.__self__
        return handler
    return decorator
1315157
function(req, res) {
            return function(err) {
                err = err || new Error('wsFinalHandler error');
                err.msg = req.body;
                var code = json_rpc.ERROR_CODES.methodNotFound;
                var error = json_rpc.newSysError(req.body, code,
                                                 'Method not found', err);
                var response = JSON.stringify(json_rpc.reply(error));
                $._.$.log && $._.$.log.trace(response);
                res.send(response);
            };
        }
503770
def get_wsgi_request_object(curr_request, method, url, headers, body):
    '''
        
    '''
    x_headers = headers_to_include_from_request(curr_request)
    method, t_headers = pre_process_method_headers(method, headers)

    # Add default content type.
    if "CONTENT_TYPE" not in t_headers:
        t_headers.update({"CONTENT_TYPE": _settings.DEFAULT_CONTENT_TYPE})

    # Override existing batch requests headers with the new headers passed for this request.
    x_headers.update(t_headers)

    content_type = x_headers.get("CONTENT_TYPE", _settings.DEFAULT_CONTENT_TYPE)

    # Get hold of request factory to construct the request.
    _request_factory = BatchRequestFactory()
    _request_provider = getattr(_request_factory, method)

    secure = _settings.USE_HTTPS

    request = _request_provider(url, data=body, secure=secure,
                                content_type=content_type, **x_headers)

    return request
302179
def sanitize_http_wsgi_env(client, event):
    
    try:
        env = event["context"]["request"]["env"]
        event["context"]["request"]["env"] = varmap(_sanitize, env)
    except (KeyError, TypeError):
        pass
    return event
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
1112333
def wrap_requests(requests_func):
    """"""
    def call(url, *args, **kwargs):
        blacklist_hostnames = execution_context.get_opencensus_attr(
            'blacklist_hostnames')
        parsed_url = urlparse(url)
        if parsed_url.port is None:
            dest_url = parsed_url.hostname
        else:
            dest_url = '{}:{}'.format(parsed_url.hostname, parsed_url.port)
        if utils.disable_tracing_hostname(dest_url, blacklist_hostnames):
            return requests_func(url, *args, **kwargs)

        _tracer = execution_context.get_opencensus_tracer()
        _span = _tracer.start_span()
        _span.name = '[requests]{}'.format(requests_func.__name__)
        _span.span_kind = span_module.SpanKind.CLIENT

        # Add the requests url to attributes
        _tracer.add_attribute_to_current_span(HTTP_URL, url)

        result = requests_func(url, *args, **kwargs)

        # Add the status code to attributes
        _tracer.add_attribute_to_current_span(
            HTTP_STATUS_CODE, str(result.status_code))

        _tracer.end_span()
        return result

    return call
34289
def handle_one_request(self):
        """Copy of WSGIRequestHandler, but with different ServerHandler"""

        self.raw_requestline = self.rfile.readline(65537)
        if len(self.raw_requestline) > 65536:
            self.requestline = ''
            self.request_version = ''
            self.command = ''
            self.send_error(414)
            return

        if not self.parse_request():  # An error code has been sent, just exit
            return

        handler = ServerHandler(
            self.rfile, self.wfile, self.get_stderr(), self.get_environ()
        )
        handler.request_handler = self      # backpointer for logging
        handler.run(self.server.get_app())
1227838
def jsonp(func):
    

    @functools.wraps(func)
    def decorated_view(*args, **kwargs):
        callback = request.args.get('callback', None)
        if callback:
            data = str(func(*args, **kwargs))
            content = str(callback) + '(' + data + ')'
            mimetype = 'application/javascript'
            return current_app.response_class(content, mimetype=mimetype)
        else:
            return func(*args, **kwargs)
    return decorated_view
280974
def request(self, request_type):
        '''  '''

        def _handler(func):
            self._handlers[request_type] = func
            return func

        return _handler
1019604
def request(func=None, timeout=600):
    
    if func is None:
        return partial(request, timeout=timeout)

    @wraps(func)
    def wrapper(self, *args, **kwargs):
        params = func(self, *args, **kwargs)
        self = params.pop('self', None)
        entity = params.pop('entity', None)
        app_name = params.pop('app_name', None)
        request_id = unique_hex()
        params['request_id'] = request_id
        future = self._send_request(app_name, endpoint=func.__name__, entity=entity, params=params, timeout=timeout)
        return future

    wrapper.is_request = True
    return wrapper
159554
def apize_raw(url, method='GET'):
	
	def decorator(func):
		def wrapper(*args, **kwargs):
			elem = func(*args, **kwargs)

			if type(elem) is not dict:
				raise BadReturnVarType(func.__name__)

			response = send_request(url, method, 
				elem.get('data', {}),
				elem.get('args', {}),
				elem.get('params', {}),
				elem.get('headers', {}),
				elem.get('cookies', {}),
				elem.get('timeout', 8),
				elem.get('is_json', False),
				elem.get('verify_cert', True)
			)

			return response
		return wrapper

	return decorator
468578
def execute(self, request, *args, **path_args):
        # type: (BaseHttpRequest, tuple, Dict[Any]) -> Any
        
        binding = self.binding
        if binding:
            # Provide binding as decorators are executed prior to binding
            return self.callback(binding, request, *args, **path_args)
        else:
            return self.callback(request, *args, **path_args)
776646
def get_handler(self, *args, **options):
        
        handler = get_internal_wsgi_application()
        from django.contrib.staticfiles.handlers import StaticFilesHandler
        return StaticFilesHandler(handler)
383585
def wrap_handler(cls, handler, protocol, **kwargs):
        '''  '''
        def _wrapper(request, *args, **kwargs):
            instance = cls(request=request, **kwargs)
            if protocol == Resource.Protocol.http:
                return instance._wrap_http(handler, request=request, **kwargs)
            elif protocol == Resource.Protocol.websocket:
                return instance._wrap_ws(handler, request=request, **kwargs)
            elif protocol == Resource.Protocol.amqp:
                return instance._wrap_amqp(view_type, *args, **kwargs)
            else:
                raise Exception('Communication protocol not specified')
        return _wrapper
1188243
function toRestifyHandler(handler) {
        if ((typeof handler === 'function') && (handler.length !== 3)) {
            //Wrap `virgilio-http` type handlers.
            handler = restifyHandler.bind(this, handler);
        }
        return handler;
    }
337497
def wsgi_app(self, environ, start_response):
        """"""
        @_LOCAL_MANAGER.middleware
        def _wrapped_app(environ, start_response):
            request = Request(environ)
            setattr(_local, _CURRENT_REQUEST_KEY, request)
            response = self._dispatch_request(request)
            return response(environ, start_response)
        return _wrapped_app(environ, start_response)
69341
async def _wrap_ws(self, handler, *args, **kwargs):
        '''  '''
        try:
            method = self.request_method()
            # call the wrapped handler
            data = await handler(self, *args, **kwargs)
            status = self.responses.get(method, OK)
            response = {
                'type': 'response',
                'key': getattr(self.request, 'key', None),
                'status': status,
                'payload': data
            }
        except Exception as ex:
            response = {
                'type': 'response',
                'key': getattr(self.request, 'key', None),
                'status': getattr(ex, 'status', 500),
                'payload': getattr(ex, 'msg', 'general error')
            }
        # return a formatted response object
        return self.format(method, response)