当前位置: 首页 > 工具软件 > restful-dj > 使用案例 >

python django restful_Django轻松构建RESTful接口

芮叶秋
2023-12-01

(我不得不编辑最明显的链接。)

+1为piston - (上面的链接)。我过去曾经使用过apibuilder(华盛顿时报开源),但活塞对我来说更容易。对我来说最困难的事情是弄清楚我的API的URL结构,并帮助使用正则表达式。我也使用了surlex,这使得这件苦差事更容易。

例如,将此模型用于Group(来自我们正在研究的时间表系统):

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

这个urls.py片段(请注意,surlex允许容易地设置正则表达式宏):

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'[wW ,-]+')

urlpatterns = patterns('',

# group handler

# all groups

url(r'^groups/$', group_handler),

surl(r'^group//$', group_handler),

surl(r'^group//$', group_handler),)

然后这个处理程序将处理JSON输出(默认情况下),也可以执行XML和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()

正如您所看到的,大多数处理程序代码都在确定在ѭ9中传递了哪些参数。

一些示例URL是api/groups/,api/group/3301/和api/group/st1gp01/ - 所有这些都将输出JSON。

 类似资料: