How to use the restless.dj.DjangoResource function in restless

To help you get started, we’ve selected a few restless examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github toastdriven / restless / tests / test_dj.py View on Github external
from django.core.exceptions import ObjectDoesNotExist

# Ugh. Settings for Django.
from django.conf import settings
settings.configure(DEBUG=True)

from restless.dj import DjangoResource
from restless.exceptions import Unauthorized
from restless.preparers import FieldsPreparer
from restless.resources import skip_prepare
from restless.utils import json

from .fakes import FakeHttpRequest, FakeModel


class DjTestResource(DjangoResource):
    preparer = FieldsPreparer(fields={
        'id': 'id',
        'title': 'title',
        'author': 'username',
        'body': 'content'
    })
    fake_db = []

    def __init__(self, *args, **kwargs):
        super(DjTestResource, self).__init__(*args, **kwargs)

        self.http_methods.update({
            'schema': {
                'GET': 'schema',
            }
        })
github toastdriven / restless / examples / django / posts / api.py View on Github external
from django.contrib.auth.models import User

from restless.dj import DjangoResource

from posts.models import Post


class PostResource(DjangoResource):
    fields = {
        'id': 'id',
        'title': 'title',
        'author': 'user.username',
        'body': 'content',
        'posted_on': 'posted_on',
    }

    def list(self):
        return Post.objects.all()

    def detail(self, pk):
        return Post.objects.get(id=pk)

    def create(self):
        return Post.objects.create(
github dbca-wa / oim-cms / oim_cms / api.py View on Github external
from tracking.api import EC2InstanceResource, FreshdeskTicketResource
from .utils import CSVDjangoResource


def recursive_node_to_dict(node):
    # http://stackoverflow.com/questions/12556268/fastest-way-to-create-json-to-reflect-a-tree-structure-in-python-django-using
    result = {
        'name': node.name, 'id': node.pk,
        'children': [recursive_node_to_dict(c) for c in node._cached_children]
    }
    if not result['children']:
        del result['children']
    return result


class OptionResource(DjangoResource):
    """Returns serialised lists of object data. Request parameter must include
    ``list`` value of a defined function (below), minus the ``data_`` prefix.
    Example:
    /api/options?list=org_structure
    """

    @skip_prepare
    def list(self):
        return getattr(self, 'data_' + self.request.GET['list'])()

    def data_org_structure(self):
        # Return the current org structure, excluding inactive OrgUnits.
        return [recursive_node_to_dict(cache_tree_children(dept.get_descendants_active(include_self=True))[0])
                for dept in OrgUnit.objects.filter(unit_type=0, active=True).order_by('name')]

    def data_cost_centre(self):
github dbca-wa / oim-cms / oim_cms / api.py View on Github external
return [i.name for i in OrgUnit.objects.filter(unit_type=0, active=True).order_by('name')]

    def data_branch(self):
        return [i.name for i in OrgUnit.objects.filter(unit_type=2, active=True).order_by('name')]

    def data_section(self):
        return [i.name for i in OrgUnit.objects.filter(unit_type=7, active=True).order_by('name')]

    def data_regiondistrict(self):
        return [i.name for i in OrgUnit.objects.filter(unit_type__in=[3, 6], active=True).order_by('name')]

    def data_office(self):
        return [i.name for i in OrgUnit.objects.filter(unit_type=5, active=True).order_by('name')]


class WhoAmIResource(DjangoResource):
    """
    whoami is a read only resource and does not require any request parameters.
    This resource can be used to return the authentication data by whoami request and auth request.
    so only one method 'detail' is required no matter which http method is used.
    """
    http_methods = {
        'list': {
            'GET': 'detail',
            'POST': 'detail',
            'PUT': 'detail',
            'DELETE': 'detail',
        },
        'detail': {
            'GET': 'detail',
            'POST': 'detail',
            'PUT': 'detail',
github dbca-wa / oim-cms / oim_cms / utils.py View on Github external
from django.http import HttpResponse
from djqscsv import render_to_csv_response
from restless.dj import DjangoResource


class CSVDjangoResource(DjangoResource):
    """Extend the restless DjangoResource class to add a CSV export endpoint.
    """
    @classmethod
    def as_csv(self, request):
        resource = self()
        if not hasattr(resource, "list_qs"):
            return HttpResponse(
                "list_qs not implemented for {}".format(self.__name__))
        resource.request = request
        return render_to_csv_response(
            resource.list_qs(), field_order=resource.VALUES_ARGS)


class FieldsFormatter(object):
    """
    A formatter object to format specified fields with a configured formatter
github vmesel / PyJobs / pyjobs / api / views.py View on Github external
from django.core.paginator import Paginator
from restless.dj import DjangoResource
from restless.exceptions import BadRequest
from restless.preparers import FieldsPreparer

from pyjobs.api.serializers import PyJobsSerializer
from pyjobs.core.models import Job


class DjangoPaginatedResource(DjangoResource):
    """This will be unnecessary with next restless versions. For instante,
    see this recent (2019) progress for details:
    https://github.com/toastdriven/restless/issues/78"""

    def serialize_list(self, data):
        if data is None:
            return super(DjangoResource, self).serialize_list(data)

        paginator = Paginator(data, self.page_size)
        page_number = self.request.GET.get("page", 1)
        if page_number not in paginator.page_range:
            raise BadRequest("Invalid page number")

        self.page = paginator.page(page_number)
        data = self.page.object_list
        return super(DjangoResource, self).serialize_list(data)
github dbca-wa / oim-cms / registers / api.py View on Github external
VALUES_ARGS = ()

    def prepare(self, data):
        # Exclude decommissioned systems from the list of systems returned.
        it_systems = data.itsystem_set.all().exclude(status=3)
        return {
            'hostname': data.computer.hostname,
            'role': data.get_role_display(),
            'it_systems': [i.name for i in it_systems],
        }

    def list(self):
        return ITSystemHardware.objects.all()


class ITSystemEventResource(DjangoResource):
    def __init__(self, *args, **kwargs):
        super(ITSystemEventResource, self).__init__(*args, **kwargs)
        self.http_methods.update({
            'current': {'GET': 'current'}
        })

    preparer = FieldsPreparer(fields={
        'id': 'id',
        'description': 'description',
        'planned': 'planned',
        'current': 'current',
    })

    def prepare(self, data):
        prepped = super(ITSystemEventResource, self).prepare(data)
        prepped['event_type'] = data.get_event_type_display()
github vmesel / PyJobs / pyjobs / api / views.py View on Github external
def serialize_list(self, data):
        if data is None:
            return super(DjangoResource, self).serialize_list(data)

        paginator = Paginator(data, self.page_size)
        page_number = self.request.GET.get("page", 1)
        if page_number not in paginator.page_range:
            raise BadRequest("Invalid page number")

        self.page = paginator.page(page_number)
        data = self.page.object_list
        return super(DjangoResource, self).serialize_list(data)
github toastdriven / restless / restless / dj.py View on Github external
def as_detail(self, *args, **kwargs):
        return csrf_exempt(super(DjangoResource, self).as_detail(*args, **kwargs))
github dbca-wa / oim-cms / organisation / api.py View on Github external
def format_position_type(request, value):
    position_type = dict(DepartmentUser.POSITION_TYPE_CHOICES)
    if value is not None:
        return position_type[value]
    else:
        return value


def format_account_type(request, value):
    if value is not None:
        return ACCOUNT_TYPE_DICT[value]
    else:
        return value


class DepartmentUserResource(DjangoResource):
    """An API Resource class to represent DepartmentUser objects.
    This class is used to create & update synchronised user account data from
    Active Directory.
    It also includes custom endpoints to return the P&W organisation
    structure membership.
    """
    COMPACT_ARGS = (
        'pk', 'name', 'title', 'employee_id', 'email', 'telephone',
        'mobile_phone', 'extension', 'photo', 'photo_ad', 'org_data', 'parent__email',
        'parent__name', 'username', 'org_unit__location__id',
        'org_unit__location__name', 'org_unit__location__address',
        'org_unit__location__pobox', 'org_unit__location__phone',
        'org_unit__location__fax', 'ad_guid',
        'org_unit__secondary_location__name', 'preferred_name',
        'expiry_date')
    VALUES_ARGS = COMPACT_ARGS + (