Herramientas de usuario

Herramientas del sitio


fw:djangorest

Diferencias

Muestra las diferencias entre dos versiones de la página.

Enlace a la vista de comparación

Ambos lados, revisión anterior Revisión previa
Próxima revisión
Revisión previa
fw:djangorest [2014/06/02 17:57]
alfred [Notes]
fw:djangorest [2020/05/09 09:25] (actual)
Línea 6: Línea 6:
 pip install djangorestframework pip install djangorestframework
 </​code>​ </​code>​
-===== How to... ===== 
-==== Request objects are formed? ==== 
-  * ''​request.DATA''​ returns the parsed content of the request body. 
-  * ''​request.FILES''​ returns any uploaded files that may be present in the content of the request body.  
-  * ''​request.QUERY_PARAMS''​ is a more correctly named synonym for request.GET. 
-  * ''​request.user''​ typically returns an instance of ''​django.contrib.auth.models.User''​. 
-  * ''​request.auth''​ returns any additional authentication context. ​ 
-  * ''​request.method''​ returns the uppercased string representation of the request'​s HTTP method. 
-  * ''​request.content_type'',​ returns a string object representing the media type of the HTTP request'​s body, or an empty string if no media type was provided. 
-  * ''​request.stream''​ returns a stream representing the content of the request body. 
  
-==== Response objects are created? ==== 
-The renderers used by the Response class cannot natively handle complex datatypes such as Django model instances, so you need to serialize the data into primitive datatypes before creating the Response object. 
-  * ''​data'':​ The serialized data for the response. 
-  * ''​status'':​ A status code for the response. Defaults to 200. See also status codes. 
-  * ''​template_name'':​ A template name to use if HTMLRenderer is selected. 
-  * ''​headers'':​ A dictionary of HTTP headers to use in the response. 
-  * ''​content_type'':​ The content type of the response. Typically, this will be set automatically by the renderer as determined by content negotiation,​ but there may be some cases where you need to specify the content type explicitly. 
-==== Parsers work? ==== 
-Parsers are classes to convert from a datatype to another. We can set default parsers for all our API REST or any of the views. There are some default parsers: 
-  * ''​JSONParser''​ 
-  * ''​YAMLParser''​ 
-  * ''​XMLParser''​ 
-  * ''​FormParser''​ 
-  * ''​MultiPartParser''​ 
-  * ''​FileUploadParser''​ 
- 
-You can code your own parse inheriting from ''​BaseParser''​. There also are other third party packages with their own parsers ''​MessagePack'',​ ''​CamelCaseJSON''​... 
 ===== Routers ===== ===== Routers =====
 To define the URL for the API REST you can use router classes, which mount a list of relationships between url and views. It can be used in the ''​urlpatterns''​ settings variable. They have a ''​register( prefix, viewset)'',​ prefix is used to indicate URL patterns and viewset the concrete view. To define the URL for the API REST you can use router classes, which mount a list of relationships between url and views. It can be used in the ''​urlpatterns''​ settings variable. They have a ''​register( prefix, viewset)'',​ prefix is used to indicate URL patterns and viewset the concrete view.
Línea 409: Línea 382:
  
 They are in the package ''​rest_framework.generics''​. They are in the package ''​rest_framework.generics''​.
 +
 +===== How to... =====
 +==== Request objects are formed? ====
 +  * ''​request.DATA''​ returns the parsed content of the request body.
 +  * ''​request.FILES''​ returns any uploaded files that may be present in the content of the request body. 
 +  * ''​request.QUERY_PARAMS''​ is a more correctly named synonym for request.GET.
 +  * ''​request.user''​ typically returns an instance of ''​django.contrib.auth.models.User''​.
 +  * ''​request.auth''​ returns any additional authentication context. ​
 +  * ''​request.method''​ returns the uppercased string representation of the request'​s HTTP method.
 +  * ''​request.content_type'',​ returns a string object representing the media type of the HTTP request'​s body, or an empty string if no media type was provided.
 +  * ''​request.stream''​ returns a stream representing the content of the request body.
 +
 +==== Response objects are created? ====
 +The renderers used by the Response class cannot natively handle complex datatypes such as Django model instances, so you need to serialize the data into primitive datatypes before creating the Response object.
 +  * ''​data'':​ The serialized data for the response.
 +  * ''​status'':​ A status code for the response. Defaults to 200. See also status codes.
 +  * ''​template_name'':​ A template name to use if HTMLRenderer is selected.
 +  * ''​headers'':​ A dictionary of HTTP headers to use in the response.
 +  * ''​content_type'':​ The content type of the response. Typically, this will be set automatically by the renderer as determined by content negotiation,​ but there may be some cases where you need to specify the content type explicitly.
 +==== Parsers work? ====
 +Parsers are classes to convert from a datatype to another. We can set default parsers for all our API REST or any of the views. There are some default parsers:
 +  * ''​JSONParser''​
 +  * ''​YAMLParser''​
 +  * ''​XMLParser''​
 +  * ''​FormParser''​
 +  * ''​MultiPartParser''​
 +  * ''​FileUploadParser''​
 +
 +You can code your own parse inheriting from ''​BaseParser''​. There also are other third party packages with their own parsers ''​MessagePack'',​ ''​CamelCaseJSON''​...
 +
 +==== Filtering works? ====
 +To restrict the returned queryset you can filter...
 +=== Against the current user ===
 +<code python>
 +class PurchaseList(generics.ListAPIView)
 +    serializer_class = PurchaseSerializer
 +    def get_queryset(self):​
 +        user = self.request.user
 +        return Purchase.objects.filter(purchaser=user)
 +</​code>​
 +
 +=== Against the url ===
 +<code python>
 +url('​^purchases/​(?​P<​username>​.+)/​$',​ PurchaseList.as_view()),​
 +...
 +class PurchaseList(generics.ListAPIView)
 +    serializer_class = PurchaseSerializer
 +    def get_queryset(self):​
 +        username = self.kwargs['​username'​]
 +        return Purchase.objects.filter(purchaser__username=username)
 +</​code>​
 +
 +=== Against query parameters ===
 +<code python>
 +class PurchaseList(generics.ListAPIView)
 +    serializer_class = PurchaseSerializer
 +    def get_queryset(self):​
 +        queryset = Purchase.objects.all()
 +        username = self.request.QUERY_PARAMS.get('​username',​ None)
 +        if username is not None:
 +            queryset = queryset.filter(purchaser__username=username)
 +        return queryset
 +</​code>​
 +
 +=== Others ===
 +  * [[http://​www.django-rest-framework.org/​api-guide/​filtering]]
 +Django REST Framework provides several ways to return a queryset only defining order or fields. Also you can define your own filter classes.
 +
 +==== Pagination works? ====
 +
 +==== Others ====
 +=== Format suffixes ===
 +It's how to return the Response with a concrete format indicated by the url: [[http://​www.django-rest-framework.org/​api-guide/​format-suffixes]].
 +=== Return URLs ===
 +  * [[http://​www.django-rest-framework.org/​api-guide/​reverse]]
 +When returning URLs to other resources it's better to return the absolute url rather than the relative. Even if it was an identifier; if the string represents a resource, in REST it must be the resource absolute path. To do so in Django REST Framework you could use ''​reverse''​ and ''​reverse_lazy''​ functions.
 +
 +=== Configure ===
 +  * [[http://​www.django-rest-framework.org/​api-guide/​settings]]
 +You can configure features like default classes (renderers, parsers, authentications...),​ generic view settings (pagination,​ ordering...),​ el formato de las fechas...
 ===== Authentication and permissions ===== ===== Authentication and permissions =====
 ==== Authentication ==== ==== Authentication ====
Línea 471: Línea 524:
 Authorization:​ Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b Authorization:​ Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b
 </​code>​ </​code>​
-The curl command ​line tool may be useful ​for testing token authenticated APIs. For example:+The curl command ​for obtain the token: 
 +<​code>​ 
 +curl -X POST http://​127.0.0.1:​8000/​api-token-auth/​ -H "​Content-type:​ application/​json"​ -d '​{"​username":​ "​alfred",​ "​password":​ "​test"​}'​ 
 +</​code>​ 
 + 
 +The curl command ​for testing token authenticated APIs. For example:
 <​code>​ <​code>​
 curl -X GET http://​127.0.0.1:​8000/​api/​example/​ -H '​Authorization:​ Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b'​ curl -X GET http://​127.0.0.1:​8000/​api/​example/​ -H '​Authorization:​ Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b'​
Línea 518: Línea 576:
         return (user, None)         return (user, None)
 </​code>​ </​code>​
- 
 ==== Permissions ==== ==== Permissions ====
 Permissions are defined as a list of permission classes. When a view is called a permission list classes is checked, if any of them fails an ''​exceptions.PermissionDenied''​ exception will be raised. \\  Permissions are defined as a list of permission classes. When a view is called a permission list classes is checked, if any of them fails an ''​exceptions.PermissionDenied''​ exception will be raised. \\ 
fw/djangorest.1401731858.txt.gz · Última modificación: 2020/05/09 09:24 (editor externo)