Django and React in Modern Web Apps

Django and React in Modern Web Apps

Presented at PyCon LT 2017.

Looks at why and how to combine Django and React, making your user interface more modular and easier to work with. Also briefly covers creating APIs, and running everything in Docker.

895ac7b84a280f686b70e2a70a8f5cd9?s=128

Rivo Laks

May 13, 2017
Tweet

Transcript

  1. Django and React in Modern Web Apps Rivo Laks ⋅

    Thorgate 2017-05-13
  2. Who is Rivo? Rivo Laks

  3. Who is Rivo? Rivo Laks Python for ~8 yrs, Django

    for ~6 yrs
  4. Who is Rivo? Rivo Laks Python for ~8 yrs, Django

    for ~6 yrs CTO of Thorgate
  5. Who is Rivo? Rivo Laks Python for ~8 yrs, Django

    for ~6 yrs CTO of Thorgate Thorgate is Estonian web agency / VC
  6. Who is Rivo? Rivo Laks Python for ~8 yrs, Django

    for ~6 yrs CTO of Thorgate Thorgate is Estonian web agency / VC Mostly web-based projects, using Django & React
  7. Motivation Django is very good choice for backend dev

  8. Motivation Django is very good choice for backend dev For

    frontend though, Javascript cannot be ignored
  9. Motivation Django is very good choice for backend dev For

    frontend though, Javascript cannot be ignored Python is great for glueing together various technologies
  10. Motivation Django is very good choice for backend dev For

    frontend though, Javascript cannot be ignored Python is great for glueing together various technologies Let's combine the two!
  11. Decisions

  12. Goals Use Django for backend Use modern JS & React

    for dynamic frontend
  13. Goals Use Django for backend Use modern JS & React

    for dynamic frontend Frontend should use APIs to access data
  14. Goals Use Django for backend Use modern JS & React

    for dynamic frontend Frontend should use APIs to access data Use Docker for easy deploys
  15. React JS library for building user interfaces

  16. React JS library for building user interfaces Built by Facebook,

    open-sourced in March 2015
  17. React JS library for building user interfaces Built by Facebook,

    open-sourced in March 2015 Not a full framework, easy to get started with
  18. React JS library for building user interfaces Built by Facebook,

    open-sourced in March 2015 Not a full framework, easy to get started with Brings declarative thinking to JS
  19. Single Page Apps Should we create an SPA?

  20. Single Page Apps Should we create an SPA? SPAs have

    steep learning curve
  21. Single Page Apps Should we create an SPA? SPAs have

    steep learning curve React makes it easy to start incrementally
  22. Single Page Apps Should we create an SPA? SPAs have

    steep learning curve React makes it easy to start incrementally Can move to full SPA later (or immediately), if desired
  23. Single Page Apps Should we create an SPA? SPAs have

    steep learning curve React makes it easy to start incrementally Can move to full SPA later (or immediately), if desired Use your Django expertise, add React where needed
  24. Tooling

  25. Tooling Django REST framework for APIs

  26. Tooling Django REST framework for APIs Webpack for bundling JS/CSS

  27. Tooling Django REST framework for APIs Webpack for bundling JS/CSS

    Docker for easy & consistent environments
  28. Let's Get Started!

  29. Existing Django View + Template # myapp/views.py class MyAppView(TemplateView): template_name

    = 'myapp.html' <!-- myapp.html --> {% extends "base.html" %} {% block content %} Hello! {% endblock %}
  30. Add a container HTML element to your page: {% block

    content %} <div id="container"> <div class="loading-indicator"> Loading... </div> </div> {% endblock %}
  31. Add a container HTML element to your page: {% block

    content %} <div id="container"> <div class="loading-indicator"> Loading... </div> </div> {% endblock %} {% block scripts %}{{ block.super }} <script> myapp.init(); </script> {% endblock %}
  32. De ne the JS init() function to render the React

    component into container function init() { const container = document.getElementById('container'); ReactDOM.render(<HelloMessage name="PyCon LT" />, container); } HelloMessage is a React component.
  33. Simple React components function HelloMessage(props) { return ( <div className="message">

    Hello {props.name}! </div> ); } // init() function ReactDOM.render(<HelloMessage name="PyCon LT" />, container);
  34. Stateful React components For more complex components

  35. Stateful React components For more complex components Add local state,

    de ne event handlers, etc
  36. Stateful React components For more complex components Add local state,

    de ne event handlers, etc There will be some code duplication
  37. class MyApp extends React.Component { constructor(props) { super(props); this.state =

    { counter: 1, }; } increaseCount() { this.setState({counter: this.state.counter + 1}); } render() { return ( <div className="app"> <HelloMessage name={this.prop.name} /> Counter: {this.state.counter} <button onClick={() => this.increaseCount()}>Increase</button> </div> ); } }
  38. What next? Use React Devtools in browser

  39. What next? Use React Devtools in browser Add Redux for

    managing data
  40. What next? Use React Devtools in browser Add Redux for

    managing data Look at React Router and SPAs
  41. What next? Use React Devtools in browser Add Redux for

    managing data Look at React Router and SPAs Don't do it all at once
  42. Getting data from Django to JS

  43. Initial data can be passed in Django template, as JSON:

    <script> var MYAPP_DATA = { user: { email: "{{ request.user.email|escapejs }}", name: "{{ request.user.name|escapejs }}", }, // 'items' is JSON-serialized data items: {{ items|safe }}, }; </script> function init() { const container = document.getElementById('container'); ReactDOM.render(<MyApp items={MYAPP_DATA.items} />, container); }
  44. Using APIs For loading interactive data, create APIs with Django

    REST framework.
  45. Using APIs For loading interactive data, create APIs with Django

    REST framework. Integrates with Django's models and authentication
  46. Using APIs For loading interactive data, create APIs with Django

    REST framework. Integrates with Django's models and authentication Built-in functionality includes paging, throttling, validation, etc
  47. Using APIs For loading interactive data, create APIs with Django

    REST framework. Integrates with Django's models and authentication Built-in functionality includes paging, throttling, validation, etc Browsable APIs
  48. None
  49. Javascript side fetch() is the standard approach

  50. Javascript side fetch() is the standard approach async / await

    help keep your code clean
  51. Javascript side fetch() is the standard approach async / await

    help keep your code clean class MyApp extends React.Component { async loadData() { const response = await fetch('/api/data/', {credentials: 'include'}); const data = await response.json(); this.setState(data); } onRefresh() { this.loadData(); }
  52. Environments & Deploys

  53. Bundling JS & CSS with Webpack We have Javascript /

    React sources
  54. Bundling JS & CSS with Webpack We have Javascript /

    React sources We want nal JS that browsers can read
  55. Bundling JS & CSS with Webpack We have Javascript /

    React sources We want nal JS that browsers can read Webpack – JS module bundler
  56. Webpack in a Nutshell

  57. Webpack Advantages Bundles everything into one (or few) les

  58. Webpack Advantages Bundles everything into one (or few) les Mini

    es the bundles
  59. Webpack Advantages Bundles everything into one (or few) les Mini

    es the bundles You can use ES2015, Sass, etc
  60. Docker We use Docker in dev & production

  61. Docker We use Docker in dev & production Reproducability and

    consistency
  62. Docker We use Docker in dev & production Reproducability and

    consistency Makes dev env easy to setup
  63. Docker 101

  64. Docker 101 Easily run speci c version of Python: docker

    run -it python:3.6.1
  65. Docker 101 Easily run speci c version of Python: docker

    run -it python:3.6.1 Volumes for persisting data: docker run -it -v $PWD:/app python:3.6.1
  66. Docker 101 Easily run speci c version of Python: docker

    run -it python:3.6.1 Volumes for persisting data: docker run -it -v $PWD:/app python:3.6.1 Run Jupyter SciPy notebook: docker run -p 8888:8888 -v $PWD:/home/jovyan/work jupyter/scipy-notebook
  67. Docker Compose Docker Compose is “a tool for de ning

    and running multi-container Docker applications”
  68. Docker Compose Docker Compose is “a tool for de ning

    and running multi-container Docker applications” de ne & control multiple containers at once
  69. Docker Compose Docker Compose is “a tool for de ning

    and running multi-container Docker applications” de ne & control multiple containers at once easier networking among single app's services
  70. None
  71. How Docker helps us Consistent & easy envs

  72. How Docker helps us Consistent & easy envs Setup dev

    env with make setup
  73. How Docker helps us Consistent & easy envs Setup dev

    env with make setup Much easier to add dependent services
  74. Docker Pitfalls Tooling can be problematic

  75. Docker Pitfalls Tooling can be problematic Don't leave your ports

    exposed
  76. Docker Pitfalls Tooling can be problematic Don't leave your ports

    exposed There will be dragons
  77. Conclusions Don't let Javascript scare you, embrace it

  78. Conclusions Don't let Javascript scare you, embrace it You can

    start using React incrementally
  79. Conclusions Don't let Javascript scare you, embrace it You can

    start using React incrementally Use Django REST framework for APIs
  80. Conclusions Don't let Javascript scare you, embrace it You can

    start using React incrementally Use Django REST framework for APIs Docker helps with env setup
  81. Thanks! Rivo Laks ⋅ @rivolaks ⋅ rivolaks.com CTO at Thorgate

    ⋅ thorgate.eu Have a look at our Django project template: https://github.com/thorgate/django-project-template