【问题标题】:What is the best way to add command api with django-tastypie?用 django-tastypie 添加命令 api 的最佳方法是什么?
【发布时间】:2012-03-16 07:18:26
【问题描述】:

我有以下模型,我想允许用户使用 API 加入活动 使用 django-tastypie。

# 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 之类的

# 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)),
)

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

【问题讨论】:

    标签: django rest tastypie


    【解决方案1】:

    我认为您可以创建“EventResource”。然后,您可以为用户加入、用户离开和任何其他操作设置不同的事件。所以基本上也有“EventTypeResource”可能会很好。

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

    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.");
        }
    );
    

    【讨论】:

    • 抱歉,我不明白你对 EventTypeResource 的意思。根据您的建议,用户如何加入特定活动?我应该传递“join”之类的类型来表示加入,“leave”表示离开,“update”表示更新事件或其他什么???
    • 在 RESTful API 中不应有任何操作或方法调用(这是类 RPC API 的特征)。因此,您应该只创建一个事件而不是加入它(对其执行操作)。 EventTypeResource 帮助您区分不同的事件,例如加入或离开。所以是的,在最简单的形式中,EventTypeResource 可能只有一个属性“标签”或“名称”,并通过 ToOneField() 与 EventResource 相关联。那么“用户加入事件”表示为正在创建相关EventTypeResource“加入”的EventResource。
    猜你喜欢
    • 2010-11-07
    • 2021-04-10
    • 2013-08-21
    • 1970-01-01
    • 1970-01-01
    • 2020-02-03
    • 1970-01-01
    • 2015-03-12
    • 2018-08-10
    相关资源
    最近更新 更多