簡體   English   中英

是否可以在Tastypie資源中請求其他api?

[英]Is it possible to request other api in a Tastypie resource?

我正在使用Django 1.9.6 + Tastypie來實現RESTFUL api,有一個api需要從另一台服務器上的api whitch獲取數據,我不知道該怎么做。

我發現的所有例子都是這樣的:

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

EDITED

實現它的一種方法可能如下所示:

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,它將被轉義。 找出如何解決它

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM