How to use the djangorestframework.views.View function in djangorestframework

To help you get started, we’ve selected a few djangorestframework 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 srri / OpenRelay / apps / server_talk / views.py View on Github external
'comment': local_node.comment,
            }
            return local_node_info
        else:
            return Response(status.PARTIAL_CONTENT)


class Heartbeat(View):
    def post(self, request):
        uuid = request.GET.get('uuid')
        # TODO: Reject call from non verified nodes
        logger.info('received heartbeat call from node: %s @ %s' % (uuid, request.META['REMOTE_ADDR']))
        return {'cpuload': CPUsage()}


class InventoryHash(View):
    def post(self, request):
        uuid = request.GET.get('uuid')
        # TODO: Reject call from non verified nodes
        logger.info('received inventory hash call from node: %s @ %s' % (uuid, request.META['REMOTE_ADDR']))
        return {'inventory_hash': HASH_FUNCTION(u''.join([version.full_uuid for version in Version.objects.all().order_by('timestamp')]))}
     
        
# Interactive views - user
def join(request):
    if request.method == 'POST':
        form = JoinForm(request.POST)
        if form.is_valid():
            try:
                entry_point = RemoteCall(
                    ip_address=form.cleaned_data['ip_address'],
                    port=form.cleaned_data['port']
github devilry / devilry-django / src / devilry_subjectadmin / devilry_subjectadmin / rest / deadlinesbulk.py View on Github external
group_ids = ListOfTypedField(required=False,
                                 coerce=int,
                                 help_text='List of group IDs (int).')


class CreateOrUpdateResource(FormResource):
    form = CreateOrUpdateForm

    def validate_request(self, data, files=None):
        if 'bulkdeadline_id' in data:
            del data['bulkdeadline_id']
        return super(CreateOrUpdateResource, self).validate_request(data, files)



class DeadlinesBulkListOrCreate(View):
    """
    Handle deadlines on an assignment in bulk.

    # About bulkdeadline_id
    The ``bulkdeadline_id`` is a generated string on this format:

        --

    - ```` is the datetime of the deadaline formatted as
      ``YYYY-MM-DDThh_mm_ss``.
    - ```` is the hexdigested SHA-1 encoded deadline text (40
      characters). If the deadline text is ``null`` or empty string,
      ```` will be an empty string.

    # GET
    List all deadlines on an assignment with newest deadline firsts. Deadlines
github srri / OpenRelay / apps / server_talk / views.py View on Github external
class OpenRelayAPI(View):
    """
    This is the REST API for OpenRelay (https://github.com/Captainkrtek/OpenRelay).
    """

    def get(self, request):
        return [
            {'name': 'Resources', 'url': reverse('resource_file-root')},
            {'name': 'Versions', 'url': reverse('version-root')},
            {'name': 'Announce', 'url': reverse('service-announce')},
            {'name': 'Heartbeat', 'url': reverse('service-heartbeat')},
            {'name': 'Inventory hash', 'url': reverse('service-inventory_hash')},
        ]


class ResourceFileRoot(View):
    def post(self, request):
        return [
            {
                'uuid': resource.uuid,
                'url': reverse('resource_file', args=[resource.uuid]),
            }
            for resource in Resource.objects.all()
        ]
    

class ResourceFileObject(View):
    def post(self, request, uuid):
        resource = get_object_or_404(Resource, uuid=uuid)
        return {
            'uuid': resource.uuid,
            'name': resource.name,
github tranvictor / truongnha / api / views.py View on Github external
date_parts[0],
                            date_parts[1],
                            date_parts[2],
                            api_called=True,
                            data=data)
                if response.status_code == 200:
                    return Response(status.HTTP_200_OK)
                else:
                    return Response(status.HTTP_400_BAD_REQUEST)
            except Exception as e:
                print e
                raise e
        else:
            return Response(status.HTTP_403_FORBIDDEN)

class Subject(View):
    @need_login
    @school_function
    def get(self, request, class_id):
        try:
            cl = Class.objects.get(id=class_id)
        except ObjectDoesNotExist:
            return Response(status=status.HTTP_404_NOT_FOUND)
        subjects = cl.subject_set.all()
        result = []
        for s in subjects:
            result.append({
                'name': s.name,
                'type': s.type,
                'hs': s.hs,
                'nx': s.nx,
                'primary': s.primary,
github tranvictor / truongnha / api / views.py View on Github external
if homeroom_class.teacher_id:
                                temp['homeTeacher'] = homeroom_class.teacher_id.full_name()
                            classes.append(temp)
                    result['teaching_class'] = classes

                except Exception as e:
                    print e
                    raise e
            elif user_position > 3:
                #TODO: return necessary information for school's admins
                return Response(status=status.HTTP_404_NOT_FOUND)
            return Response(status=status.HTTP_200_OK, content= result)
        else:
            return Response(status.HTTP_401_UNAUTHORIZED)

class ApiLogout(View):
    def get(self, request):
        logout(request=request)
        return Response(status=status.HTTP_200_OK)

class ApiGetStudentList(View):
    def get(self, request,
            class_id,
            day=None,
            month=None,
            year=None,
            all=False):
        if request.user.is_anonymous():
            return Response(status=status.HTTP_401_UNAUTHORIZED)
        position = get_position(request)
        if position >=3:
            try:
github encode / django-rest-framework / examples / permissionsexample / views.py View on Github external
"""

    def get(self, request):
        return [
            {
                'name': 'Throttling Example',
                'url': reverse('throttled-resource', request=request)
            },
            {
                'name': 'Logged in example',
                'url': reverse('loggedin-resource', request=request)
            },
        ]


class ThrottlingExampleView(View):
    """
    A basic read-only View that has a **per-user throttle** of 10 requests per minute.

    If a user exceeds the 10 requests limit within a period of one minute, the
    throttle will be applied until 60 seconds have passed since the first request.
    """

    permissions = (PerUserThrottling,)
    throttle = '10/min'

    def get(self, request):
        """
        Handle GET requests.
        """
        return "Successful response to GET request because throttle is not yet active."
github devilry / devilry-django / src / devilry_authenticateduserinfo / devilry_authenticateduserinfo / rest.py View on Github external
from djangorestframework.views import View
from djangorestframework.permissions import IsAuthenticated

from devilry.apps.core.models.devilryuserprofile import user_is_nodeadmin
from devilry.apps.core.models.devilryuserprofile import user_is_subjectadmin
from devilry.apps.core.models.devilryuserprofile import user_is_periodadmin
from devilry.apps.core.models.devilryuserprofile import user_is_assignmentadmin
from devilry.apps.core.models.devilryuserprofile import user_is_student
from devilry.apps.core.models.devilryuserprofile import user_is_examiner




class UserInfo(View):
    """
    Provides an API that lists information about the authenticated user.

    # GET
    An object with the following attributes:

    - ``id`` (int): Internal Devilry ID. Is never ``null``, and unlike the username, this is never changed.
    - ``username`` (string): The unique Devilry username for this user. Is never ``null``, however it may be changed by a superuser.
    - ``full_name`` (string|null): The full name of the user.
    - ``email`` (string|null): The email address of the user.
    - ``languagecode`` (string|null): The languagecode of the preferred language.
    - ``is_superuser`` (boolean): Is the user a superuser?
    - ``is_nodeadmin`` (boolean): Is the user admin directly on any Node?
    - ``is_subjectadmin`` (boolean): Is the user admin directly on any Subject?
    - ``is_periodadmin`` (boolean): Is the user admin directly on any Period?
    - ``is_assignmentadmin`` (boolean): Is the user admin directly on any Assignment?
github encode / django-rest-framework / examples / objectstore / views.py View on Github external
def get_filename(key):
    """
    Given a stored object's key returns the file's path.
    """
    return os.path.join(OBJECT_STORE_DIR, key)


def get_file_url(key, request):
    """
    Given a stored object's key returns the URL for the object.
    """
    return reverse('stored-object', kwargs={'key': key}, request=request)


class ObjectStoreRoot(View):
    """
    Root of the Object Store API.
    Allows the client to get a complete list of all the stored objects, or to create a new stored object.
    """

    def get(self, request):
        """
        Return a list of all the stored object URLs. (Ordered by creation time, newest first)
        """
        filepaths = [os.path.join(OBJECT_STORE_DIR, file)
                     for file in os.listdir(OBJECT_STORE_DIR)
                     if not file.startswith('.')]
        ctime_sorted_basenames = [item[0] for item in sorted([(os.path.basename(path), os.path.getctime(path)) for path in filepaths],
                                                             key=operator.itemgetter(1), reverse=True)]
        return [get_file_url(key, request) for key in ctime_sorted_basenames]
github devilry / devilry-django / src / devilry_qualifiesforexam / devilry_qualifiesforexam / rest / preview.py View on Github external
from djangorestframework.views import View
from djangorestframework.permissions import IsAuthenticated
from djangorestframework.response import ErrorResponse
from djangorestframework import status as statuscodes
from django.shortcuts import get_object_or_404

from devilry_qualifiesforexam.pluginhelpers import create_sessionkey
from devilry.apps.core.models import Period
from devilry.utils.groups_groupedby_relatedstudent_and_assignment import GroupsGroupedByRelatedStudentAndAssignment
from devilry_subjectadmin.rest.auth import IsPeriodAdmin
from devilry_qualifiesforexam.pluginhelpers import PreviewData


class Preview(View):
    """
    Generate the data required to provide a preview for the qualified for exam wizard.

    # GET

    ## Parameters
    The following parameters are required:

    - ``periodid``: The ID of the period. Supplied as the last part of the URL-path.
      404 is returned unless the user is admin on this period.
    - ``pluginsessionid``: Forwarded from the first page of the wizard. It is an ID
      used to lookup the output from the plugin, included in the listing in the plugins
      REST API.

    ## Returns
    An object/dict with the following attributes:
github srri / OpenRelay / apps / server_talk / views.py View on Github external
HASH_FUNCTION = lambda x: hashlib.sha256(x).hexdigest()


def _get_object_or_404(model, *args, **kwargs):
    '''
    Custom get_object_or_404 as the Django one call .get() method on a
    QuerySet thus ignoring a custom manager's .get() method
    '''
    try:
        return model.objects.get(*args, **kwargs)
    except model.DoesNotExist:
        raise Http404('No %s matches the given query.' % model._meta.object_name)


# API views
class OpenRelayAPI(View):
    """
    This is the REST API for OpenRelay (https://github.com/Captainkrtek/OpenRelay).
    """

    def get(self, request):
        return [
            {'name': 'Resources', 'url': reverse('resource_file-root')},
            {'name': 'Versions', 'url': reverse('version-root')},
            {'name': 'Announce', 'url': reverse('service-announce')},
            {'name': 'Heartbeat', 'url': reverse('service-heartbeat')},
            {'name': 'Inventory hash', 'url': reverse('service-inventory_hash')},
        ]


class ResourceFileRoot(View):
    def post(self, request):