简体   繁体   English

对非RESTful API使用django-tastypie

[英]Using django-tastypie for a non-RESTful API

Suppose you need to write a simple non-RESTful API, and want to do it using django-tastypie , how would you do so? 假设您需要编写一个简单的非RESTful API,并想使用django-tastypie做到这一点 ,您将如何做?

Tastypie only provides Resource s that are tightly coupled to a data model. Tastypie仅提供与数据模型紧密耦合的Resource

Is there a way to use tastypie's other utilities for APIs (such as authentication, serlialization, etc.) but use it for "simple" APIs? 有没有一种方法可以将asteapie的其他实用程序用于API(例如身份验证,序列化等),但可以将其用于“简单” API? Of course this could be written as a simple view, but then you'd be missing out on the other stuff tastypie gives you. 当然,这可以写成一个简单的视图,但是那样的话,您可能会错过了好看的其他东西。

A simple example would be an API that receives a string and reverses it. 一个简单的示例是一个接收字符串并反转它的API。

This is the purpose of prepend_urls - you can add custom endpoints to your existing methods. 这是prepend_urls的目的-您可以将自定义端点添加到现有方法中。 Out-of-the-box they work just like plain views, but you now have the ability to call all the functions you need from your Resource - and return either plain HttpResponse s or piggyback on existing Tastypie functions to return rich objects. 开箱即用的它们就像普通视图一样工作,但是现在您可以从Resource中调用所需的所有功能-并返回纯HttpResponse或在现有的Deliciouspie函数上搭载以返回丰富的对象。

For instance, if I had a User resource and wanted to provide an endpoint to determine if a user is currently authenticated by returning 1 or 0 , I'd do this: 例如,如果我有一个User资源,并且想提供一个端点来确定用户当前是否通过返回10身份验证,则可以这样做:

def prepend_urls(self):
    return [
        #...
        url(r"^(?P<resource_name>%s)/is_authenticated?$" % (self._meta.resource_name), self.wrap_view('is_authenticated')),
        #...
    ]
# ...other methods in your Resource...
def is_authenticated(self, request, **kwargs):
    if self._meta.authentication.is_authenticated(request):
        return HttpResponse("1")
    else:
        return HttpResponse("0")

Or, if I actually wanted to return the actual user resource for the authenticated user, I could (for example) replace return HttpResponse("1") with return self.get_detail(request, id=request.user.id) - effectively simulating a call to /user/?id=[authenticated user's ID] . 或者,如果我实际上想返回经过身份验证的用户的实际用户资源,则可以(例如return HttpResponse("1")return self.get_detail(request, id=request.user.id)替换return HttpResponse("1") return self.get_detail(request, id=request.user.id) -有效地模拟呼叫/user/?id=[authenticated user's ID]

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

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