Beispiel #1
0
 def object_data_format(self, request, resource_name, primary_key, format='html', *args, **kwargs):
     """
     Object data
     """
     
     log.debug('object_data_format()')
     
     try:
         resource = self.registry[resource_name]
     except KeyError:
         error_msg = "Sorry, but no resource with the name <span class='loud'>{0}</span> has been registered with Fulcrum.".format(resource_name)
         return render_to_response('fulcrum/404_fulcrum.html',
                                   { 'error_msg': error_msg },
                                   context_instance=RequestContext(request))
     
     if format == 'html':
         try:
             object = resource.object_by_pk(primary_key)
         except:
             error_msg = "Sorry, but Fulcrum can't find an object with a primary key of <span class='loud'>{0}</span>.".format(primary_key)
             return render_to_response('fulcrum/404_fulcrum.html',
                                       { 'error_msg': error_msg },
                                       context_instance=RequestContext(request))
         return render_to_response('fulcrum/object_detail.html',
                                   { 'object': object },
                                   context_instance=RequestContext(request))
     else:
         return resource.handle(request, pk=primary_key, emitter_format=format)
Beispiel #2
0
    def resource_data_format(self,
                             request,
                             resource_name,
                             format='html',
                             *args,
                             **kwargs):
        """
        Resource data
        """

        log.debug('resource_data_format(): %s' % format)

        for k, v in request.GET.items():
            kwargs[str(k)] = str(v)

        try:
            resource = self.registry[resource_name]
        except KeyError:
            error_msg = "Sorry, but no resource with the name <span class='loud'>{0}</span> has been registered with Fulcrum.".format(
                resource_name)
            return render_to_response('fulcrum/404_fulcrum.html',
                                      {'error_msg': error_msg},
                                      context_instance=RequestContext(request))

        return resource.handle(request, emitter_format=format, *args, **kwargs)
Beispiel #3
0
    def resource_api(self, request, resource_name, *args, **kwargs):
        """
        Resource API handler
        """

        log.debug('resource_api()')

        try:
            resource = self.registry[resource_name]
        except KeyError:
            error_msg = "Sorry, but no resource with the name <span class='loud'>{0}</span> has been registered with Fulcrum.".format(
                resource_name)
            return render_to_response('fulcrum/404_fulcrum.html',
                                      {'error_msg': error_msg},
                                      context_instance=RequestContext(request))

        protocol = request.META['SERVER_PROTOCOL'].split('/')[0].lower()
        host = request.META['HTTP_HOST']
        path_info = request.META['PATH_INFO'].lstrip('/').rstrip('/api')
        example_uri = '%s://%s/%s' % (protocol, host, path_info)

        return render_to_response('fulcrum/resource_api.html', {
            'resource': resource,
            'handler': resource.handler,
            'example_uri': example_uri
        },
                                  context_instance=RequestContext(request))
Beispiel #4
0
 def data_schema(self):
     log.debug('data_schema')
     return {
         'description':
         BaseArbitraryHandler.__doc__,
         'handler':
         BaseArbitraryHandler.__name__,
         'params':
         'You must override data_schema method to provide necessary parameters.',
         'return_value':
         'You must override data_schema method to provide expected return value.'
     }
Beispiel #5
0
 def index(self, request):
     """
     Renders index page view for fulcrum. Lists all registered resources.
     """
     
     log.debug('index()')
     
     r_list = [{'group': resource.group, 'resource': resource } for resource in self.registry.values()]
     
     return render_to_response('fulcrum/homepage.html',
                               { 'resource_list': r_list },
                               context_instance=RequestContext(request))
Beispiel #6
0
    def index(self, request):
        """
        Renders index page view for fulcrum. Lists all registered resources.
        """

        log.debug('index()')

        r_list = [{
            'group': resource.group,
            'resource': resource
        } for resource in self.registry.values()]

        return render_to_response('fulcrum/homepage.html',
                                  {'resource_list': r_list},
                                  context_instance=RequestContext(request))
Beispiel #7
0
 def resource_schema(self, request, resource_name, format, *args, **kwargs):
     """
     Resource schema handler
     """
     
     log.debug('resource_schema()')
     
     try:
         resource = self.registry[resource_name]
     except KeyError:
         error_msg = "Sorry, but no resource with the name <span class='loud'>{0}</span> has been registered with Fulcrum.".format(resource_name)
         return render_to_response('fulcrum/404_fulcrum.html',
                                   { 'error_msg': error_msg },
                                   context_instance=RequestContext(request))
         #raise http.Http404("This resource has not been registered with fulcrum.")
     
     return resource.get_schema_view(format)
