Diese Präsentation wurde erfolgreich gemeldet.
Wir verwenden Ihre LinkedIn Profilangaben und Informationen zu Ihren Aktivitäten, um Anzeigen zu personalisieren und Ihnen relevantere Inhalte anzuzeigen. Sie können Ihre Anzeigeneinstellungen jederzeit ändern.

Django Rest Framework vs Django TastyPie

15.917 Aufrufe

Veröffentlicht am

Slides from the Long Island Python Meetup http://www.meetup.com/li-python/events/175793552/

Veröffentlicht in: Software
  • Loggen Sie sich ein, um Kommentare anzuzeigen.

Django Rest Framework vs Django TastyPie

  1. 1. RESTful APIs in Django: Library Face-Off! TastyPie vs Django REST Framework
  2. 2. Scope of Discussion ● Introduction to REST ● Review of Django’s Flow ● Demo Structure Overview ● Demo of TastyPie ● Demo of Django Rest Framework ● Demo of SQLAlchemy in both Frameworks ● Conclusion
  3. 3. Introduction to REST ● REST - Representational State Transfer ● REST is a philosophy, not a communication protocol. o An architectural style for distributed systems just like the web o REST is not tied to the web, but it's almost always implemented as such, and was inspired by HTTP o Majority of RESTful APIs use HTTP serving JSON or XML.
  4. 4. Examples of REST Systems ● Google Glass API ● Twitter API ● Amazon Web Services ● Atom (RESTful alternative to RSS) ● Tesla Model S o Uses RESTful calls to communicate between mobile devices and car: http://docs.timdorr.apiary.io/
  5. 5. REST
  6. 6. REST Characteristics ● The term was introduced by Roy Fielding in 2000 for his in his doctoral dissertation at UC Irvine ● 6 Constraints proposed by Roy Fielding o Client-Server o Stateless Server o Cache o Uniform Interface o Layered System
  7. 7. REST Characteristics ● Client-Server Model: Pull Based (not event driven) system o Client - Sends requests to a server and awaits a response from the server. o Server - Provides a service to multiple clients. Receives requests and provides a response for the information that the client requested.
  8. 8. REST Characteristics ● Stateless Server o Each request to the server must contain all of the information necessary for the server to understand the request. o Server cannot take advantage of any server-side stored context. ● Ex: Server cannot know user’s profile before the request is made.
  9. 9. REST Characteristics ● Cacheable Responses o Responses from the server have to be capable of being cached by the client (though this doesn’t need to be used). ● Ex: Client stores locally the employee’s id for each consequent request after the initial request to login was successful.
  10. 10. REST Characteristics ● Uniform Interface o Resource Identifier - URL / URI  http://twitter.com/#!/jack/status/20 o Resource Representation and Manipulation  Whatever comes back that represents the resource identified by the URL. We can manipulate the resource directly from the URL. o Self-Descriptive Messages  Self-descriptive messages contain metadata to describe the meaning of the message. The methods used to invoke the message must be standard and agreeable between the first three constraints - client-server, stateless server, and cache.
  11. 11. REST Characteristics ● Uniform Interface o HATEOAS - Hypermedia as the engine of application state  User requests resource  Resource has transitions (or hyperlinks) to go to a new state (new resources)
  12. 12. REST Characteristics ● Layered System o Should be able to accommodate extra layers like proxy servers, firewalls, gateways, caching system o (this is why HTTP is most often used)
  13. 13. REST Characteristics ● Code-on-Demand o The optional code-on-demand constraint allows clients to request and execute code from servers. This, in turn, allows the server to deploy new features to clients.
  14. 14. More Information ● API Design: Ruminating Over REST o https://blog.apigee.com/detail/api_design_ruminat ing_over_rest ● A Beginner's Guide to HTTP and REST o http://code.tutsplus.com/tutorials/a-beginners-guide- to-http-and-rest--net-16340 ● HATEOAS o https://www.youtube.com/watch?v=6UXc71O7htc
  15. 15. HTTP ● Hypertext Transfer Protocol o Roy Fielding used REST to implement HTTP 1.1 o The protocol that is used to manipulate remote resources. o We can use HTTP Verbs to manipulate these resources.
  16. 16. CRUD (Create, Read, Update, Delete) Operation HTTP Verb Get an element by it’s ID GET Get a list of elements GET Insert a new element POST or PUT (usually POST) Update an existing element PUT Delete an element DELETE Basic Operations for Manipulating Data over HTTP
  17. 17. To most people, REST just means... ● Expose directory-structure-like URLS ● Use HTTP methods correctly / consistently ● Transfer XML or JSON ● Be stateless o The same call should always yield the same result regardless of server state / previous calls made
  18. 18. What are the Benefits? ● Separation of frontend and backend logic o easy to change your frontend client without touching your API o can add multiple clients (web, mobile, desktop app, batch process, etc) with no logic changes o gives a clear API layer to document. ● Only one protocol for accessing backend logic: changes only need to be made in one place. ● Predictable since it is stateless
  19. 19. What are the Benefits? ● You can make good use of HTTP caching and proxy servers / load balancers to help you handle high load. ● It helps you organize very complex applications into simple resources. ● It makes it easy for new clients to use your application, even if you haven’t designed it specifically for them.
  20. 20. Why is this example #1 not RESTful? Bret lives in Oregon. His address is part of his user profile – not sent with every API call When he performs a GET call on the URL /cars/used/9000/12000/ To search for used cars in his price range, he gets back only results for within 50 miles of his address.
  21. 21. Example 1: Find Cars for User URL: http://foo.bar.com/cars/used/ Request: Method: GET Request Payload: { "username" : "bobschmoe", "query" : "nearby" } Response: { "results” : [{ "car_id" : "ABC001”, "make” : "Honda”, "model” : "Accord” }, { "car_id” : "ABC001”, "make” : "Honda”, "model” : "Accord” }], "zip": "11040" }
  22. 22. Example 1: Find Cars for User It is NOT RESTful since it is not stateless. ● The server some how knew the user’s zip code. The client didn’t provide this information to the server.
  23. 23. Example 2: Add Vehicle to Company Profile URL: http://profile.mycompany.com/api/ Request: Method: POST Request Payload: { "resource" : "vehicle", "method" : "addVehicle", "year" : "2014", "make" : "Honda", "model" : "Accord", "trim" : "EX-L", } Response: { "resource_id" : "ABC00234", }
  24. 24. Example 2: Add Vehicle to Company Profile It is NOT RESTful since the URI is not unique. ● Unique resources are not tied to a unique URI. They all share one. ● Due to all requests being routed through one URI (/api/), no results have the ability to be cachable.
  25. 25. Example #3: Modifying Patient Information URL: http://mymeds.com/patients?method=updateAddress&patient_id=3254 Request: Method: POST Request Payload: { "address" : "123 Main Street", "city" : "Lake Success", "state" : "NY", } Response: { "success" : "true" }
  26. 26. Example #3: Modifying Patient Information This is NOT RESTful because the resource has state information. ● The client is making this call in order to change the state of the _ data on the server. But the client is using the GET method instead of the PUT method. ● REST specifies that A resource is uniquely tied to a single URI and that the correct method is used to create, read, update, or delete it.
  27. 27. Example #3: Modifying Patient Information This is NOT RESTful because the resource has state information. ● Tunneling all calls through GET is the primary REST anti-pattern! The base URI here - /patients/ - is not uniquely tied to a resource. ● /patient/address/32543/ used together with PUT would be better.
  28. 28. Django Request-Response Cycle B r o w s e r Django urlpatterns = patterns( '', # Examples: # url(r'^$', 'notematic3000.views.home', name='home'), url(r'^note/(?P<pk>d+)/update/(?P<params>.+)', views.UpdateNote.as_view(), name='update'), url(r'^note/(?P<pk>d+)/delete', views.DeleteNote.as_view(), name='delete'), url(r'^note/(?P<%s>d+)' % PK, views.DisplayNote.as_view(), name=DISPLAY), url(r'^new/(?P<params>.+)', views.CreateNote.as_view(), name='create'), url(r'^(all)?', views.AllNotes.as_view(), name=GETALL), ) Selected view ● Receives request object ● Responsible for all processing of request ● One view will process different methods ● Performs database interactions using ORM ● Creates response ● Returns response object GET note/3 G E T n o t e / 3 Response - (e.g. JSON text)
  29. 29. Demo Structure Overview
  30. 30. Project Structure notematic3000 |----------------------------------------------- notes |-- Makefile |----------------------------- api |-- manage.py |-- admin.py |-- __init__.py |-- notematic3000 |-- alchemy |-- rest |------------------------ urls | |-- __init__.py | |-- __init__.py |-- crossbrowser.py |-- default.py | `-- notemanager.py | |-- routers.py |-- db.sqlite3 |-- __init__.py |-- constants.py | |-- serializers.py |-- __init__.py |-- pie.py |-- __init__.py | |-- sqlalchemy_viewset.py |-- settings `-- rest.py |-- models.py | `-- viewsets.py | |-- base.py |-- tests.py `-- tastypie | |-- default.py |-- urls.py |-- api.py | |-- __init__.py `-- views.py |-- __init__.py | |-- pie.py `-- sqlalchemy_api.py | `-- rest.py `-- wsgi.py
  31. 31. Project Settings from base import * # MODIFY INSTALLED APPS INSTALLED_APPS = INSTALLED_APPS + ('rest_framework',) # MODIFY URLS ROOT_URLCONF = 'notematic3000.urls.rest' # DJANGO REST FRAMEWORK SETTINGS REST_FRAMEWORK = { 'DEFAULT_RENDERER_CLASSES' : ( 'rest_framework.renderers.BrowsableAPIRenderer', 'rest_framework.renderers.JSONRenderer', 'rest_framework.renderers.XMLRenderer', ) }
  32. 32. Project Structure notematic3000 |----------------------------------------------- notes |-- Makefile |----------------------------- api |-- manage.py |-- admin.py |-- __init__.py |-- notematic3000 |-- alchemy |-- rest |------------------------ urls | |-- __init__.py | |-- __init__.py |-- crossbrowser.py |-- default.py | `-- notemanager.py | |-- routers.py |-- db.sqlite3 |-- __init__.py |-- constants.py | |-- serializers.py |-- __init__.py |-- pie.py |-- __init__.py | |-- sqlalchemy_viewset.py |-- settings `-- rest.py |-- models.py | `-- viewsets.py | |-- base.py |-- tests.py `-- tastypie | |-- default.py |-- urls.py |-- api.py | |-- __init__.py `-- views.py |-- __init__.py | |-- pie.py `-- sqlalchemy_api.py | `-- rest.py `-- wsgi.py
  33. 33. Introduction to DRF Django REST framework is a powerful and flexible toolkit that makes it easy to build Web APIs.
  34. 34. DRF - Routers ● REST framework adds support for automatic URL routing to Django, and provides you with a simple, quick and consistent way of wiring your view logic to a set of URLs. ● Types of Routers o SimpleRouter o DefaultRouter o CustomRouters
  35. 35. DRF - Parsers ● REST framework includes a number of built in Parser classes, that allow you to accept requests with various media types. There is also support for defining your own custom parsers, which gives you the flexibility to design the media types that your API accepts. ● Types of Parsers o Built-In:  JSONParser, YAMLParser, XMLParser, FormParser, MultiPartParser, FileUploadParser o You can build your own custom parser
  36. 36. DRF - ViewSets ● Django REST framework allows you to combine the logic for a set of related views in a single class, called a ViewSet. In other frameworks you may also find conceptually similar implementations named something like 'Resources' or 'Controllers'. ● Types of ViewSets: o Built-In:  GenericViewSet, ModelViewSet, ReadOnlyModelViewSet o You can build your own custom ViewSet
  37. 37. DRF - Renderers ● REST framework includes a number of built in Renderer classes, that allow you to return responses with various media types.
  38. 38. DRF - Renderers ● Built-in Renderers o JSONRenderer, UnicodeJSONRenderer, JSONPRenderer, YAMLRenderer, XMLRenderer, TemplateHTMLRenderer, StaticHTMLRenderer,HTMLFormRenderer, BrowsableAPIRenderer, MultiPartRenderer o Custom Renderers
  39. 39. Other Features ● Authorization o BasicAuthorization, TokenAuthorization, SessionAuthorization, OAuthAuthorization, OAuth2Authorization, CustomAuthorization ● Permissions ● Throttling ● Filtering ● Pagination
  40. 40. DEMO TIME
  41. 41. Introduction to Tastypie ● Tastypie is a framework providing boilerplate code to create RESTful APIs ● Depends on Django - cannot stand alone ● Basically involves creating ‘Resource’ oriented classes ● Resources are intermediary between end-user and Django models ● Provides out-of-box authentication, authorization, caching, throttling and serialization
  42. 42. Tastypie Request Flow HTTP Request Django URL Resolver check Lookup view for match Check for serialization errors call dispatch dispatch method call HTTP method in allowed list? Authenticate/Authorize Throttle check call actual method
  43. 43. Advanced Tastypie ● Bundles - Abstraction to pass data between resources ● Api - Collection of resources ● Resource Fields - Representation of resource (just like Django Fields) ● You can customize authentication, authorization, caching, throttling, validation, serialization ● Learn more at http://django-tastypie.readthedocs.org/
  44. 44. DEMO TIME
  45. 45. Non-Django ORM sources ● What if - we cannot use Django ORM and we need something more advanced? ● Both frameworks have hooks to replace Django ORM ● Tastypie - Extend and override ‘Resource’ methods ● DRF - Extend and override ‘ViewSet’ methods
  46. 46. Conclusion (1) ● REST is now the standard for open APIs ● REST is best summed up as verbs + nouns in URLS ● Django app is structured as urls + views + models + stuff to make it easier ● Provides ORM ● Lots of libraries which build off it
  47. 47. Conclusion (2) ● DRF documentation is better and well-structured ● DRF is modular, pluggable, easy to understand ● DRF supports web-browsable APIs and oAuth2 ● DRF has better integration with Swagger ● TastyPie is older, can do anything, but is less Django-style
  48. 48. The Verdict Description DRF TastyPie Git Commits Web-browsable APIs Yes No Throttling Yes Yes Caching Yes Yes Form Validation No Yes oAuth2 Yes No Documentation Well-structured, easy to find Good, but not good enough Ease of use APIs are Django-like, easier to understand and hence use APIs hard to understand and hence use Swagger Better integration Does integrate, but takes effort