Exemple #1
0
def jsonify(return_data={}, **kwargs):
    """
    Overriding Flask's jsonify method to account for extra error handling

    :param return_data: dictionary of data to be passed to :meth:`flask:flask.jsonify`
    :param kwargs: Optional keyword arguments merged into return_data
    :return: output of :meth:`flask:flask.jsonify`
    """
    if isinstance(return_data, dict) and return_data.get('error'):
        handle_error(return_data)
        return _jsonify(dict_merge(dict(success=False), dict_merge(kwargs, return_data)))
    if len(kwargs):
        return _jsonify(dict_merge(kwargs, return_data))
    return _jsonify(return_data)
Exemple #2
0
def jsonify(obj):
    """
    Updated jsonify, adding list support.
    """
    if isinstance(obj, (list, tuple)):
        return Response(json.dumps(obj), mimetype='application/json')
    return _jsonify(obj)
Exemple #3
0
def jsonify(obj):
    """
    Updated jsonify, adding list support.
    """
    if isinstance(obj, (list, tuple)):
        return Response(json.dumps(obj), mimetype='application/json')
    return _jsonify(obj)
Exemple #4
0
 def apply(*pargs, **kargs):
   result = fn(*pargs, **kargs)
   response = _jsonify(**kargify(result))
   try:
     response.status_code = result['head']['status']
   except:
     response.status_code = 200
   return response
Exemple #5
0
 def unauthorised(error):
     return (
         _jsonify({
             "success": False,
             "error": 401,
             "message": "unauthorised"
         }),
         401,
     )
Exemple #6
0
 def unprocessable(error):
     return (
         _jsonify({
             "success": False,
             "error": 422,
             "message": "unprocessable"
         }),
         422,
     )
Exemple #7
0
 def internal_error(error):
     return (
         _jsonify({
             "success": False,
             "error": 500,
             "message": "the server could not complete the request",
         }),
         500,
     )
Exemple #8
0
def jsonify(*args, **kwargs):
    """
    Extends flask.jsonify by allowing to set a custom HTTP status code.
    """
    status_code = kwargs.get('status_code', None)
    if status_code is not None:
        del kwargs['status_code']
    response = _jsonify(*args, **kwargs)
    response.status_code = status_code if status_code else 200
    return response
Exemple #9
0
def _handle_error(err):
    """It helps preventing writing unnecessary
    try/except block though out the application
    """
    # Handle HTTPExceptions
    if isinstance(err, _HTTPException):
        msg = getattr(err, "description", _HTTP_STATUS_CODES.get(err.code, ""))
        msg = msg if msg else getattr(err, "message", "unspecified")
        return (
            _jsonify({
                "message": msg,
                "status_code": err.code,
                "details": str(err),
            }),
            err.code,
        )

    # Handle SQLAlchemyErrors
    if isinstance(err, _SQLAlchemyError):
        return (
            _jsonify({
                "message": "Backend error encountered.",
                "details": str(getattr(err, "orig", err)).split("\n")[0],
                "status_code": 400,
            }),
            400,
        )

    # If message attribute is not set,
    # consider it as Python core exception and
    # hide sensitive error info from end user
    if not getattr(err, "message", None):
        return (
            _jsonify({
                "message": "Server has encountered an error",
                "status_code": 500,
                "details": "Python error.  See server logs for details",
            }),
            500,
        )
    # Handle application specific custom exceptions
    return _jsonify(**err.kwargs), err.http_status_code
Exemple #10
0
def jsonify(**kwargs):
    def dictify(model):
        return model.__dictify__

    for k, v in kwargs.items():
        with ignores(AttributeError):
            if isinstance(v, db.Model):
                kwargs[k] = dictify(v)
            elif isinstance(v, list):
                kwargs[k] = [dictify(i) for i in v]

    return _jsonify(**kwargs)
Exemple #11
0
def jsonify(func=None, *args, **kargs):
    """Function or decorator that returns jsonfiy response"""
    if callable(func):
        # pylint: disable=missing-docstring
        @wraps(func)
        def decorated(*args, **kargs):
            return _jsonify(**func(*args, **kargs))

        return decorated
    else:
        if func is not None:
            # consider `f` a positional arg
            args = tuple([func] + list(args))
        return _jsonify(*args, **kargs)
Exemple #12
0
    def wrapper(*args, **kwargs):
        results = func(*args, **kwargs)

        status_code = 200
        if isinstance(results, tuple):
            data = results[0]
            if len(results) > 1:
                status_code = results[1]
        else:
            data = results

        response = _jsonify(data)
        response.status_code = status_code

        return response
Exemple #13
0
def jsonify(data=None, code=200, **kwargs):
    response = dict(msg='success', error_code=0)
    if not data:
        response.update(data=kwargs)

    if isinstance(data, Base):
        for k, v in kwargs.items():
            setattr(data, k, v)
            data.append(k)
        response.update(data=data)

    if isinstance(data, list):
        response.update(data=data)
        for k, v in kwargs.items():
            setattr(response, k, v)

    return _jsonify(response), code
Exemple #14
0
def jsonify(obj, status_code=200):
    obj["status"] = "error" if "error" in obj else "okay"
    res = _jsonify(obj)
    res.status_code = status_code
    return res
Exemple #15
0
def jsonify(status_code, *args, **kwargs):
    response = _jsonify(*args, **kwargs)
    if status_code:
        response.status_code = status_code
    return response
Exemple #16
0
 def apply(*pargs, **kargs):
   result = fn(*pargs, **kargs)
   response = _jsonify(**kargify(result))
   response.status_code = 200
   return response
Exemple #17
0
def _retval(code, result=None):
    d = {'success': code == _ErrorCode.Success, 'code': code.value}
    if result is not None:
        d['result'] = result
    return _jsonify(d)
Exemple #18
0
def jsonify(res, http_code=200, msg=''):
    res['code'] = http_code
    res['msg'] = msg
    return _jsonify(res), http_code
def jsonify(data):
    response = _jsonify(data)
    response.headers['Access-Control-Allow-Origin'] = '*'
    return response
Exemple #20
0
 def not_found(error):
     return _jsonify({
         "success": False,
         "error": 404,
         "message": "not found"
     }), 404
Exemple #21
0
def jsonify(status_code, *args, **kwargs):
    resp = _jsonify(*args, **kwargs)
    resp.status_code = status_code
    return resp
def jsonify(d):
    resp = _jsonify(d)
    resp.status_code = d.get("code", 200)
    return resp
Exemple #23
0
def jsonify(obj, status_code=200):
    obj['status'] = 'error' if 'error' in obj else 'okay'
    res = _jsonify(obj)
    res.status_code = status_code
    return res
Exemple #24
0
def jsonify(status_code, *args, **kwargs):
    resp = _jsonify(*args, **kwargs)
    resp.status_code = status_code
    return resp
Exemple #25
0
 def decorated(*args, **kargs):
     return _jsonify(**func(*args, **kargs))