是否可以在 Tastypie 资源中请求其他 api



我正在使用Django 1.9.6 + Tastypie来实现RESTFUL api,有一个api需要从另一台服务器上的api获取数据,我不知道该怎么做。

我找到的所有示例都是这样的:

from tastypie.resources import ModelResource
from services.models import Product
from tastypie.authorization import Authorization

class ProductResource(ModelResource):
    class Meta:
        queryset = Product.objects.all()
        resource_name = 'product'
        allowed_methods = ['get']
        authorization = Authorization()

资源类从应用程序的模型(本地数据库)获取数据,是否可以请求另一台服务器上的 API?如果答案是肯定的,那么该怎么做?

也许这个问题很愚蠢。

谢谢:)

也许您要查找的是嵌套资源或仅相关的资源字段,例如:

from tastypie.resources import ModelResource
from tastypie import fields
from services.models import Product
from tastypie.authorization import Authorization

class ProductResource(ModelResource):
    shelf = fields.ForeignKey('shelf.api.ShelfResource', 'shelf', null=True)
    class Meta:
        queryset = Product.objects.all()
        resource_name = 'product'
        allowed_methods = ['get']
        authorization = Authorization()

full=True会将整个ShelfResource放置在ProductResource

已编辑

实现它的一种方法可能如下所示:

import requests
from requests.exceptions import RequestException
[...]    
# implementing connection in models.py gives more flexibility.
class Product(models.Model):
    [...]
    def get_something(self):
        try:
            response = requests.get('/api/v1/other/cars/12341')
        except RequestException as e:
            return {'success': False, 'error': 'Other service unavailable!'}
        if response.status_code not in [200, 201, 202, 203, 204, 205]:
            return {'success': False, 'error': 'Something went wrong ({}): {}'.format(response.status_code, response.content)}
        data = json.load(response.content)
        data['success'] = True
        return data
    def something(self):
         self.get_something()

from tastypie.resources import ModelResource
from services.models import Product
from tastypie.authorization import Authorization

class ProductResource(ModelResource):
    something = fields.CharField('something', readonly=True)
    class Meta:
        queryset = Product.objects.all()
        resource_name = 'product'
        allowed_methods = ['get']
        authorization = Authorization()

请注意,字段不会被序列化为 JSON,它将被转义。了解如何在那里修复它

最新更新