2016-06-02 4 views
1

난 장고 1.9.6 + Tastypie RESTFUL API를 구현하는 데 사용하고 있습니다, 거기에 다른 서버에 API를 whitch에서 데이터를 가져올 필요가있는 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을 배치합니다 당신의 질문은 어리석은 것이 아닙니다. 다루는 것은 아주 흔한 일입니다.

하지만 그것에 대해 모두가 어떤 이론의 첫 번째

:

당신은 아마 당신은 별도의 독립적 인 서비스를 나타내는 편안하고 API를 기존했다고 밝혔습니다. 한 종류의 서비스를 제공하는 각 API 서버는 최대한 독립적이어야합니다. 프론트 엔드 부분은 모든 서비스를 사용하는 풀이어야합니다.

한 서비스가 두 번째 서비스에서 필요한 것을 필요로한다고 생각한다면 프런트 엔드에서 실제로 그 서비스를 실제로 얻을 수 없는지 확인하십시오. 프론트 엔드 모듈을 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

관련 문제