Djangular

RESTful APIs with Django and AngularJS

Information


Github Repository: https://github.com/rooeydaniel
Twitter: @rooeydaniel

App Technology

  • Bootstrap
  • AngularJS
  • Django
  • Django REST Framework
  • Potential Architecture

Bootstrap

  • Home page: http://getbootstrap.com/
  • Front-end framework for responsive design
  • Fantastic for those that struggle with app design/layout
  • Has great documentation
  • Tremendous community support

AngularJS

  • Home page: https://angularjs.org/
  • Official Tutorial: https://docs.angularjs.org/tutorial
  • ng-book: https://www.ng-book.com/
  • Front-end JavaScript framework
    • Used mainly for Single-Page Applications (SPAs)
    • MVC, allows for separation of app logic, data and views
    • MVC, makes testing easier
  • Provides Ajax services
  • Dependency Injection
  • Two-way data binding (three-way with technologies like Firebase)
    • Changes in view and/or controller are reflected immediately

django

  • Home page: https://www.djangoproject.com/
  • High-level Python Web framework
  • Adheres to 'DRY' principle
  • Built-in ORM that still allows for custom SQL
  • Automated admin interface
  • Templating language
  • Caching
  • Internationalization

django Rest framework

  • Home page: http://www.django-rest-framework.org/
  • Makes building Web APIs easy
  • Browseable Web API
    • Development phase becomes simpler
  • OAuth2 (and OAuth1) baked in
  • JSON Serialization, supports ORM and non-ORM sources
  • Class-based and function-based views
  • Outstanding documentation

Potential App architecture

  • Pure Django
    • Routes handled exclusively by Django
    • Django templating language
    • Django forms
  • Django w/ jQuery
    • Similar to Pure Django, but jQuery handles dynamic content
  • Django w/ AngularJS Embedded
    • Replace jQuery with AngularJS for dynamic data
    • Preferred non-distributed architecture
  • Split: Django Back-end and AngularJS Front-end
    • Single page application (SPA)
    • Routes handled by AngularJS and Django

Pure django

Django models

Django Admin

Retrieve Tasks

Filter/Search Tasks

Create Tasks

Update Tasks

Filter on Model Attribute

Delete Tasks

Deploy to Heroku

django w/jquery

django Models

Django admin

retrieve tasks

filter/search tasks

create tasks

update tasks

filter on model attribute

delete tasks

deploy to heroku

django w/Angularjs embedded

django models

django admin

retrieve tasks

filter/search tasks

create tasks

update tasks

filter on model attribute

delete tasks

deploy to heroku

