Beispiel #1
0
def update_single_model(request, model_name):
    """Handles "PATCH /model_name/id" requests, updating the instance if
    the data validates.

    :param request: The request to handle
    :type request: :class:`~pyramid.request.Request`
    :param model_name: The name of the model to load
    :type model_name: ``unicode``
    :return: The JSON API response
    :rtype: ``dict``
    """
    dbsession = DBSession()
    data = JSONAPIValidator(not_empty=True).to_python(request.body)
    item = dbsession.query(COMPONENTS[model_name]['class']).filter(COMPONENTS[model_name]['class'].id == request.matchdict['iid']).first()
    if item:
        if item.allow(request.current_user, 'edit'):
            with transaction.manager:
                dbsession.add(item)
                item.update_from_dict(data, dbsession)
                dbsession.flush()
                item_data, item_included = item.as_dict(request=request)
                response = {'data': item_data}
                if item_included:
                    response['included'] = filter_list(item_included)
            return response
        else:
            raise_json_exception(HTTPUnauthorized)
    else:
        raise_json_exception(HTTPNotFound)
Beispiel #2
0
def login(request):
    """Route handler for the special "login" route."""
    dbsession = DBSession()
    try:
        params = LoginUserSchema().to_python(request.POST,
                                             State(dbsession=dbsession))
        user = dbsession.query(User).filter(
            User.email == params['email']).first()
        return {'user': user.as_dict()[0]}
    except Invalid as e:
        raise_json_exception(HTTPClientError, body=invalid_to_error_list(e))
Beispiel #3
0
def handle_relationship(request):
    """Handles "/model_name/id/relationship" requests, dispatching to :func:`~webrpg.api.handle_fetch_relationship`
    depending on the request method.

    :param request: The request to handle
    :type request: :class:`~pyramid.request.Request`
    :return: The JSON API response
    :rtype: ``dict``
    """
    model_name = request.matchdict['model']
    if model_name in COMPONENTS:
        if request.method == 'GET':
            return handle_fetch_relationship(request, model_name)
        else:
            raise raise_json_exception(HTTPMethodNotAllowed)
    else:
        raise_json_exception(HTTPNotFound)
Beispiel #4
0
def handle_item(request):
    """Handles "/model_name/id" requests, dispatching to :func:`~webrpg.api.handle_single_model`,
    :func:`~webrpg.api.update_single_model`, or :func:`~webrpg.api.delete_single_model` functions
    depending on the request method.

    :param request: The request to handle
    :type request: :class:`~pyramid.request.Request`
    :return: The JSON API response
    :rtype: ``dict``
    """
    model_name = request.matchdict['model']
    if model_name in COMPONENTS:
        if request.method == 'GET' and 'item' in COMPONENTS[model_name]['actions']:
            return handle_single_model(request, model_name)
        elif request.method == 'PATCH' and 'update' in COMPONENTS[model_name]['actions']:
            return update_single_model(request, model_name)
        elif request.method == 'DELETE' and 'delete' in COMPONENTS[model_name]['actions']:
            return delete_single_model(request, model_name)
        else:
            raise raise_json_exception(HTTPMethodNotAllowed)
    else:
        raise_json_exception(HTTPNotFound)
Beispiel #5
0
def handle_single_model(request, model_name):
    """Handles "GET /model_name/id" requests.

    :param request: The request to handle
    :type request: :class:`~pyramid.request.Request`
    :param model_name: The name of the model to load
    :type model_name: ``unicode``
    :return: The JSON API response
    :rtype: ``dict``
    """
    dbsession = DBSession()
    item = dbsession.query(COMPONENTS[model_name]['class']).filter(COMPONENTS[model_name]['class'].id == request.matchdict['iid']).first()
    if item:
        if item.allow(request.current_user, 'view'):
            item_data, item_included = item.as_dict(request=request)
            response = {'data': item_data}
            if item_included:
                response['included'] = filter_list(item_included)
            return response
        else:
            raise_json_exception(HTTPUnauthorized)
    else:
        raise_json_exception(HTTPNotFound)
Beispiel #6
0
def handle_collection(request):
    """Handles requests to the collection URL /model_name, dispatching to
    :func:`~webrpg.views.api.handle_list_model` or :func:`~webrpg.views.api.handle_new_model`
    depending on the request method.

    :param request: The request to handle
    :type request: :class:`~pyramid.request.Request`
    :return: The JSON API response
    :rtype: ``dict``
    """
    model_name = request.matchdict['model']
    if model_name in COMPONENTS:
        try:
            if request.method == 'GET' and 'list' in COMPONENTS[model_name]['actions']:
                return handle_list_model(request, model_name)
            elif request.method == 'POST' and 'new' in COMPONENTS[model_name]['actions']:
                return handle_new_model(request, model_name)
            else:
                raise raise_json_exception(HTTPMethodNotAllowed)
        except Invalid as e:
            raise_json_exception(HTTPClientError, body=invalid_to_error_list(e))
    else:
        raise_json_exception(HTTPNotFound)
Beispiel #7
0
def handle_fetch_relationship(request, model_name):
    """Handles "GET /model_name/id/relationship" requests, returning all models for the given
    relationship for the model item, if the user has permission to view the item.

    :param request: The request to handle
    :type request: :class:`~pyramid.request.Request`
    :param model_name: The name of the model to load
    :type model_name: ``unicode``
    :return: The JSON API response
    :rtype: ``dict``
    """
    dbsession = DBSession()
    item = dbsession.query(COMPONENTS[model_name]['class']).filter(COMPONENTS[model_name]['class'].id == request.matchdict['iid']).first()
    if item:
        if item.allow(request.current_user, 'view'):
            rel_name = request.matchdict['rid']
            if hasattr(item, '__json_relationships__') and rel_name in item.__json_relationships__:
                try:
                    response = {'data': [],
                                'included': []}
                    for rel in getattr(item, rel_name):
                        if rel and rel.allow(request.current_user, 'view'):
                            rel_data, rel_included = rel.as_dict(request=request)
                            response['data'].append(rel_data)
                            response['included'].extend(rel_included)
                except:
                    rel = getattr(item, rel_name)
                    if rel and rel.allow(request.current_user, 'view'):
                        rel_data, rel_included = rel.as_dict(request=request)
                        response = {'data': rel_data,
                                    'included': rel_included}
                    else:
                        response = {'data': {},
                                    'included': []}
                if response['included']:
                    response['included'] = filter_list(response['included'])
                else:
                    del response['included']
                return response
            else:
                raise_json_exception(HTTPUnauthorized)
        else:
            raise_json_exception(HTTPNotFound)
    else:
        raise_json_exception(HTTPNotFound)
Beispiel #8
0
def delete_single_model(request, model_name):
    """Handles "DELETE /model_name/id" requests, deleting the instance if the
    user has the necessary permissions.

    :param request: The request to handle
    :type request: :class:`~pyramid.request.Request`
    :param model_name: The name of the model to load
    :type model_name: ``unicode``
    :return: The JSON API response
    :rtype: ``dict``
    """
    dbsession = DBSession()
    item = dbsession.query(COMPONENTS[model_name]['class']).filter(COMPONENTS[model_name]['class'].id == request.matchdict['iid']).first()
    if item:
        if item.allow(request.current_user, 'delete'):
            with transaction.manager:
                dbsession.delete(item)
            raise_json_exception(HTTPNoContent)
        else:
            raise_json_exception(HTTPUnauthorized)
    else:
        raise_json_exception(HTTPNotFound)