2016-06-02 6 views
1

私はDjango 1.9.6 + Tastypieを使ってRESTFUL APIを実装しています.APIが別のサーバにあるからデータを取得する必要があるAPIがありますが、その方法はわかりません。Tastypieリソースに他の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を要求することは可能でしょうか?答えが "はい"の場合、それを行う方法は?

多分問題は愚かです。

感謝:)たぶん

答えて

0

内全体ShelfResourceを配置しますあなたの質問は愚かではありません。

しかし、最初にそれについてのすべてのいくつかの理論の:

あなたはおそらく別の独立したサービスを表すRESTfulなAPIを既存していると言います。 1種類のサービスを提供する各APIサーバーは、可能な限り独立している必要があります。フロントエンド部分は、すべてのサービスを使用する接着剤でなければなりません。

サービスが2番目のサービスから何かを必要としていると思うのであれば、フロントエンドで本当に本当に本当に達成できないことを確認してください。 Javascriptなどのフロントエンドモジュールを書くことで、両方のサービスをリクエストし、取得する方法でデータを計算することができます。

これが本当に機能しない場合は、あなたのサービスは他のサービスに依存していることを文書化しなければなりません。また、他のサービスの更新がある場合は、おそらくサービスが必要です。インターネット接続やその他のサービスの安定性に依存するため、開発はより困難になります。

あなたのAPIはJSON上で動作すると仮定します。このようになります。これを実現するための

一つの方法:

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() 
  1. 注JSONの損傷を防ぐためにエスケープすることになるだろうJSONとして文句を言わない「シリアル化されているフィールド。それを修正する方法を見つけるthere

  2. これはパフォーマンスを大幅に低下させることになり、まったくお勧めしません。

+0

ご連絡ありがとうございました – dropax

0

あなたが探しているものは、例えば、単に関連するリソースフィールドnested Resourcesまたは、次のとおりです。

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=TrueProductResource

関連する問題