Using ajax decorator
507898
def dispatch(self, request, *args, **kwargs):
        
        ajax_kwargs = {'mandatory': self.ajax_mandatory}
        if self.json_encoder:
            ajax_kwargs['cls'] = self.json_encoder

        return ajax(**ajax_kwargs)(super(
            AJAXMixin, self).dispatch)(request, *args, **kwargs)
350979
def action_decorator(name):
    
    def decorator(cls):
        action_decorators.append((name, cls))
        return cls
    return decorator
21763
function ajax(url, options, callback) {
        if (typeof options === 'function') {
          callback = options;
          options = {};
        }
        callback = callback || function () {};
        var xhr = new XMLHttpRequest();
        xhr.onload = function () {
          if (xhr.status >= 400) {
            return callback(new Error(xhr.responseText || xhr.statusText));
          }
          try {
            return callback(null, JSON.parse(xhr.responseText));
          } catch (e) {
            return callback(new Error('invalid_response'));
          }
        };
        xhr.onerror = function (err) {
          return callback(err);
        };
        xhr.open('GET', url);
        xhr.send();
      }
20067
def _check_decorator(fct):
        """"""
        def wrapper(self, *args, **kw):
            if self.is_enable():
                ret = fct(self, *args, **kw)
            else:
                ret = self.stats
            return ret
        return wrapper
1133788
def saveit(func):
    """"""

    name = '_' + func.__name__

    def _wrapper(self, *args, **kwds):
        if not hasattr(self, name):
            setattr(self, name, func(self, *args, **kwds))
        return getattr(self, name)
    return _wrapper
1365461
function() {
            this.xhr = $.ajax(_.extend({}, {
                "type":     this.options.method,
                "url":      this.options.url,
                "data":     this.options.params,
                "dataType": this.options.dataType,
                "context":  this,
                "success":  function(data) {
                    logging.debug("Result for request ", this.options);
                    this.trigger("done", data);
                },
                "error": function(xhr, textStatus, errorThrown) {
                    logging.error("Error for request ", this.options);
                    this.trigger("error", {
                        'status': textStatus,
                        'error': errorThrown,
                        'content': xhr.responseText,
                        'xhr': xhr
                    });
                }
            }, this.options.options));
            return this;
        }
1195415
def _handler(func):
    ""

    def _wrapped(*a, **k):
        r = func(*a, **k)
        if r is None: r = 0
        return r

    return staticmethod(_wrapped)
1209544
def on(  # pylint: disable=invalid-name
            self, event: str, *handlers: T.Callable
    ) -> T.Callable:
        """"""

        def _on_wrapper(*handlers: T.Callable) -> T.Callable:
            """wrapper for on decorator"""
            self._events[event].extend(handlers)
            return handlers[0]

        if handlers:
            return _on_wrapper(*handlers)
        return _on_wrapper
1295741
def hook(self, name):
        
        def decorator(func):
            self.add_hook(name, func)
            return func
        return decorator
151148
function _ajax$(url, settings, override) {
    // We just need to split up the arguments and pass them to ``doit``.
    var originalArgs = settings ? [url, settings] : [url];
    var originalSettings = settings || url;
    var extracted = bluetry.extractBluejaxOptions(originalArgs);
    // We need a copy here so that we do not mess up what the user passes to us.
    var bluejaxOptions = $.extend({}, override, extracted[0]);
    var cleanedOptions = extracted[1];
    return doit(originalArgs, originalSettings, cleanedOptions, bluejaxOptions);
  }
780431
def detect_and_decorate(decorator, args, kwargs):
    
    # special behavior when invoked with only one non-keyword argument: act as
    # a normal decorator, decorating and returning that argument with
    # click.option
    if len(args) == 1 and len(kwargs) == 0 and callable(args[0]):
        return decorator(args[0])

    # if we're not doing that, we should see no positional args
    # the alternative behavior is to fall through and discard *args, but this
    # will probably confuse someone in the future when their arguments are
    # silently discarded
    elif len(args) != 0:
        raise ValueError("this decorator cannot take positional args")

    # final case: got 0 or more kwargs, no positionals
    # do the function-which-returns-a-decorator dance to produce a
    # new decorator based on the arguments given
    else:

        def inner_decorator(f):
            return decorator(f, **kwargs)

        return inner_decorator
1119052
def returns_json(func):
    
    def decorator(*args, **kwargs):
        instance = args[0]
        request = getattr(instance, 'request', None)
        request.response.setHeader("Content-Type", "application/json")
        result = func(*args, **kwargs)
        return json.dumps(result)
    return decorator
481051
def api(func):
    """"""
    @wraps(func)
    def decorated_function(*args, **kwargs):
        try:
            value = func(*args, **kwargs)
        except BaseException as e:
            value = {
                "status": "failed",
                "error": "Unkonwn error!"
            }
            flask.current_app.logger.error("Unkonwn error: %s" % str(e))
            flask.current_app.logger.exception(e)

        status = 200
        mimetype = 'application/json'
        content = json.dumps(value)
        callback = flask.request.args.get('callback', False)
        if callback:
            content = str(callback) + '(' + content + ')'
            mimetype = 'application/javascript'

        return flask.current_app.response_class(content, status=status, mimetype=mimetype)
    return decorated_function
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
77262
def api(func=None, timeout=API_TIMEOUT):  # incoming
    
    if func is None:
        return partial(api, timeout=timeout)
    else:
        wrapper = _get_api_decorator(func=func, timeout=timeout)
        return wrapper
1068684
def patch_loader(*decorator_args, serializer):
    
    def wrapped(fn):
        @wraps(fn)
        def decorated(*args, **kwargs):
            result = serializer.load(request.get_json(),
                                     instance=kwargs.pop('instance'),
                                     partial=True)
            if not result.errors and not result.data.id:
                abort(HTTPStatus.NOT_FOUND)
            return fn(*result)
        return decorated

    if decorator_args and callable(decorator_args[0]):
        return wrapped(decorator_args[0])
    return wrapped
1326815
def render_as_json(func):
    
    if inspect.isclass(func):
        setattr(func, "_renderer", json_renderer)
        return func
    else:
        @functools.wraps(func)
        def decorated_view(*args, **kwargs):
            data = func(*args, **kwargs)
            return _build_response(data, jsonify)
        return decorated_view