Пример #1
0
def jsonify(*args, **kwargs):
    if len(args) == 1 and type(args[0]) in (list, tuple):
        return current_app.response_class(
            json.dumps(args[0], indent=None if request.is_xhr else 2),
            mimetype='application/json'
        )
    return flask_jsonify(*args, **kwargs)
Пример #2
0
def a_json_endpoint():
    """Returns a simple JSON document.
    ---
    tags:
      - Response formats
    produces:
      - application/json
    responses:
      200:
        description: An JSON document.
    """
    return flask_jsonify(
        slideshow={
            'title': 'Sample Slide Show',
            'date': 'date of publication',
            'author': 'Yours Truly',
            'slides': [
                {'type': 'all',
                 'title': 'Wake up to WonderWidgets!'},
                {'type': 'all',
                 'title': 'Overview',
                 'items': [
                    'Why <em>WonderWidgets</em> are great',
                    'Who <em>buys</em> WonderWidgets'
                 ]}
            ]
        }
    )
Пример #3
0
def a_json_endpoint():
    """Returns a simple JSON document.
    ---
    tags:
      - Response formats
    produces:
      - application/json
    responses:
      200:
        description: An JSON document.
    """
    return flask_jsonify(
        slideshow={
            "title": "Sample Slide Show",
            "date": "date of publication",
            "author": "Yours Truly",
            "slides": [
                {"type": "all", "title": "Wake up to WonderWidgets!"},
                {
                    "type": "all",
                    "title": "Overview",
                    "items": [
                        "Why <em>WonderWidgets</em> are great",
                        "Who <em>buys</em> WonderWidgets",
                    ],
                },
            ],
        }
    )
Пример #4
0
def jsonify(*args, **kwargs):
    kwargs = dict([(k, jsonable(v)) for k, v in kwargs.items()])
    for x in jsonable(args):
        for k, v in x.items():
            if k in kwargs:
                raise Exception("key duplicated. key: {}".format(k))
            kwargs[k] = v
    return flask_jsonify(**kwargs)
Пример #5
0
 def make_response(*args, **kwargs):
     response = dict(status=None, msg='')
     try:
         f(*args, **kwargs)
         response['status'] = True
     except Exception as exc:
         response['status'] = False
         response['msg'] = str(exc)
     return flask_jsonify(**response)
Пример #6
0
 def default_json_error(ex):
     """ Exception -> flask JSON responder """
     app.logger.error("Uncaught error thrown by Flask/Werkzeug: {0}"
                      .format(ex))
     response = flask_jsonify(message=str(ex), type='api_error')
     response.status_code = (ex.code
                             if isinstance(ex, HTTPException)
                             else 500)
     return response
Пример #7
0
 def default_json_error(ex):
     """ Exception -> flask JSON responder """
     logger = get_logger()
     logger.error('Uncaught error thrown by Flask/Werkzeug', exc_info=ex)
     response = flask_jsonify(message=str(ex), type='api_error')
     response.status_code = (ex.code
                             if isinstance(ex, HTTPException)
                             else 500)
     return response
Пример #8
0
 def _wrapped(*args, **kwargs):
     from flask import jsonify as flask_jsonify
     try:
         result_dict = f(*args, **kwargs)
     except Exception as e:
         result_dict = dict(success=False)
         result_dict['content'] = 'Operation failed: ' + e.message
         if app.config['DEBUG']:
             from traceback import format_exc
             result_dict['exc_info'] = format_exc(e)
     return flask_jsonify(**result_dict)
Пример #9
0
 def _wrapped(*args, **kwargs):
     from flask import jsonify as flask_jsonify
     try:
         result_dict = f(*args, **kwargs)
     except Exception as e:
         result_dict = dict(status='error')
         if current_app.config['DEBUG']:
             result_dict['reason'] = e.message
             from traceback import format_exc
             result_dict['exc_info'] = format_exc(e)
     return flask_jsonify(**result_dict)
