Set a instance method to be call as a wsgi application, adding common
    behavior and using webob.Request for practical use.


    @wsgi_handler
    def handle_verify_token(self, request):
        pass

    :param func:
    :return:
558077
def wsgi_handler(func):
    

    @wraps(func)
    def inner(*args):
        self, environ, start_response, *args = args
        request = Request(environ)

        try:
            response = func(self, request)
        except Exception as err:
            raise
        else:
            return response(environ, start_response)

    return inner
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)
1151547
def auth_required(method):
    
    @functools.wraps(method)
    def wrapper(*args, **kwargs):
        _verify_and_add_jwt()
        try:
            return method(*args, **kwargs)
        finally:
            remove_jwt_data_from_app_context()
    return wrapper
805787
def execute(func, handler, args, kwargs):
    
    tracing = handler.settings.get('opentracing_tracing')

    with tracer_stack_context():
        if tracing._trace_all:
            attrs = handler.settings.get('opentracing_traced_attributes', [])
            tracing._apply_tracing(handler, attrs)

        return func(*args, **kwargs)
197440
def setter(self, func):
        
        if not callable(func):
            raise TypeError('setter must be callable function')
        if hasattr(func, '__code__') and func.__code__.co_argcount != 2:
            raise TypeError('setter must be a function with two arguments')
        if func.__name__ != self.name:
            raise TypeError('setter function must have same name as getter')
        self._set_func = func
        return self
977373
def __request(self, method, url, request_args, headers=None, stream=False):
        
        func = getattr(self.client, method)
        headers = headers if headers else {}
        response = None
        try:
            logger.info("performing request %s", url)
            response = func(url, stream=stream, headers=headers,
                            **request_args)
        except requests.RequestException as err:
            logger.error("request %s failed [%s]", url, err)
            raise err

        # Handle error responses
        if response.status_code >= 400:
            logger.error("request %s failed [%d,%s]",
                         url,
                         response.status_code,
                         response.content.decode('utf-8'))
            raise V20Error(response.status_code,
                           response.content.decode('utf-8'))
        return response
355138
def authenticated(func):
    
    @wraps(func)
    def wrapper(*args, **kwargs):
        self = args[0]
        if self.refresh_token is not None and \
           self.token_expiration_time <= dt.datetime.utcnow():
            self.re_authenticate()
        return func(*args, **kwargs)
    return wrapper
29831
def require_auth(function):
    
    @functools.wraps(function)
    def wrapper(self, *args, **kwargs):
        if not self.access_token():
            raise MissingAccessTokenError
        return function(self, *args, **kwargs)
    return wrapper
1185769
def add_handler(self, func, type='all'):
        
        if not callable(func):
            raise ValueError("{} is not callable".format(func))

        self._handlers[type].append(
            (func, len(signature(func).parameters.keys()))
        )
384972
def basic_auth_required(view_func):
    
    @wraps(view_func)
    def wrapper(*args, **kwargs):
        if app.config.get('BASIC_AUTH_ACTIVE', False):
            if basic_auth.authenticate():
                return view_func(*args, **kwargs)
            else:
                return basic_auth.challenge()
        else:
            return view_func(*args, **kwargs)
    return wrapper
1092300
def open_required(func):
    

    def wrapper(self, *args, **kwargs):
        if self._status == "closed":
            raise aiohttp.web.HTTPForbidden(text="The project is not opened")
        return func(self, *args, **kwargs)
    return wrapper
280974
def request(self, request_type):
        '''  '''

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

        return _handler
398642
def set_callback(self, func):
        

        if isinstance(func, str if py3k else basestring) and func:
            self.arguments.update({'callback': '%s' % func})
        else:
            raise TwitterSearchException(1006)
974819
def _request(self, func, url, version=1, *args, **kwargs):
        
        return_json = kwargs.pop('return_json', False)
        url = self.api_url[version] + url
        response = func(url, *args, **kwargs)

        if 'proxies' not in kwargs:
            kwargs['proxies'] = self.proxydict

        # Check for error, raising an exception if appropriate.
        response.raise_for_status()

        try:
            json_response = response.json()
        except ValueError:
            json_response = None
        if isinstance(json_response, dict):
            error = json_response.get('error')
            if error:
                raise BitstampError(error)
            elif json_response.get('status') == "error":
                raise BitstampError(json_response.get('reason'))

        if return_json:
            if json_response is None:
                raise BitstampError(
                    "Could not decode json for: " + response.text)
            return json_response

        return response
