【问题标题】:How to POST data into DB using Tastypie API如何使用 Tastypie API 将数据发布到数据库中
【发布时间】:2013-06-30 04:06:17
【问题描述】:

我可以直接调用 API URI 执行创建/删除操作吗?像

http://www.somedomain.com/api/entry/?action=create&book_title=something&year=1986&author=someone

而不是在 curl 中传递标题?

我可以用 CURL 做到这一点:

curl --dump-header - -H "Content-Type: application/json" -X POST --data '{"name": "me", "passwd": "123456"}' http://www.somedomain.com/api/entry/

但我希望通过在浏览器中请求 url 而不是使用 curl 来执行此操作。 这在美味派中可能吗?

【问题讨论】:

  • 您的问题似乎是“如何使用 Tastypie API 将数据获取到数据库中”,因为您想使用纯 url。

标签: api tastypie


【解决方案1】:

您可以覆盖 Resources 上的 dispatch 方法

from tastypie import resources

class MyResource(resources.ModelResource):
    class Meta:
        # TODO stuff here

    def dispatch(self, request_type, request, **kwargs):
        action = request.GET.get("action")
        if action in ["POST", "PUT", "DELETE", "PATCH"] and request.method == "GET":
            request.method = action
            request.POST = request.GET
        return super(MyResource, self).dispatch(request_type, request, **kwargs)

然后您可以使用GET从url直接调用您的api:

http://www.somedomain.com/api/entry/?action=POST&book_title=something&year=1986&author=someone

【讨论】:

  • 谢谢哥们,我已经用我的方法解决了。顺便说一句,你教了我另一种方法,这对下一个项目很有用。
【解决方案2】:

GET 将参数放在 URL 中,POST 请求应该将它们的数据放在消息正文中

http://en.wikipedia.org/wiki/POST_%28HTTP%29

【讨论】:

    猜你喜欢
    • 2019-06-15
    • 1970-01-01
    • 2018-01-07
    • 1970-01-01
    • 2023-02-16
    • 2015-08-04
    • 1970-01-01
    • 1970-01-01
    • 2015-07-18
    相关资源
    最近更新 更多