2014-11-09 46 views
7

'da parametre türünü nasıl belirleyebilirim django-rest-framwork ve django-rest-swagger kullanıyorum.django-rest-swagger: docstring

Sorun istek gövdesinden doğrudan veri alma olmam:

def put(self, request, format=None): 
    """                                                 
    This text is the description for this API                                       
    username -- username                                            
    password -- password                                            
    """ 
    username = request.DATA['username'] 
    password = request.DATA['password'] 

ama dayı-ui isteğini çalıştığımda ("parametresi türü" belirleyemezsiniz varsayılan sorgu tarafından var ve "introspectors.py" fonksiyonu dosyasından den build_query_params_from_docstring bazı çizgi değiştirerek benim sorunu aşmanın başarmış

) docstringe onu değiştirmek için bir yol bulamıyorum ama başka bir var mı diye merak ediyordum Bunu yapmanın yolu.

cevap

8

GÜNCELLEME: Bu cevap sadece django-rest-swagger < 2 için çalışır, aşağıdaki Krd'den gör.

docs: http://django-rest-swagger.readthedocs.org/en/latest/yaml.html

form-data koymak istiyorsanız: bir filtre-sınıf tanımlamak

def put(...): 
    """ 
    ... 

    --- 
    parameters: 
    - name: body 
     description: JSON object containing two strings: password and username. 
     required: true 
     paramType: body 
     pytype: RequestSerializer 
    """ 
    ... 
+0

Teşekkür: geçersiz kılma varsayılan DRF şema jeneratör, bu doc ​​django dinlenme Swagger adım 2 entegrasyon adımı açıklıyor! Geçen yıldan beri çözümü bulmayı başardım;) Ama her zaman birilerine yardım edebilir – Alexis

+4

Yaml docstring desteği 2.0'dan sonra kaldırıldı, bu yüzden artık çalışmayacak http://marcgibbons.github.io/django-rest- swagger/# changes-in-20 – krd

+6

Yani, eğer dizinde değil mi? şimdi nasıl yapmalı? – Stephan

1

: Eğer böyle bir şey yapabileceği bir JSON vücuda için

def put(self, request, format=None): 
    """ 
    This text is the description for this API. 

    --- 
    parameters: 
    - name: username 
     description: Foobar long description goes here 
     required: true 
     type: string 
     paramType: form 
    - name: password 
     paramType: form 
     required: true 
     type: string 
    """ 
    username = request.DATA['username'] 
    password = request.DATA['password'] 

senin bakışta. django-rest artık parametreler için bu yaml dosyasını yapmıyor. Filtre sınıfınızda tanımladığınız alanlar, openapi/swagger belgelerinizde alanlar olarak görünecektir. Bu çok temiz.

READ belgelerini okuyun. filterseet tanımlanan

http://www.django-rest-framework.org/apiguide/filtering/#djangofilterbackend

from django_filters.rest_framework.filterset import FilterSet 

class ProductFilter(FilterSet): 

    class Meta(object): 
     models = models.Product 
     fields = (
      'name', 'category', 'id',) 


class PurchasedProductsList(generics.ListAPIView): 
    """ 
    Return a list of all the products that the authenticated 
    user has ever purchased, with optional filtering. 
    """ 
    model = Product 
    serializer_class = ProductSerializer 
    filter_class = ProductFilter 

    def get_queryset(self): 
     user = self.request.user 
     return user.purchase_set.all() 

alanları de belgelerinde gösterilir. ancak hiçbir açıklama yapılmayacaktır.

+0

Doğru cevap budur. Bunu Rest Swagger v2.0 ve ondan nasıl uygulamanız gerektiği. –

+1

@ api_view' hakkında ne dersiniz? –

+0

Bu cevap biraz örnek kod ile genişletilebilir mi? – jonalv

0

Parametre türlerini tanımlamada başarılı olmanın tek yolu, jeneratörü kullanmadan istediğimi tanımlayan bir görünüm oluşturmaktır.

gerçek manuel oluşturulan doc:

drf_api urls.py bu sınıfını kullanarak

class SwaggerSchemaView(APIView): 
permission_classes = [IsAuthenticatedOrReadOnly,] 
renderer_classes = [renderers.OpenAPIRenderer, renderers.SwaggerUIRenderer] 

schema = coreapi.Document(
    title='Thingy API thing', 
     'range': coreapi.Link(
      url='/range/{start}/{end}', 
      action='get', 
      fields=[ 
       coreapi.Field(
        name='start', 
        required=True, 
        location='path', 
        description='start time as an epoch', 
        type='integer' 
       ), 
       coreapi.Field(
        name='end', 
        required=True, 
        location='path', 
        description='end time as an epoch', 
        type='integer' 
       ) 
      ], 
      description='show the things between the things' 
     ), 
    } 
) 

ve sonra

John VanBuskirk cevabı Benzer
urlpatterns = [ 
    url(r'^$', SwaggerSchemaView.as_view()), 
    ... 
] 
1

, burada ne var /business/schema.py

# encoding: utf-8 
from __future__ import unicode_literals 
from __future__ import absolute_import 
import coreapi 

schema = coreapi.Document(
    title='Business Search API', 
    url='/api/v3/business/', 
    content={ 
     'search': coreapi.Link(
      url='/', 
      action='get', 
      fields=[ 
       coreapi.Field(
        name='what', 
        required=True, 
        location='query', 
        description='Search term' 
       ), 
       coreapi.Field(
        name='where', 
        required=True, 
        location='query', 
        description='Search location' 
       ), 
      ], 
      description='Search business listings' 
     ) 
    } 
) 

Sonra get_swagger_view fonksiyonunu kopyalanan ve özelleştirilmiş:

drf_api/swagger.py

# encoding: utf-8 
from __future__ import unicode_literals 
from __future__ import absolute_import 
from rest_framework import exceptions 
from rest_framework.permissions import AllowAny 
from rest_framework.renderers import CoreJSONRenderer 
from rest_framework.response import Response 
from rest_framework.views import APIView 
from rest_framework_swagger import renderers 
from django.utils.module_loading import import_string 


def get_swagger_view(schema_location): 
    """ 
    Returns schema view which renders Swagger/OpenAPI. 
    """ 
    class SwaggerSchemaView(APIView): 
     _ignore_model_permissions = True 
     exclude_from_schema = True 
     permission_classes = [AllowAny] 
     renderer_classes = [ 
      CoreJSONRenderer, 
      renderers.OpenAPIRenderer, 
      renderers.SwaggerUIRenderer 
     ] 

     def get(self, request): 
      schema = None 

      try: 
       schema = import_string(schema_location) 
      except: 
       pass 

      if not schema: 
       raise exceptions.ValidationError(
        'The schema generator did not return a schema Document' 
       ) 

      return Response(schema) 


    return SwaggerSchemaView.as_view() 

Sonra URL'ler o kadar kanca.py

DJANGO DİNLENME Swagger> 2.0 İÇİN
from ..swagger import get_swagger_view 
from . import views 

schema_view = get_swagger_view(schema_location='drf_api.business.schema.schema') 

urlpatterns = [ 
    url(r'^swagger/$', schema_view), 
+0

Eğer özel schema_view kullanırsak, konum nasıl ekleyeceğiz = 'body' ve beden örneğini nasıl gösteririz? –

İlgili konular