【问题标题】:Tastypie: REST API where POST and GET resource format are differentTastypie:POST 和 GET 资源格式不同的 REST API
【发布时间】:2013-04-24 17:35:26
【问题描述】:

我创建了一个 API。获取我的资源给出:

{
    category: {
        id: "517ed1bff929f90e1152ad43",
        name: "Test category"
    },
    cost: "Free",
    description: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras tincidunt augue in mi scelerisque quis condimentum velit sollicitudin. Nam eleifend posuere semper. Pellentesque non nulla et arcu ornare lacinia. Donec quis dui at velit placerat volutpat vitae sit amet lorem. ",
    genders: [
        "M",
        "F"
    ],
    id: "517ed1bff929f90e1152ad44",
    tags: [
        {
            id: "517ed1bff929f90e1152ad3f",
            name: "testing",
            resource_uri: "/api/v1/interests/517ed1bff929f90e1152ad3f/"
        },
        {
            id: "517ed1bff929f90e1152ad41",
            name: "coding",
            resource_uri: "/api/v1/interests/517ed1bff929f90e1152ad41/"
        }
    ],
    location: {
        lat_lng: [
            51.500705,
            -0.124575
        ],
        locality: "London",
        name: "Big Ben"
    },
    resource_uri: "/api/v1/events/517ed1bff929f90e1152ad44/",
    slug: "test-event1",
    title: "Test event1"
}

我想允许用户将标签作为列表提交,例如['testing', 'coding', 'python'] 而不是要求他们提交对象 - 这是因为如果不存在标记对象,我将创建一个。

我怎么能用 sweetpie 做到这一点,它违反了 REST 原则?

【问题讨论】:

    标签: rest tastypie


    【解决方案1】:

    我做了类似的事情,除了我让 GET 和 POST 都使用名称而不是 URI。这可能在内部更加一致。

    如果您只想让 POST/PUT 使用名称,您应该能够定义 hydrate_tags method of your resource。如果您被排除在客户端使用 url 而只允许使用名称,也许这样的事情会起作用:

    def hydrate_tags(self, bundle):
        new_list = []
        for item in bundle:
            new_list.append(TagResource.build_bundle(data={name: item.data}))
        return new_list
    

    请注意,以上内容未经验证 - 我没有检查 hydrate_tags 是否应该返回列表或捆绑包。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-07-15
      • 2021-12-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多