Пример #1
0
def jsoned(struct, wrap=True, meta=None, struct_key='result'):
    """ Provides a json dump of the struct

    Args:
        struct: The data to dump
        wrap (bool, optional): Specify whether to wrap the
            struct in an enclosing dict
        struct_key (str, optional): The string key which will
            contain the struct in the result dict
        meta (dict, optional): An optional dictonary to merge
            with the output dictionary.

    Examples:

        >>> jsoned([3,4,5])
        ... '{"status": "success", "result": [3, 4, 5]}'

        >>> jsoned([3,4,5], wrap=False)
        ... '[3, 4, 5]'

    """
    if wrap:
        output = {'status': 'success', struct_key: struct}
        if meta:
            output = merge(output, meta)
        return _json.dumps(output, default=json_encoder)
    else:
        return _json.dumps(struct, default=json_encoder)
Пример #2
0
def jsoned(struct, wrap=True, meta=None, struct_key='result'):
    """ Provides a json dump of the struct

    Args:
        struct: The data to dump
        wrap (bool, optional): Specify whether to wrap the
            struct in an enclosing dict
        struct_key (str, optional): The string key which will
            contain the struct in the result dict
        meta (dict, optional): An optional dictonary to merge
            with the output dictionary.

    Examples:

        >>> jsoned([3,4,5])
        ... '{"status": "success", "result": [3, 4, 5]}'

        >>> jsoned([3,4,5], wrap=False)
        ... '[3, 4, 5]'

    """
    if wrap:
        output = {'status': 'success', struct_key: struct}
        if meta:
            output = merge(output, meta)
        return _json.dumps(output,
                           default=json_encoder)
    else:
        return _json.dumps(struct,
                           default=json_encoder)
Пример #3
0
def jsoned(struct, wrap=True, meta=None):
    if wrap:
        output = {'status': 'success', 'result': struct}
        if meta:
            output = merge(output, meta)
        return _json.dumps(output, default=_json_encoder)
    else:
        return _json.dumps(struct, default=_json_encoder)
Пример #4
0
def jsoned(struct, wrap=True, meta=None):
    if wrap:
        output = {'status': 'success', 'result': struct}
        if meta:
            output = merge(output, meta)
        return _json.dumps(output,
                           default=_json_encoder)
    else:
        return _json.dumps(struct,
                           default=_json_encoder)
Пример #5
0
def error_json(status_code, error=None):
    return Response(_json.dumps({
        'status': 'failure',
        'error': error,
        'url': request.url},
        default=dthandler),
        status_code, mimetype='application/json')
Пример #6
0
def jsoned(struct, wrap=True, meta=None, struct_key=None, pre_render_callback=None):
    """ Provides a json dump of the struct

    Args:
        struct: The data to dump
        wrap (bool, optional): Specify whether to wrap the
            struct in an enclosing dict
        struct_key (str, optional): The string key which will
            contain the struct in the result dict
        meta (dict, optional): An optional dictonary to merge
            with the output dictionary.

    Examples:

        >>> jsoned([3,4,5])
        ... '{"status": "success", "result": [3, 4, 5]}'

        >>> jsoned([3,4,5], wrap=False)
        ... '[3, 4, 5]'

    """
    return _json.dumps(
        structured(
            struct, wrap=wrap, meta=meta, struct_key=struct_key,
            pre_render_callback=pre_render_callback),
        default=json_encoder)
Пример #7
0
def jsoned(struct, wrap=True, meta=None, struct_key='result', pre_render_callback=None):
    """ Provides a json dump of the struct

    Args:
        struct: The data to dump
        wrap (bool, optional): Specify whether to wrap the
            struct in an enclosing dict
        struct_key (str, optional): The string key which will
            contain the struct in the result dict
        meta (dict, optional): An optional dictonary to merge
            with the output dictionary.

    Examples:

        >>> jsoned([3,4,5])
        ... '{"status": "success", "result": [3, 4, 5]}'

        >>> jsoned([3,4,5], wrap=False)
        ... '[3, 4, 5]'

    """
    return _json.dumps(
        structured(
            struct, wrap=wrap, meta=meta, struct_key=struct_key,
            pre_render_callback=pre_render_callback),
        default=json_encoder)
Пример #8
0
def dumps(obj, **kwargs):
    _dump_arg_defaults(kwargs)
    encoding = kwargs.pop('encoding', None)
    kwargs['cls'] = JSONEncoder
    rv = _json.dumps(obj, **kwargs)
    if encoding is not None and isinstance(rv, text_type):
        rv = rv.encode(encoding)
    return rv
Пример #9
0
def exception_response_json(exception):
    log = {'exception': exception, 'remote_ip': request.remote_addr}
    current_app.logger.exception(exception)
    current_app.logger.error(str(log))
    result = {'status': 'failure', 'error': exception.description}
    return Response(_json.dumps(result, default=_json_encoder),
                    exception.code,
                    mimetype='application/json')
def error_json(status_code, error=None):
    return Response(_json.dumps({
        'status': 'failure',
        'error': error
    },
                                default=json_encoder),
                    status_code,
                    mimetype='application/json')
Пример #11
0
def exception_response_json(exception):
    log = {
        'exception': exception,
        'remote_ip': request.remote_addr
    }
    current_app.logger.exception(exception)
    current_app.logger.error(str(log))
    return Response(_json.dumps({
        'status': 'failure',
        'error': exception.description,
        'url': request.url},
        default=dthandler),
        exception.code, mimetype='application/json')
Пример #12
0
def _sanitize_object(obj):
    result = {}
    for k, v in obj.items():
        if isinstance(v, int) or isinstance(v, Decimal):
            result[k] = v
        elif not (isinstance(v, str) or isinstance(v, six.text_type)):
            result[k] = json.loads(bleach.clean(json.dumps(v)))
        else:
            result[k] = bleach.clean(v)
        if result[k] == '':
            result[k] = None
        # Making an assumption that there is no good usecase
        # for setting an empty string. This will help prevent
        # cases where empty string is sent because of client
        # not clearing form fields to null
    return result
Пример #13
0
def setter_request(url,
                   method,
                   data,
                   key=config.API_KEY,
                   secret=config.API_SECRET,
                   raw=False):
    requester = getattr(requests, method.lower())
    json_data = json.dumps(data)
    response = requester(url,
                         data=json_data,
                         headers={
                             'Content-Type':
                             JSON_MIME_TYPE,
                             'Authorization':
                             get_signed_authorization_header(
                                 key or config.API_KEY, secret
                                 or config.API_SECRET,
                                 "{0}:{1}:{2}:{3}".format(
                                     method, url, JSON_MIME_TYPE, json_data))
                         })
    if raw:
        return response
    else:
        return result(response)
Пример #14
0
    def _post_data(self, context, traceback=None):
        """POST data to the the Exceptional API. If DEBUG is True then data is
        sent to ``EXCEPTIONAL_DEBUG_URL`` if it has been defined. If TESTING is
        true, error data is stored in the global ``flask.g.exceptional``
        variable.

        :param context: The current application or application context.
        :param traceback: Default ``None``. The exception stack trace.
        """
        if context:
            if isinstance(context, Flask):
                app = context
                context = None
            else:
                app = context.app
        else:
            app = stack.top.app

        application_data = self.__get_application_data(app)
        client_data = {
            "name": "flask-exceptional",
            "version": self.__version__,
            "protocol_version": self.__protocol_version
        }

        if context:
            request_data = self.__get_request_data(app, context.request,
                                                   context.session)
            context_data = getattr(context, "exceptional_context", None)
        else:
            request_data = None
            context_data = None

        traceback = traceback or tbtools.get_current_traceback()
        exception_data = self.__get_exception_data(traceback)
        encode_basestring = json.encoder.encode_basestring

        def _encode_basestring(value):
            if isinstance(value, str) and \
                    json.encoder.HAS_UTF8.search(value) is not None:
                value = value.decode("utf-8",
                                     "replace")  # ensure the decode succeeds.

            replace = lambda match: json.encoder.ESCAPE_DCT[match.group(0)]

            return u'"%s"' % json.encoder.ESCAPE.sub(replace, value)

        try:
            json.encoder.encode_basestring = _encode_basestring
            ret_val = json.dumps(
                {
                    "application_environment": application_data,
                    "client": client_data,
                    "request": request_data,
                    "exception": exception_data,
                    "context": context_data
                },
                ensure_ascii=False).encode("utf-8")
        finally:
            json.encoder.encode_basestring = encode_basestring

        if context and app.testing:
            g.exceptional = ret_val

        if self.url:
            request = Request(self.url)
            request.add_header("Content-Type", "application/json")

            if app.debug:
                data = ret_val
            else:
                request.add_header("Content-Encoding", "deflate")
                data = compress(ret_val, 1)

            try:
                try:
                    urlopen(request, data)
                except HTTPError, e:
                    if e.code >= 400:
                        raise
            except URLError:
                message = "Unable to connect to %s. See http://status.exceptional.io for details. Error data:\n%s"  # NOQA
                app.logger.warning(message, self.url, ret_val, exc_info=True)
            except BadStatusLine:
                pass

        return ret_val
Пример #15
0
 def process_bind_param(self, value, dialect):
     if value is not None:
         value = json.dumps(value, default=json_encoder)
     return value
Пример #16
0
 def jpatch(self, url, data, **kwargs):
     kwargs['content_type'] = "application/json"
     jdata = json.dumps(data, default=json_encoder)
     parse_json_response = kwargs.pop('parse_json_response', True)
     resp = self.patch(url, data=jdata, **kwargs)
     return json.loads(resp.data) if parse_json_response else resp
Пример #17
0
 def jpost(self, url, **kwargs):
     kwargs['content_type'] = "application/json"
     kwargs['data'] = json.dumps(
         kwargs['data'], default=_json_encoder)
     return self.post(url, **kwargs)
Пример #18
0
def json_dump(obj):
    return _json.dumps(
        obj,
        default=json_encoder)
Пример #19
0
def error_json(status_code, error=None):
    return Response(_json.dumps({
        'status': 'failure',
        'error': error},
        default=json_encoder),
        status_code, mimetype='application/json')
 def jpatch(self, url, data, **kwargs):
     kwargs['content_type'] = "application/json"
     jdata = json.dumps(data, default=json_encoder)
     parse_json_response = kwargs.pop('parse_json_response', True)
     resp = self.patch(url, data=jdata, **kwargs)
     return json.loads(resp.data) if parse_json_response else resp
Пример #21
0
def json_dump(obj):
    return _json.dumps(
        obj,
        default=json_encoder)
Пример #22
0
 def process_bind_param(self, value, dialect):
     if value is not None:
         value = json.dumps(value, default=json_encoder)
     return value
def booster_json_dumps(obj):
    return _json.dumps(obj, cls=BoosterJSONEncoder)
Пример #24
0
    def _post_data(self, context, traceback=None):
        """POST data to the the Exceptional API. If DEBUG is True then data is
        sent to ``EXCEPTIONAL_DEBUG_URL`` if it has been defined. If TESTING is
        true, error data is stored in the global ``flask.g.exceptional``
        variable.

        :param context: The current application or application context.
        :param traceback: Default ``None``. The exception stack trace.
        """
        if context:
            if isinstance(context, Flask):
                app = context
                context = None
            else:
                app = context.app
        else:
            app = stack.top.app

        application_data = self.__get_application_data(app)
        client_data = {
            "name": "flask-exceptional",
            "version": self.__version__,
            "protocol_version": self.__protocol_version
        }

        if context:
            request_data = self.__get_request_data(app, context.request,
                    context.session)
            context_data = getattr(context, "exceptional_context", None)
        else:
            request_data = None
            context_data = None

        traceback = traceback or tbtools.get_current_traceback()
        exception_data = self.__get_exception_data(traceback)
        encode_basestring = json.encoder.encode_basestring

        def _encode_basestring(value):
            if isinstance(value, str) and \
                    json.encoder.HAS_UTF8.search(value) is not None:
                value = value.decode("utf-8",
                        "replace")  # ensure the decode succeeds.

            replace = lambda match: json.encoder.ESCAPE_DCT[match.group(0)]

            return u'"%s"' % json.encoder.ESCAPE.sub(replace, value)

        try:
            json.encoder.encode_basestring = _encode_basestring
            ret_val = json.dumps({
                "application_environment": application_data,
                "client": client_data,
                "request": request_data,
                "exception": exception_data,
                "context": context_data
            }, ensure_ascii=False).encode("utf-8")
        finally:
            json.encoder.encode_basestring = encode_basestring

        if context and app.testing:
            g.exceptional = ret_val

        if self.url:
            request = Request(self.url)
            request.add_header("Content-Type", "application/json")

            if app.debug:
                data = ret_val
            else:
                request.add_header("Content-Encoding", "deflate")
                data = compress(ret_val, 1)

            try:
                try:
                    urlopen(request, data)
                except HTTPError, e:
                    if e.code >= 400:
                        raise
            except URLError:
                message = "Unable to connect to %s. See http://status.exceptional.io for details. Error data:\n%s"  # NOQA
                app.logger.warning(message, self.url, ret_val,
                        exc_info=True)
            except BadStatusLine:
                pass

        return ret_val