586840
def _generate_handler_wrapper(api_name, api_spec, endpoint, handler_func, error_callback, global_decorator):
    """"""

    # Decorate the handler function, if Swagger spec tells us to
    if endpoint.decorate_server:
        endpoint_decorator = get_function(endpoint.decorate_server)
        handler_func = endpoint_decorator(handler_func)

    @wraps(handler_func)
    def handler_wrapper(**path_params):
        log.info(" ")
        log.info(" ")
        log.info("=> INCOMING REQUEST %s %s -> %s" %
                 (endpoint.method, endpoint.path, handler_func.__name__))
        log.info(" ")
        log.info(" ")

        # Get caller's pym-call-id or generate one
        call_id = request.headers.get('PymCallID', None)
        if not call_id:
            call_id = str(uuid.uuid4())
        stack.top.call_id = call_id

        # Append current server to call path, or start one
        call_path = request.headers.get('PymCallPath', None)
        if call_path:
            call_path = "%s.%s" % (call_path, api_name)
        else:
            call_path = api_name
        stack.top.call_path = call_path

        if endpoint.param_in_body or endpoint.param_in_query:
            # Turn the flask request into something bravado-core can process...
            try:
                req = FlaskRequestProxy(request, endpoint.param_in_body)
            except BadRequest:
                ee = error_callback(ValidationError("Cannot parse json data: have you set 'Content-Type' to 'application/json'?"))
                return _responsify(api_spec, ee, 400)

            try:
                # Note: unmarshall validates parameters but does not fail
                # if extra unknown parameters are submitted
                parameters = unmarshal_request(req, endpoint.operation)
                # Example of parameters: {'body': RegisterCredentials()}
            except jsonschema.exceptions.ValidationError as e:
                ee = error_callback(ValidationError(str(e)))
                return _responsify(api_spec, ee, 400)

        # Call the endpoint, with proper parameters depending on whether
        # parameters are in body, query or url
        args = []
        kwargs = {}

        if endpoint.param_in_path:
            kwargs = path_params

        if endpoint.param_in_body:
            # Remove the parameters already defined in path_params
            for k in list(path_params.keys()):
                del parameters[k]
            lst = list(parameters.values())
            assert len(lst) == 1
            args.append(lst[0])

        if endpoint.param_in_query:
            kwargs.update(parameters)

        result = handler_func(*args, **kwargs)

        if not result:
            e = error_callback(PyMacaronCoreException("Have nothing to send in response"))
            return _responsify(api_spec, e, 500)

        # Did we get the expected response?
        if endpoint.produces_html:
            if type(result) is not tuple:
                e = error_callback(PyMacaronCoreException("Method %s should return %s but returned %s" %
                                                          (endpoint.handler_server, endpoint.produces, type(result))))
                return _responsify(api_spec, e, 500)

            # Return an html page
            return result

        elif endpoint.produces_json:
            if not hasattr(result, '__module__') or not hasattr(result, '__class__'):
                e = error_callback(PyMacaronCoreException("Method %s did not return a class instance but a %s" %
                                                          (endpoint.handler_server, type(result))))
                return _responsify(api_spec, e, 500)

            # If it's already a flask Response, just pass it through.
            # Errors in particular may be either passed back as flask Responses, or
            # raised as exceptions to be caught and formatted by the error_callback
            result_type = result.__module__ + "." + result.__class__.__name__
            if result_type == 'flask.wrappers.Response':
                return result

            # We may have got a pymacaron Error instance, in which case
            # it has a http_reply() method...
            if hasattr(result, 'http_reply'):
                # Let's transform this Error into a flask Response
                log.info("Looks like a pymacaron error instance - calling .http_reply()")
                return result.http_reply()

            # Otherwise, assume no error occured and make a flask Response out of
            # the result.

            # TODO: check that result is an instance of a model expected as response from this endpoint
            result_json = api_spec.model_to_json(result)

            # Send a Flask Response with code 200 and result_json
            r = jsonify(result_json)
            r.status_code = 200
            return r

    handler_wrapper = cross_origin(headers=['Content-Type', 'Authorization'])(handler_wrapper)

    # And encapsulate all in a global decorator, if given one
    if global_decorator:
        handler_wrapper = global_decorator(handler_wrapper)

    return handler_wrapper
602172
def expose_request(func):
    
    if not python.callable(func):
        raise TypeError("func must be callable")

    if isinstance(func, types.UnboundMethodType):
        setattr(func.im_func, '_pyamf_expose_request', True)
    else:
        setattr(func, '_pyamf_expose_request', True)

    return func
1104694
def auth_basic(check, realm="private", text="Access denied"):
    '''  '''
    def decorator(func):
        def wrapper(*a, **ka):
            user, password = request.auth or (None, None)
            if user is None or not check(user, password):
                err = HTTPError(401, text)
                err.add_header('WWW-Authenticate', 'Basic realm="%s"' % realm)
                return err
            return func(*a, **ka)
        return wrapper
    return decorator