Upgrade to Pro — share decks privately, control downloads, hide ads and more …

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.

Rivo Laks

May 13, 2017
Tweet

More Decks by Rivo Laks

Other Decks in Programming

Transcript

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

    for ~6 yrs CTO of Thorgate Thorgate is Estonian web agency / VC
  2. 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
  3. Motivation Django is very good choice for backend dev For

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

    frontend though, Javascript cannot be ignored Python is great for glueing together various technologies
  5. 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!
  6. Goals Use Django for backend Use modern JS & React

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

    for dynamic frontend Frontend should use APIs to access data Use Docker for easy deploys
  8. React JS library for building user interfaces Built by Facebook,

    open-sourced in March 2015 Not a full framework, easy to get started with
  9. 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
  10. Single Page Apps Should we create an SPA? SPAs have

    steep learning curve React makes it easy to start incrementally
  11. 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
  12. 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
  13. Tooling Django REST framework for APIs Webpack for bundling JS/CSS

    Docker for easy & consistent environments
  14. Existing Django View + Template # myapp/views.py class MyAppView(TemplateView): template_name

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

    content %} <div id="container"> <div class="loading-indicator"> Loading... </div> </div> {% endblock %}
  16. 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 %}
  17. 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.
  18. Simple React components function HelloMessage(props) { return ( <div className="message">

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

    de ne event handlers, etc There will be some code duplication
  20. 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> ); } }
  21. What next? Use React Devtools in browser Add Redux for

    managing data Look at React Router and SPAs
  22. 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
  23. 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); }
  24. Using APIs For loading interactive data, create APIs with Django

    REST framework. Integrates with Django's models and authentication
  25. 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
  26. 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
  27. 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(); }
  28. Bundling JS & CSS with Webpack We have Javascript /

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

    React sources We want nal JS that browsers can read Webpack – JS module bundler
  30. Webpack Advantages Bundles everything into one (or few) les Mini

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

    consistency Makes dev env easy to setup
  32. 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
  33. 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
  34. Docker Compose Docker Compose is “a tool for de ning

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

    and running multi-container Docker applications” de ne & control multiple containers at once
  36. 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
  37. How Docker helps us Consistent & easy envs Setup dev

    env with make setup Much easier to add dependent services
  38. Conclusions Don't let Javascript scare you, embrace it You can

    start using React incrementally Use Django REST framework for APIs
  39. 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
  40. 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