首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用django-tastypie添加命令api的最好方法是什么?

用django-tastypie添加命令api的最好方法是什么?
EN

Stack Overflow用户
提问于 2012-03-16 15:18:27
回答 1查看 486关注 0票数 0

我有以下模型,我想让用户加入与django的API的活动-品味。

代码语言:javascript
复制
# Conceptual, may not work.
class Event(models.Model):
    title = models.CharField('title', max_length=255)
    users = models.ForeignKey(User)

    def join(self, user):
        self.users.add(user)
    def leave(self, user):
        self.users.remove(user)

# join the events with API like...
jQuery.post(
    '/api/v1/events/1/join',
    function(data) {
        // data should be a joined user instance
        // or whatever
        alert(data.username + " has joined.");
    },
);

但我不知道最好的方法。我应该像这样创建EventJoinResource

代码语言:javascript
复制
# Conceptual, may not work.
class EventJoinResource(Resource):
    action = fields.CharField(attribute='action')

    def post_detail(self, request, **kwargs):
        pk = kwargs.get('pk')
        action = kwargs.get('action')
        instance = Event.objects.get(pk=pk)
        getattr(instance, action)(request.user)

resource = EventJoinResource()

# ??? I don't know how to write this with django-tastypie urls
urlpatterns = patterns('',
    ('r'^api/v1/events/(?P<pk>\d+)/(?P<action>join|leave)/$', include(resource.urls)),
)

我该怎么办?欢迎任何建议:-)

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-03-17 04:40:22

我认为你可以创建"EventResource“。然后,你可以有不同的事件,用户加入,用户离开和任何其他行动。所以从根本上来说,也有"EventTypeResource“可能是件好事。

然后,每次发生事件时,您只需POST到"EventResource“,指定事件的类型(通过指定EventTypeResource集合的元素)和任何额外的数据,如下所示:

代码语言:javascript
复制
jQuery.ajax ( {
    url : '/api/v1/events/', #note the collection URI not the element URI
    data : {
        type : '/api/v1/event-types/<pk_of_the_event_type', #URI of EventTypeResource
        extra_data : { ... }
    },
    success : function(data) {
        // data should be a joined user instance
        // or whatever
        alert(data.username + " has joined.");
    }
);
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/9733374

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档