Пример #10
0
def jsonify(func, *args, **kwargs):
    """Creates a :class:`~flask.Response` with the JSON representation of
    the given arguments with an `application/json` mimetype.  The arguments
    to this function are the same as to the :class:`dict` constructor.

    It is a decorator for :func:`flask.jsonify`, to auto serialize object or
    dictionary to json response by :module:`jsonpickle` & :func:`flask.jsonify`

    Example usage::

        from flask.views import MethodView
        from .decorator import jsonify

        class User(object):
            def __init__(self, name):
                self.name = name


        class UserView(MethodView):
            decorators = [jsonify]

            def get(self):
                return {"name": "Tony"}

            def post(self):
                user = User("Tony")
                return user

    This will send a JSON response like this to the browser::

        {
            "name": "Tony",
        }

    For security reasons only objects are supported toplevel.  For more
    information about this, have a look at :ref:`json-security`.

    This function's response will be pretty printed if it was not requested
    with ``X-Requested-With: XMLHttpRequest`` to simplify debugging unless
    the ``JSONIFY_PRETTYPRINT_REGULAR`` config parameter is set to false.
    """
    result = func(*args, **kwargs)

    if isinstance(result, dict):
        pass
    elif isinstance(result, Response):
        return result
    elif type(result) in JSON_TYPES:
        result = {"data": result}
    else:
        result = dumps(result, unpicklable=False)

    return flask_jsonify(result)
Пример #11
0
    def _wrapped(*args, **kwargs):
        from flask import jsonify as flask_jsonify

        try:
            result_dict = f(*args, **kwargs)
        except Exception as e:
            result_dict = dict(status="error")
            if current_app.config["DEBUG"]:
                result_dict["reason"] = str(e)
                from traceback import format_exc

                result_dict["exc_info"] = format_exc()
        return flask_jsonify(**result_dict)
Пример #12
0
def del_cdmi_dir_obj(path):
    """Delete a directory through CDMI."""

    try:
        storage.rmdir(path)
    except storage.NotFoundException as e:
        return e.msg, 404
    except storage.NotAuthorizedException as e:
        return e.msg, 401
    except storage.ConflictException as e:
        return e.msg, 409
    except storage.StorageException as e:
        return e.msg, 500

    return flask_jsonify(delete='Deleted: %s' % (path))
Пример #13
0
 def wrapped(*args, **kwargs):
     rv = f(*args, **kwargs)
     status_or_headers = {}
     headers = None
     if isinstance(rv, tuple):
         rv, status_or_headers, headers = rv + (None,) * (3 - len(rv))
     if isinstance(status_or_headers, (dict, list)):
         headers, status_or_headers = status_or_headers, None
     if not isinstance(rv, dict):
         # assume it is a model, call its to_json() method
         rv = rv.to_json(exclude=exclude).data
     rv = flask_jsonify(rv)
     if status_or_headers is not None:
         rv.status_code = status_or_headers
     if headers is not None:
         rv.headers.extend(headers)
     return rv
Пример #14
0
def put_cdmi_dir_obj(path):
    """Put a directory entry through CDMI.

    Create a directory.
    """

    try:
        storage.mkdir(path)
    except storage.NotFoundException as e:
        return e.msg, 404
    except storage.NotAuthorizedException as e:
        return e.msg, 401
    except storage.ConflictException as e:
        return e.msg, 409
    except storage.StorageException as e:
        return e.msg, 500

    return flask_jsonify(create='Created')
Пример #15
0
def api_get_hint(session_id, extra_msg=None):
    # TODO: get hint by request
    session = db.sessions.find_one({'id': session_id})
    current_hint_id = session['current_hint_id']
    try:
        hint = session['hints'][current_hint_id]
    except LookupError:
        return restart_session(session_id,
                               extra_msg='На жаль, використані всі можливі підказки. '
                                         'Моє слово було: {}'.format(session.get('word')))
    db.sessions.update({'id': session_id},
                       {'$inc': {'current_hint_id': 1}})

    hint = "Підказка №{}:  {}".format(current_hint_id  + 1, hint)
    if extra_msg:
        hint = extra_msg + '\n' + hint

    return flask_jsonify({'hint': hint})
Пример #16
0
def get_cdmi_dir_obj(path):
    """Get a directory entry through CDMI.

    Get the listing of a directory.

    TODO: find a way to stream the listing.
    """
    cdmi_filters = []
    if request_wants_cdmi_object():
        try:
            cdmi_filters = get_cdmi_filters(request.args)
        except MalformedArgumentValueException as e:
            return e.msg, 400

    try:
        dir_list = [x for x in storage.ls(path)]
    except storage.NotFoundException as e:
        return e.msg, 404
    except storage.NotAuthorizedException as e:
        return e.msg, 401
    except storage.StorageException as e:
        return e.msg, 500

    if request_wants_cdmi_object():
        cdmi_json_gen = get_cdmi_json_dir_generator(path, dir_list)
        if cdmi_filters:
            filtered_gen = ((a, b(cdmi_filters[a])) for a, b in cdmi_json_gen
                            if a in cdmi_filters)
        else:
            filtered_gen = ((a, b()) for a, b in cdmi_json_gen)

        json_stream_wrapper = wrap_with_json_generator(filtered_gen)
        return Response(stream_with_context(json_stream_wrapper))

    elif request_wants_json():
        return flask_jsonify(dirlist=create_dirlist_dict(dir_list, path))
    else:
        return render_template('dirlisting.html',
                               dirlist=dir_list,
                               path=path,
                               parent_path=common.split_path(path)[0])
Пример #17
0
def del_cdmi_file_obj(path):
    """Delete a file through CDMI."""

    try:
        storage.rm(path)
    except storage.NotFoundException as e:
        return e.msg, 404
    except storage.NotAuthorizedException as e:
        return e.msg, 401
    except storage.ConflictException as e:
        return e.msg, 409
    except storage.StorageException as e:
        return e.msg, 500

    if request_wants_cdmi_object():
        empty_response = Response(status=204)
        del empty_response.headers['content-type']
        return empty_response
    elif request_wants_json():
        return flask_jsonify(delete='Deleted: %s' % (path)), 204
    else:
        return 'Deleted: %s' % (path), 204
Пример #18
0
def get_container_capabilities():
    cdmi_container_capabilities = {
        'cdmi_list_children': True,
        'cdmi_list_children_range': True,
        'cdmi_read_metadata': True,
        'cdmi_modify_metadata': False,
        'cdmi_create_dataobject': True,
        'cdmi_post_dataobject': False,
        'cdmi_create_container': True,
        'cdmi_create_reference': False,
        'cdmi_export_container_webdav': False,
        'cdmi_delete_container': True,
        'cdmi_move_container': False,
        'cdmi_copy_container': False,
        'cdmi_move_dataobject': False,
        'cdmi_copy_dataobject': True,
    }

    cdmi_storage_capabilities = {
        'cdmi_size': False,
    }

    cdmi_container_capabilities.update(cdmi_storage_capabilities)

    cdmi_capabilities_envelope = {
        'objectType': 'application/cdmi-capability',
        'objectID': None,
        'objectName': 'container/',
        'parentURI': '/cdmi_capabilities/',
        'parentID': None,
        'capabilities': cdmi_container_capabilities,
        'childrenrange': '0-0',
        'children': [],
    }

    return flask_jsonify(cdmi_capabilities_envelope)
Пример #19
0
def a_json_endpoint():
    """Returns a simple JSON document.
    ---
    tags:
      - Response formats
    produces:
      - application/json
    responses:
      200:
        description: An JSON document.
    """
    return flask_jsonify(
        slideshow={
            "title":
            "Sample Slide Show",
            "date":
            "date of publication",
            "author":
            "Yours Truly",
            "slides": [
                {
                    "type": "all",
                    "title": "Wake up to WonderWidgets!"
                },
                {
                    "type":
                    "all",
                    "title":
                    "Overview",
                    "items": [
                        "Why <em>WonderWidgets</em> are great",
                        "Who <em>buys</em> WonderWidgets",
                    ],
                },
            ],
        })
Пример #20
0
def handle_not_implemented_error(error):
    response = flask_jsonify(message="API endpoint not yet implemented.",
                             type='api_error')
    response.status_code = 501
    return response
Пример #21
0
def handle_input_error(error):
    response = flask_jsonify(message=error.message,
                             type='invalid_request_error')
    response.status_code = error.status_code
    return response
Пример #22
0
 def _wrapped(*args, **kwargs):
     from flask import jsonify as flask_jsonify
     result_dict = f(*args, **kwargs)
     return flask_jsonify(**result_dict), {'Cache-Control': 'no-store'}
Пример #23
0
def handle_generic_error(error):
    log_exception(sys.exc_info())
    response = flask_jsonify(message=error.message, type='api_error')
    response.status_code = 500
    return response
Пример #24
0
 def exception_handler(e):
     logger.exception(e)
     return (
         flask_jsonify(dict(exception=e.__class__.__name__, message=e.message, code=getattr(e, "error_code", 0))),
         500,
     )
Пример #25
0
def jsonify(*args, **kwargs):
    return flask_jsonify(*args, **kwargs)
Пример #26
0
def preview_entry(resource_id):
    data = request.get_json()
    preview = entrywrite.preview_entry(resource_id, data)
    return flask_jsonify(preview)
Пример #27
0
def jsonify(obj):
    return flask_jsonify(json(obj))
Пример #28
0
def jsonify(*args, **kwargs):
    if args and len(args) == 1 and not kwargs and isinstance(args[0], list):
        s = json.dumps(args[0])
        return Response(s, mimetype='application/json')
    else:
        return flask_jsonify(*args, **kwargs)
Пример #29
0
def get_domain(domain):
    return flask_jsonify('We dont support domains just yet')
Пример #30
0
def jsonify(*args, **kwargs):
    rv = dict(*args, **kwargs)
    if 'status' not in rv:
        rv['status'] = 'ok'
    return flask_jsonify(rv)
Пример #31
0
def jsonify(*args, **kwargs):
    if len(args) == 1 and type(args[0]) in (list, tuple):
        return current_app.response_class(json.dumps(
            args[0], indent=None if request.is_xhr else 2),
                                          mimetype='application/json')
    return flask_jsonify(*args, **kwargs)
Пример #32
0
def jsonify(obj):
    if '_id' in obj:
        del obj['_id']
    return flask_jsonify(obj)
Пример #33
0
def jsonify(response, status_code):
    jsonified_response = flask_jsonify(response)
    jsonified_response.status_code = status_code
    return jsonified_response
Пример #34
0
 def _wrapped(*args, **kwargs):
     from flask import jsonify as flask_jsonify
     result_dict = f(*args, **kwargs)
     return flask_jsonify(**result_dict), {'Cache-Control': 'no-store'}
Пример #35
0
def user_snslogin():
    '''
    第三方登录
    URL:/user/snslogin
    POST 参数:
        sns -- 第三方平台 1新浪 2QQ 3微信
        uid -- 第三方UID
        username -- 第三方昵称
        token -- 第三方token
        avaurl -- 头像
    返回值
        {'token':,'isbind':1} 成功
        isbind=1 已绑定 0未绑定
        ret=-5 系统异常
    '''
    try:
        data = request.get_json()
        sns = common.strtoint(data['sns'], 0)
        uid = data['uid']
        name = data['username']
        token = data['token']
        avaurl = data['avaurl']
        if sns > 0:
            user = User.snslogin(sns, uid)
            if user is not None:
                user = User.objects(_id=user._id).first()
                login_user(user, True)
            else:
                col1 = User()
                col1.role_id = 3
                col1._id = collection.get_next_id('users')
                col1.name = name
                col1.password = ''
                col1.avaurl = avaurl
                sn = SNS()
                sn.token = token
                if sns == 1:
                    sn.sina = uid
                    col1.username = '******'
                elif sns == 2:
                    sn.qq = uid
                    col1.username = '******'
                elif sns == 3:
                    sn.weixin = uid
                    col1.username = '******'
                col1.sns = sn
                retjson = rong_api.call_api(action="/user/getToken",
                                            params={
                                                "userId": str(col1._id),
                                                "name": col1.name,
                                                "portraitUri": col1.avaurl
                                            })
                if retjson['code'] == 200:
                    col1.rong_token = retjson['token']
                col1.saveinfo_snslogin()
                user = User.snslogin(sns, uid)
                #user = User.objects(_id=user._id).first()
                login_user(user, True)
            return flask_jsonify({
                'token':
                user.generate_auth_token(expiration=2592000),
                'rong_token':
                col1.rong_token,
                'expiration':
                2592000,
                '_id':
                user._id,
                'isbind':
                len(user.username) == 11 and 1 or 0
            })
        #return jsonify(ret=1)#添加成功
    except Exception, e:
        logging.debug(e)
        return jsonify(ret=-5)  #系统异常
Пример #36
0
def user_snslogin():
    '''
    第三方登录
    URL:/user/snslogin
    POST 参数:
        sns -- 第三方平台 1新浪 2QQ 3微信
        uid -- 第三方UID
        username -- 第三方昵称
        token -- 第三方token
        avaurl -- 头像
    返回值
        {'token':,'isbind':1} 成功
        isbind=1 已绑定 0未绑定
        ret=-5 系统异常
    '''
    try:
        data = request.get_json()
        sns = common.strtoint(data['sns'],0)
        uid = data['uid']
        name = data['username']
        token = data['token']
        avaurl = data['avaurl']
        if sns>0:
            user = User.snslogin(sns,uid)
            if user is not None:
                user = User.objects(_id=user._id).first()
                login_user(user, True)
            else:
                col1 = User()
                col1.role_id = 3
                col1._id = collection.get_next_id('users')
                col1.name = name
                col1.password = ''
                col1.avaurl = avaurl
                sn = SNS()
                sn.token = token
                if sns==1:
                    sn.sina = uid
                    col1.username = '******'
                elif sns==2:
                    sn.qq = uid
                    col1.username = '******'
                elif sns==3:
                    sn.weixin = uid
                    col1.username = '******'
                col1.sns = sn
                retjson = rong_api.call_api(
                    action="/user/getToken",
                    params={
                        "userId": str(col1._id),
                        "name":col1.name,
                        "portraitUri":col1.avaurl
                    }
                )
                if retjson['code']==200:
                    col1.rong_token = retjson['token']
                col1.saveinfo_snslogin()
                user = User.snslogin(sns,uid)
                #user = User.objects(_id=user._id).first()
                login_user(user, True)
            return flask_jsonify({'token': user.generate_auth_token(expiration=2592000),'rong_token':col1.rong_token, 'expiration': 2592000,'_id': user._id,'isbind':len(user.username)==11 and 1 or 0})
        #return jsonify(ret=1)#添加成功
    except Exception,e:
        logging.debug(e)
        return jsonify(ret=-5)#系统异常
Пример #37
0
 def wrapped(*args, **kwargs):
     obj = f(*args, **kwargs)
     if type(obj) in (Response, PagedResponse, Error):
         obj = obj.to_dict()
     return flask_jsonify(obj)
Пример #38
0
def handle_input_error(error):
    response = flask_jsonify(message=error.message,
                             type='invalid_request_error')
    response.status_code = error.status_code
    return response
Пример #39
0
def jsonify(*args, **kwargs):
    kwargs.setdefault('flashes', get_flashed_messages(with_categories=True))
    return flask_jsonify(*args, **kwargs)
Пример #40
0
def jsonify(*args, **kwargs):
    kwargs.setdefault('flashes', get_flashed_messages(with_categories=True))
    return flask_jsonify(*args, **kwargs)
Пример #41
0
def handle_not_implemented_error(error):
    response = flask_jsonify(message="API endpoint not yet implemented.",
                             type='api_error')
    response.status_code = 501
    return response
Пример #42
0
def handle_value_error(error):
    logger.error(f'caught value error: {error!r}')
    response = flask_jsonify(message=error.args[0])
    response.status_code = 400
    return response
Пример #43
0
def handle_activitypub_error(error):
    logger.error(f'caught activitypub error {error!r}')
    response = flask_jsonify(error.to_dict())
    response.status_code = error.status_code
    return response
Пример #44
0
def wellknown_nodeinfo():
    return flask_jsonify(links=[{
        'rel': 'http://nodeinfo.diaspora.software/ns/schema/2.0',
        'href': f'{ID}/nodeinfo',
    }], )
Пример #45
0
def jsonify():
    return flask_jsonify()
Пример #46
0
def api_user_key():
    return flask_jsonify(api_key=ADMIN_API_KEY)
Пример #47
0
def handle_input_error(error):
    response = flask_jsonify(message=str(error), type='api_error')
    response.status_code = 400
    return response
Пример #48
0
def get_entries_by_id(resource_id: str, entry_ids: str):
    response = search.search_ids(request.args, resource_id, entry_ids)
    return flask_jsonify(response)
Пример #49
0
def jsonify(*args, **kwargs):
    response = flask_jsonify(*args, **kwargs)
    if not response.data.endswith(b'\n'):
        response.data += b'\n'
    return response
Пример #50
0
def handle_input_error(error):
    response = flask_jsonify(message=str(error), type='api_error')
    response.status_code = 400
    return response
Пример #51
0
def jsonify(*args, **kwargs):
    response = flask_jsonify(*args, **kwargs)
    if not response.data.endswith(b"\n"):
        response.data += b"\n"
    app.logger.info(response.get_data(as_text=True))
    return response
Пример #52
0
def jsonify(obj):
    filtered_obj = jsonify_filter(obj)

    return flask_jsonify(filtered_obj)
Пример #53
0
def jsonify(*args, **kwargs):
    response = flask_jsonify(*args, **kwargs)
    if not response.data.endswith(b'\n'):
        response.data += b'\n'
    return response
Пример #54
0
def jsonify():
    return flask_jsonify()