Beispiel #8
0
    def resource_schema(self, request, resource_name, format, *args, **kwargs):
        """
        Resource schema handler
        """

        log.debug('resource_schema()')

        try:
            resource = self.registry[resource_name]
        except KeyError:
            error_msg = "Sorry, but no resource with the name <span class='loud'>{0}</span> has been registered with Fulcrum.".format(
                resource_name)
            return render_to_response('fulcrum/404_fulcrum.html',
                                      {'error_msg': error_msg},
                                      context_instance=RequestContext(request))
            #raise http.Http404("This resource has not been registered with fulcrum.")

        return resource.get_schema_view(format)
Beispiel #9
0
 def resource_data_format(self, request, resource_name, format='html', *args, **kwargs):
     """
     Resource data
     """
     
     log.debug('resource_data_format(): %s' % format)
     
     for k, v in request.GET.items():
         kwargs[str(k)] = str(v)
     
     try:
         resource = self.registry[resource_name]
     except KeyError:
         error_msg = "Sorry, but no resource with the name <span class='loud'>{0}</span> has been registered with Fulcrum.".format(resource_name)
         return render_to_response('fulcrum/404_fulcrum.html',
                                   { 'error_msg': error_msg },
                                   context_instance=RequestContext(request))
     
     return resource.handle(request, emitter_format=format, *args, **kwargs)
Beispiel #10
0
    def object_data_format(self,
                           request,
                           resource_name,
                           primary_key,
                           format='html',
                           *args,
                           **kwargs):
        """
        Object data
        """

        log.debug('object_data_format()')

        try:
            resource = self.registry[resource_name]
        except KeyError:
            error_msg = "Sorry, but no resource with the name <span class='loud'>{0}</span> has been registered with Fulcrum.".format(
                resource_name)
            return render_to_response('fulcrum/404_fulcrum.html',
                                      {'error_msg': error_msg},
                                      context_instance=RequestContext(request))

        if format == 'html':
            try:
                object = resource.object_by_pk(primary_key)
            except:
                error_msg = "Sorry, but Fulcrum can't find an object with a primary key of <span class='loud'>{0}</span>.".format(
                    primary_key)
                return render_to_response(
                    'fulcrum/404_fulcrum.html', {'error_msg': error_msg},
                    context_instance=RequestContext(request))
            return render_to_response('fulcrum/object_detail.html',
                                      {'object': object},
                                      context_instance=RequestContext(request))
        else:
            return resource.handle(request,
                                   pk=primary_key,
                                   emitter_format=format)
Beispiel #11
0
 def resource_api(self, request, resource_name, *args, **kwargs):
     """
     Resource API handler
     """
     
     log.debug('resource_api()')
     
     try:
         resource = self.registry[resource_name]
     except KeyError:
         error_msg = "Sorry, but no resource with the name <span class='loud'>{0}</span> has been registered with Fulcrum.".format(resource_name)
         return render_to_response('fulcrum/404_fulcrum.html',
                                   { 'error_msg': error_msg },
                                   context_instance=RequestContext(request))
     
     
     protocol = request.META['SERVER_PROTOCOL'].split('/')[0].lower()
     host = request.META['HTTP_HOST']
     path_info = request.META['PATH_INFO'].lstrip('/').rstrip('/api')
     example_uri = '%s://%s/%s' % (protocol, host, path_info)
     
     return render_to_response('fulcrum/resource_api.html',
                               { 'resource': resource, 'handler': resource.handler, 'example_uri': example_uri },
                               context_instance=RequestContext(request))
Beispiel #12
0
    def create(self, request, *args, **kwargs):
        """
        Default create implementation. Will only validate if all required fields are supplied.
        Related object fields require a primary_key to an object or list of objects that already
        exist in the database.
        """
        log.debug('create()')

        if not self.has_model():
            return rc.NOT_IMPLEMENTED

        attrs = self.flatten_dict(request.POST)
        for k in attrs.keys():
            if len(attrs[k]) == 1:
                attrs[k] = attrs[k][0]

        m2mobjs = {}
        for f in self.model._meta.local_fields + self.model._meta.many_to_many:

            required = f.blank == False
            if required and f.name in attrs:

                if type(f) == ForeignKey:
                    try:
                        obj = f.rel.to.objects.get(pk=attrs[f.name])
                        attrs[f.name] = obj
                    except ObjectDoesNotExist, e:
                        error_msg = 'ObjectDoesNotExist: %s' % e
                        log.debug(error_msg)
                        return HttpResponseBadRequest(error_msg)
                elif type(f) == ManyToManyField:
                    try:
                        m2mobjs[f.name] = f.rel.to.objects.filter(
                            pk__in=attrs[f.name])

                        if len(m2mobjs[f.name]) != len(attrs[f.name]):
                            error_msg = 'ObjectDoesNotExist: A ManyToMany primary_key value failed to return an object.'
                            log.debug(error_msg)
                            return HttpResponseBadRequest(error_msg)
                        del attrs[
                            f.
                            name]  # passing this into model(**attrs) throws an error
                    except ObjectDoesNotExist, e:
                        error_msg = 'ObjectDoesNotExist: %s' % e
                        log.debug(error_msg)
                        return HttpResponseBadRequest(error_msg)
Beispiel #13
0
 def create(self, request, *args, **kwargs):
     """
     Default create implementation. Will only validate if all required fields are supplied.
     Related object fields require a primary_key to an object or list of objects that already
     exist in the database.
     """
     log.debug('create()')
     
     if not self.has_model():
         return rc.NOT_IMPLEMENTED
     
     attrs = self.flatten_dict(request.POST)
     for k in attrs.keys():
         if len(attrs[k]) == 1:
             attrs[k] = attrs[k][0]
     
     m2mobjs = {}
     for f in self.model._meta.local_fields + self.model._meta.many_to_many:
         
         required = f.blank == False
         if required and f.name in attrs:
             
             if type(f) == ForeignKey:
                 try:
                     obj = f.rel.to.objects.get(pk=attrs[f.name])
                     attrs[f.name] = obj
                 except ObjectDoesNotExist, e:
                     error_msg = 'ObjectDoesNotExist: %s' % e
                     log.debug(error_msg)
                     return HttpResponseBadRequest(error_msg)
             elif type(f) == ManyToManyField:
                 try:
                     m2mobjs[f.name] = f.rel.to.objects.filter(pk__in=attrs[f.name])
                               
                     if len(m2mobjs[f.name]) != len(attrs[f.name]):
                         error_msg = 'ObjectDoesNotExist: A ManyToMany primary_key value failed to return an object.'
                         log.debug(error_msg)
                         return HttpResponseBadRequest(error_msg)
                     del attrs[f.name] # passing this into model(**attrs) throws an error
                 except ObjectDoesNotExist, e:
                     error_msg = 'ObjectDoesNotExist: %s' % e
                     log.debug(error_msg)
                     return HttpResponseBadRequest(error_msg)
Beispiel #14
0
 def data_schema(self):
     log.debug('data_schema')
     return { 'description': BaseArbitraryHandler.__doc__,
              'handler': BaseArbitraryHandler.__name__,
              'params': 'You must override data_schema method to provide necessary parameters.',
              'return_value': 'You must override data_schema method to provide expected return value.' }
Beispiel #15
0
 def data_html(self):
     log.debug('data_html')
     return 'You must implement a data_html method in your custom handler'
Beispiel #16
0
         error_msg = 'Required field %s not found.' % f.name
         log.debug(error_msg)
         return HttpResponseBadRequest(error_msg)
 
 try:
     inst = self.model.objects.get(**attrs)
     return rc.DUPLICATE_ENTRY
 except self.model.DoesNotExist:
     
     # instantiate model and validate
     inst = self.model(**attrs)
     try:
         inst.full_clean()
     except ValidationError, e:
         error_msg = str(e)
         log.debug(error_msg)
         return HttpResponseBadRequest(error_msg)
     inst.save()
     
     # add M2M related field objs
     if len(m2mobjs):
         for k, v in m2mobjs.items():
             #log.debug('k:v = {0}:{1}'.format(k, v))
             f = getattr(inst, k)
             for val in v:
                 try:
                     f.add(val)
                     inst.save()
                 except:
                     error_msg = 'Error adding %s to %s %s field' % (val, inst, f)
                     log.debug(error_msg)
Beispiel #17
0
                error_msg = 'Required field %s not found.' % f.name
                log.debug(error_msg)
                return HttpResponseBadRequest(error_msg)

        try:
            inst = self.model.objects.get(**attrs)
            return rc.DUPLICATE_ENTRY
        except self.model.DoesNotExist:

            # instantiate model and validate
            inst = self.model(**attrs)
            try:
                inst.full_clean()
            except ValidationError, e:
                error_msg = str(e)
                log.debug(error_msg)
                return HttpResponseBadRequest(error_msg)
            inst.save()

            # add M2M related field objs
            if len(m2mobjs):
                for k, v in m2mobjs.items():
                    #log.debug('k:v = {0}:{1}'.format(k, v))
                    f = getattr(inst, k)
                    for val in v:
                        try:
                            f.add(val)
                            inst.save()
                        except:
                            error_msg = 'Error adding %s to %s %s field' % (
                                val, inst, f)
Beispiel #18
0
 def data_html(self):
     log.debug('data_html')
     return 'You must implement a data_html method in your custom handler'