Split: django w/angularJS

    • Clone Github repositories
    • Install Django dependencies
      • Virtual environment
      • PIP
    • Run Django's internal server
      • Use port 8001
      • python manage.py runserver 8001
      • http://localhost:8001
    • Run Node's internal server
      • Runs on port 8000
      • node server/server.js
      • http://localhost:8000

    django models

    • https://docs.djangoproject.com/en/1.6/topics/db/models/
    • The single, definitive source of information about your data
    • A Python class that inherits from Django's model class
    • Each attribute represents a database field

    Task
    Category
    Tag

    • South
      • Handles database synchronization
      • Migrations

    django admin

    • Production-ready app that provides an interface for any model in your project
      • https://docs.djangoproject.com/en/1.6/ref/contrib/admin/
    • Provides a documentation utility that pulls from the docstrings of install apps
      • https://docs.djangoproject.com/en/1.6/ref/contrib/admin/admindocs/
    • Extremely customizable
      • Should not customize heavily, create a custom dashboard for your clients
    • Built for site administrators, not end users
    • Custom skins available
      • https://www.djangopackages.com/grids/g/admin-styling/

    django routes and f-b views

    • Allows for clean and reusable URLs
    • Routes are defined in a python file called urls.py
      • Python code
      • Maps patterns (regex) to Python classes/functions
    • Request processing:
      • Django checks ROOT_URLCONF
      • Django loads urlpatterns
      • Django searches until it finds a match
      • Django calls the given view (a function or class)
        • Passes HttpRequest and positional or named arguments (if any exist)
      • If no match is found, an error-handling view is returned

    Django routes and f-b views

    • RESTful URL design (https://zapier.com/learn/apis/chapter-6-api-design)
      • In the end, design is up to you
      • Convention says, each resource gets 2 URL patterns (or endpoints)
        • /plural - handles GET and POST
        • /plural/id - handles GET, PUT and DELETE
      • Data transfer options
        • XML
        • JSON - easier to work with, more readable
      • Advanced endpoints
        • /plural/id/plural/id
        • Allows you to string resources together
        • Query String for searching

    DJANGO ROUTES AND F-B VIEWS

    • F-B (Function-based) views
      • A view that is backed by a python function
        • Accepts a request
        • Returns a response
          • XML, JSON or HTML
      • Exist in almost every Django project
    • Some view best practices
      • Should not contain business logic, just presentation logic
      • Keep the views as simple as possible
      • Do not repeat code
        • Abstract similar code into utility functions
        • Some utility functions can become decorators
        • @require_http_methods

    REST SERIALIZERS AND C-B VIEWS

    • Serializers are simple

    class TaskSerializer(serializers.ModelSerializer):
    class Meta:
    model = Task

      • Ties serializer fields to corresponding Task fields
      • They are customizable
    • Class-based views
      • Allow you to inherit behaviors from a super class
        • Generic Views - give you common view behavior for lists and details
        • Mixins

    REST SERIALIZERS AND C-B VIEWS

    • Mixins
      • ListModelMixin
        • provides .list, returns status code 200 or 404
      •  CreateModelMixin
        • provides .create (creates and saves), returns status code 201 or 400 
      • RetrieveModelMixin
        • provides .retrieve, returns status code 200 or 404
      • UpdateModelMixin
        • provides .update, returns status code 200, 201 or 400
        • Also allows for PATCH (which is a partial update)
      • DestroyModelMixin
        • provides .delete, returns status code 204 or 404

    browsable API

    • Very similar to Chrome's postman plugin
    • Makes it extremely easy to test back-end without having a front-end interface
      • In turn, this gives you a definite separation of concerns - the back-end developer can code and test independent of your front-end developer

    AngularJS Single Page app (spa)

    • A Web application that tries to mimic desktop behavior
    • Consists of a single Web page
      • Pieces are replaced based on routes or states
      • Replacement happens without hitting the server
    • Came about after years of refactoring
      • jQuery made JavaScript development more pleasurable
      • AngularJS (and other frameworks like it) have taken this pleasure a step further
    • Reference: http://singlepageappbook.com/goal.html

    retrieve tasks

    • Cross-Origin Resource Sharing (CORS)
      • Mechanism that allows clients to interact with servers
      • The server includes header information telling the browser when domain requests are allowed
    • Angular Routing
      • ngRoute
        • Built into Angular
        • Organized around URL routes
      • ui-route
        • Third-party library
        • Organized around states
        • Popular for complex projects with nested views

    Retrieve tasks

    • Restangular
      • Third-party library that wraps Angular's built-in $resource service.
      • Allows you to interact with a RESTful API simply
    • Directives
      • Reusable Web components, elements or attributes
      • Should do one job really well
      • Should not be application-specific
      • ngApp (ng-app)
        • Bootstraps Angular application

    retrieve tasks

    • Directives (cont.)
      • ngClick (ng-click)
        • Event handler bound to a scope function
      • ngShow/ngHide (ng-show/ng-hide)
        • ng-hide: will hide element if truthy
        • ng-show: will show element if truthy
      • ngRepeat (ng-repeat)
        • Iterates over collection, repeating the tag to which it is tied
      • ngBind
        • Replaces the text content of an HTML element
        • Changes when bound expression changes

    Retrieve tasks

    • Controllers
      • $scope
        • Data that represents the view model
        • Can watch expressions and propagate events 
      • Two-way data binding
        • Automatic synchronization of data between the model  ($scope) and the view
        • Any change to the model in the view or controller is reflected in both

    Retrieve tasks

    • Services
      • Reusable pieces of code
      • Wired into other functions through Dependency Injection
      • Lazily instantiated – Angular only instantiates a service when an application component depends on it.
      • Singletons – Each component dependent on a service gets a reference to the single instance generated by the service factory.
      • Built-in services start with a $
    • Filters
      • Formats the value of an expression for display to the user
      • Can be used in views, controllers or services

    search tasks

    • Filters are applied to expressions with the following syntax

    {{ expression | filter }}
    • Filters can be chained together

    {{ expression | filter1 | filter2 }}

    • They can be injected into a controller or service and are used like a function

    $scope.result = customFilter(params...)

    create tasks

    • Asynchronous calls
      • Allows you to continue processing without waiting on the call
      • Progress bar is driven by a $scope variable that is initially set to false, then true once the call comes back
    • Toast
      • A really nice way to show messages to the end user
      • Very customizable

    update tasks

    • $modal
      • http://angular-ui.github.io/bootstrap/#/modal
      • Allows you to quickly create AngularJS-powered modal windows
    • $on
      • Listens for events of a given type
    • $broadcast
      • Dispatches events downward to child scopes
    • $emit
      • Dispatches events upward to parent scopes
    • $rootScope
      • Parent of all other scopes
      • Can be injected into controllers, services, etc.

    delete tasks

    • splice
      • removes an item from an array
      • takes an index
      • a second argument will tell how many elements from that point need to be removed

    deploy to heroku

    • Procfile
    • Front-end - package.json
    • dj-static
      • Helps to gather static files on remote server
    • dj-database-url
      • Allows you to use Heroku's internal database configs to connect to your database
    • Environment variables are your friend
    • Heroku houses your code in its own Git repository
      • Using heroku-toolbelt, heroku's remote repo is added automatically

    conclusion






    Django + Angular = Possibly Great

    Djangular

    By dstephenson

    Djangular

    • 3,145