Django ease of building a RESTful interface

前端 未结 6 917
渐次进展
渐次进展 2020-12-25 09:43

I\'m looking for an excuse to learn Django for a new project that has come up. Typically I like to build RESTful server-side interfaces where a URL maps to resources that sp

6条回答
  •  梦毁少年i
    2020-12-25 10:04

    (I had to edit out the most obvious links.)

    +1 for piston - (link above). I had used apibuilder (Washington Times open source) in the past, but Piston works easier for me. The most difficult thing for me is in figuring out my URL structures for the API, and to help with the regular expressions. I've also used surlex which makes that chore much easier.

    Example, using this model for Group (from a timetable system we're working on):

    class Group(models.Model):
        """
        Tree-like structure that holds groups that may have other groups as leaves. 
        For example ``st01gp01`` is part of ``stage1``.
        This allows subgroups to work. The name is ``parents``, i.e.::
    
            >>> stage1group01 = Group.objects.get(unique_name = 'St 1 Gp01')
            >>> stage1group01
            >>> 
            # get the parents...
            >>> stage1group01.parents.all()
            >>> []
    
        ``symmetrical`` on ``subgroup`` is needed to allow the 'parents' attribute to be 'visible'.
        """
        subgroup = models.ManyToManyField("Group", related_name = "parents", symmetrical= False, blank=True)
        unique_name = models.CharField(max_length=255)
        name = models.CharField(max_length=255)
        academic_year = models.CharField(max_length=255)
        dept_id = models.CharField(max_length=255)
        class Meta:
            db_table = u'timetable_group'
        def __unicode__(self):
            return "%s" % self.name
    

    And this urls.py fragment (note that surlex allows regular expression macros to be set up easily):

    from surlex.dj import surl
    from surlex import register_macro
    from piston.resource import Resource
    from api.handlers import GroupHandler
    group_handler = Resource(GroupHandler)
    
    # add another macro to our 'surl' function
    # this picks up our module definitions
    register_macro('t', r'[\w\W ,-]+')
    
    urlpatterns = patterns('',
    # group handler
    # all groups
    url(r'^groups/$', group_handler),
    surl(r'^group//$', group_handler),
    surl(r'^group//$', group_handler),)
    

    Then this handler will look after JSON output (by default) and can also do XML and YAML.

    class GroupHandler(BaseHandler):
        """
        Entry point for Group model
        """
    
        allowed_methods = ('GET', )
        model = Group
        fields = ('id', 'unique_name', 'name', 'dept_id', 'academic_year', 'subgroup')
    
        def read(self, request, id=None, name=None):
            base = Group.objects
            if id:
                print self.__class__, 'ID'
                try:
                    return base.get(id=id)
                except ObjectDoesNotExist:
                    return rc.NOT_FOUND
                except MultipleObjectsReturned: # Should never happen, since we're using a primary key.
                    return rc.BAD_REQUEST
            else:
                if name:
                    print self.__class__, 'Name'
                    return base.filter(unique_name = name).all()
                else:
                    print self.__class__, 'NO ID'
                    return base.all()
    

    As you can see, most of the handler code is in figuring out what parameters are being passed in urlpatterns.

    Some example URLs are api/groups/, api/group/3301/ and api/group/st1gp01/ - all of which will output JSON.

提交回复
热议问题