简体   繁体   English

如何将Django模型公开为RESTful Web服务?

[英]How to expose a Django model as a RESTful web service?

I'm trying to create a REST web service that exposes the following Django model: 我正在尝试创建一个REST Web服务,以公开以下Django模型:

class Person(models.Model):
    uid = models.AutoField(primary_key=True)
    name = models.CharField(max_length=40)
    latitude = models.CharField(max_length=20)
    longitude = models.CharField(max_length=20)
    speed = models.CharField(max_length=10)
    date = models.DateTimeField(default=datetime.datetime.now)

    def __unicode__(self):
        return self.name

Here's how I thought about it so far: 到目前为止,这是我的想法:

Get all Persons 获取所有人
URL: http://localhost/api/persons/ 网址: http://localhost/api/persons/
Method: GET 方法: GET
Querystring: 请求参数:

  • startlat=
  • endlat=
  • startlng=
  • endlng=

Used for getting the Persons that are within the specified coordinate range. 用于获取指定坐标范围内的人物。

  • page=

Used for getting the specified page of the response (if the response contains multiple pages). 用于获取响应的指定页面(如果响应包含多个页面)。

Returns: 返回值:

  • 200 OK & JSON 200 OKJSON
  • 404 Not Found

Example: 例:
Request: 请求:

GET http://localhost/api/persons/?startlat=10&endlat=15&startlng=30&endlng=60

Response: 响应:

{
  "persons":
  [
     { "href": "1" },
     { "href": "2" },
     { "href": "3" },
     ...
     { "href": "100" }
  ],
  "next": "http://localhost/api/persons/?startlat=10&endlat=15&startlng=30&endlng=60&page=2"
}


Get info on a specified Person 获取有关指定人员的信息
URL: http://localhost/api/persons/[id] 网址: http://localhost/api/persons/[id]
Method: GET 方法: GET
Returns: 返回值:

  • 200 OK & JSON 200 OKJSON
  • 404 Not Found

Example: 例:
Request: 请求:

http://localhost/api/persons/5/

Response: 响应:

{
  "uid": "5",
  "name": "John Smith",
  "coordinates": {
                   "latitude":"14.43432",
                   "longitude":"56.4322"
                 },
  "speed": "12.6",
  "updated": "July 17, 2009, 8:46 a.m."
}



How correct is my attempt so far? 到目前为止,我的尝试有多正确? Any suggestions are highly appreciated. 任何建议都将受到高度赞赏。

{ "href": "1" },

1 is hardly a valid URL. 1几乎不是有效的URL。 You should use full URLs. 您应该使用完整的URL。 Google for HATEOAS . Google for HATEOAS

Also, remember to send a relevant Content-Type header. 另外,请记住发送相关的Content-Type标头。 You may want to make up your own mime-type to describe the format. 您可能需要组成自己的mime类型来描述格式。 This gives you the option to later change the content-type (Eg. change the format after publishing). 这使您可以选择以后更改内容类型(例如,发布后更改格式)。 See Versioning REST Web Services 请参阅REST Web服务版本控制

I think query parameters could be simpler and clearer. 我认为查询参数可能更简单明了。 This would make the URI more readable and would allow more flexibility for future extensions: 这将使URI更具可读性,并为将来的扩展提供更大的灵活性:

GET http://localhost/api/persons/?latitude=10:15&longitude=30:60

You may want to enable these in the future: 您将来可能希望启用这些功能:

GET http://localhost/api/persons/?latitude=10&longitude=60&within=5km

Seems REST-cool. 似乎REST很酷。 Even i worked on same kind of thing, few days earlier. 甚至几天前,我也从事相同的工作。

The only change, i would love to do in it, is the direct link to the person details. 我想做的唯一更改是直接链接到人员详细信息。 And also some details (like name here) to identify the person, and aid me in decision to navigate further. 还有一些细节(例如此处的姓名 )可以识别此人,并帮助我决定进一步导航。 Like... 喜欢...

{
  "persons":
  [
     { "name": "John Smith", "href": "http://localhost/api/persons/1/" },
     { "name": "Mark Henry", "href": "http://localhost/api/persons/2/" },
     { "name": "Bruce Wayne", "href": "http://localhost/api/persons/3/" },
     ...
     { "name": "Karl Lewis", "href": "http://localhost/api/persons/100/" }
  ],
  "next": "http://localhost/api/persons/?startlat=10&endlat=15&startlng=30&endlng=60&page=2"
}

This way, i am giving everything, to present data as, 这样,我就尽一切努力以数据形式呈现数据,

Next Page 下一页

It's ok to provide shorthand URIs in your JSON responses if you provide some templating system. 如果您提供一些模板系统,则可以在JSON响应中提供简写URI。 Like giving a base URI as something like http://whatever.com/persons/ {id}/ and then providing IDs. 就像提供基本URI一样,例如http://whatever.com/persons/ {id} /,然后提供ID。 Then with python you can just do a format call on the string. 然后使用python,您可以对字符串进行格式调用。 You don't ever want to make the programmer actually look at and understand the meaning of the URIs, which isn't necessary when you use templates. 您永远都不想让程序员真正了解并理解URI的含义,这在使用模板时是不必要的。

You might want to take a look at pre-existing REST middleware. 您可能想看一下预先存在的REST中间件。 I know they saved me a lot of time. 我知道他们为我节省了很多时间。 I'm using http://code.google.com/p/django-rest-interface/ . 我正在使用http://code.google.com/p/django-rest-interface/ And a snippet of the urls.py 还有urls.py

json_achievement_resource = Collection(
    queryset = Achievement.objects.all(),
    permitted_methods = ('GET',),
    responder = JSONResponder(paginate_by = 10)
)

urlpatterns += patterns('',
    url(r'^api/ach(?:ievement)?/(.*?)/json$', json_achievement_resource),
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM