SlideShare a Scribd company logo
1 of 64
Download to read offline
CREATING A FULL STACK WEB APP WITH
PYTHON, NPM, WEBPACK AND REACT
by Angela Branaes
THE STRUCTURE OF A WEB APP
➤ Separated into front and back end.
➤ Multiple technologies.
➤ Front end is:
➤ Look and feel.
➤ User interaction.
➤ Back end is:
➤ Long running operations.
➤ Data, and data processing.
➤ Application logic.
INITIAL PROJECT SETUP
➤ Create the following directory structure
.
├── README.md
└── fullstack_template/
├── server/
└── static/
├── css/
├── dist/
├── images/
└── js/
$ cd fullstack_template/static
WE’RE GOING TO NEED A JAVASCRIPT PACKAGE MANAGER
➤ Using a package manager makes it painless to:

➤ Keep your project dependencies up to date.

➤ Fetch and install new packages.

➤ Similar to brew, pip, pacman etc.
NPM
NPM = NODE PACKAGE MANAGER
➤ Automatically included with Node.js

➤ Easy to use

➤ well documented

➤ nearly 500 000 packages available

➤ Initialise NPM:

$ npm init
➤ This creates a file called package.json
OUR UPDATED DIRECTORY TREE
.
├── README.md
└── fullstack_template/
├── server/
└── static/
├── css/
├── dist/
├── images/
├── js/
└── package.json
THE PURPOSE OF PACKAGE.JSON
1. Keeps track of dependencies and versions.

2. Informs other developers about your project.

3. Makes installing, running and updating a project automatic and reproducible
THIS IS MY PACKAGE.JSON
{
"name": "FullStackTemplate",
"version": "1.0.0",
"description": "Fullstack Template",
"main": "index.jsx",
"scripts": {
"test": "echo "Error: no test specified" && exit 1",
},
"keywords": [
"python",
"react",
"npm",
"webpack"
],
"author": "Angela Branaes",
"license": "MIT",
"devDependencies": {
"webpack": "^3.0.0"
}
}
WHY WE NEED A MODULE BUNDLER
➤ Minimises the number of <script> tags in your HTML
➤ This means faster loading, and less hassle.
➤ Don’t need to worry about bundle import ordering!
➤ Don’t have to use globals or namespacing.
➤ Lazy module loading.
➤ We will be using Webpack.
WEBPACK
WEBPACK
➤ Only understands JavaScript.
➤ Everything else needs a loader or plugin.
➤ Everything is a module.
➤ You can require() JavaScript, React, CSS or images.
➤ Creates a dependency tree of all your required modules, and packages those into
bundles.
➤ Easy to get started with, if you only need JavaScript.
➤ Minor learning curve for css/less and image loading.
➤ Lets you split your bundles and load them asynchronously and lazily.
➤ Integrates seamlessly with npm.
INSTALL & CONFIGURE WEBPACK
➤ Install webpack:
$ npm i webpack --save-dev
➤ Add a file named webpack.config.js:
const webpack = require(‘webpack');
const config = {
entry: __dirname + '/js/index.jsx',
output: {
path: __dirname + '/dist',
filename: 'bundle.js',
},
resolve: {
extensions: ['.js', '.jsx', '.css']
},
};
module.exports = config;
OUR UPDATED DIRECTORY TREE
.
├── README.md
└── fullstack_template/
├── server/
└── static/
├── css/
├── dist/
├── images/
├── js/
├── package.json
└── webpack.config.js
SINGLE VS MULTI PAGE APPLICATIONS
➤ I mostly use Webpack for single page applications.
➤ You can also use webpack for multi page applications:
entry: {

“indexPage”: __dirname + “js/index.jsx”,

“aboutPage”: __dirname + “js/about.jsx”
},
output: {
path: __dirname + “/dist”,

filename: “[name].js” //e.g. aboutPage.js
}
LET’S DISPLAY AN ALERT!
OUR UPDATED DIRECTORY TREE
.
├── README.md
└── fullstack_template/
├── server/
└── static/
├── css/
├── dist/
│ └── bundle.js
├── images/
├── js/
│ └── index.jsx
├── index.html
├── package.json
└── webpack.config.js
CREATE INDEX.HTML
➤ A really simple index.html is all you need.
➤ The index.html just loads your JavaScript bundle
<body>
<div id="content" />
<script src="dist/bundle.js" type=“text/javascript”>
</script>
</body>
➤ All the layout and behaviour live in the JS/React files!
CREATE INDEX.JSX
➤ Just 1 line of Plain Old JavaScript
alert(“Hello World!”);
BUILDING YOUR APPLICATION
➤ Create run commands to simplify building your code.
➤ Run commands are just aliases.
➤ Example from my package.json:
“scripts": {
"watch": "webpack --progress -d --config webpack.config.js —watch"
}
➤ Makes the dev process more fluid.
➤ I always add the following:
➤ build
➤ dev-build
➤ watch
START THE WATCH COMMAND
➤ Any changes get built automatically
$ npm run watch
➤ Open index.html….
CREATING A SIMPLE REACT APP
THE BENEFITS OF USING REACT
➤ Easy to build UIs composed of small, distinct components.
➤ Encourages design of reusable UI components.
➤ Easier to understand what’s going on when markup lives with the code (JSX).
➤ Automatic re-rendering of components on change.
➤ Easy to maintain.
INSTALL REACT
$ npm i react react-dom —save-dev
REACTIFY INDEX.JSX
import React from "react";
import ReactDOM from "react-dom";
import App from “./App";
ReactDOM.render(<App />, document.getElementById("content"));
ADD A REACT “APP” CLASS
➤ Remember to export your react classes!
// App.jsx
import React from “react”;
export default class App extends React.Component {
render () {
return <p> Hello React!</p>;
}
}
OUR UPDATED DIRECTORY TREE
.
├── README.md
└── fullstack_template/
├── server/
└── static/
├── css/
├── dist/
├── images/
├── js/
│ ├── index.jsx
│ └── App.jsx
├── index.html
├── package.json
└── webpack.config.js
WHAT IS JSX?
➤ Syntax extension to JavaScript.
➤ Optimised on compilation, so faster than JavaScript.
➤ Statically typed and mostly type-safe. JavaScript is not.
➤ Lets you write HTML tags in your JavaScript functions:
<Hello name=“Rimini” />
instead of
React.createElement(Hello, {name: “Rimini}, null)
➤ Recognises upper-case element-types as written in React. E.g. <Hello />
➤ How do we make our browser understand JSX?
INTRODUCING BABEL
Write next-generation javascript right now!
Transform JSX to JS.
ADD BABEL
➤ Install Babel
➤ Add the Babel presets to the package.json:
“babel”: {
“presets”: [
“es2015”,
“react”
]
},
ADD A BABEL-LOADER RULE TO THE WEBPACK CONFIG:
module: {
rules: [
{
test: /.jsx?/,
exclude: /node_modules/,
use: 'babel-loader'
}
]
}
OPEN INDEX.HTML IN YOUR BROWSER
➤ This should now show the “Hello React” paragraph we added in our new React
App.jsx file.
PYTHON FLASK SERVER
PYTHON
➤ Go to the server folder
➤ Ensure you’re in a Python virtualenv
$ mkvirtualenv fullstack
➤ Install Flask
(fullstack)$ pip install flask
➤ Create a file called server.py in the server folder
OUR UPDATED DIRECTORY TREE
.
├── README.md
└── fullstack_template/
├── server/
│ └── server.py
└── static/
├── css/
├── dist/
├── images/
├── js/
│ ├── index.jsx
│ └── App.jsx
├── index.html
├── package.json
└── webpack.config.js
SERVER.PY
from flask import Flask, render_template
app = Flask(__name__, static_folder=“../static/dist",
template_folder="../static")
@app.route("/")
def index():
return render_template("index.html")
@app.route("/hello")
def hello():
return "Hello World!”
if __name__ == "__main__":
app.run()
START THE SERVER
➤ Go to: http://localhost:5000/
$ python server.py
REQUEST INFO FROM THE SERVER
var $ = require(‘jquery');
getPythonHello() {
$.get(window.location.href + 'hello', (data) => {
console.log(data);
this.personaliseGreeting(data);
});
}
MAKE PYTHON DO SOMETHING MORE INTERESTING
➤ We call get_hello() whenever we hit the /hello endpoint
def get_hello():
greeting_list = ['Ciao', 'Hei', 'Salut', 'Hola', 'Hallo', 'Hej']
return random.choice(greeting_list)
SAY HI TO SOMEONE SPECIAL
➤ There should be a class for that!

➤ Change the App.jsx render method to the following:

render () {
return (
<PageHeader>
<div className='header-contents'>
<Hello name='Rimini' />
</div>
</PageHeader>
);
)
OUR UPDATED DIRECTORY TREE
.
├── README.md
└── fullstack_template/
├── server/
│ └── server.py
└── static/
├── css/
├── dist/
├── images/
├── js/
│ ├── index.jsx
│ ├── App.jsx
│ └── Hello.jsx
├── index.html
├── package.json
└── webpack.config.js
CREATE THE HELLO CLASS
export default class Hello extends React.Component {
constructor(props) {
super(props);
// greeting is now “Hello Rimini”
this.state = {greeting: 'Hello ' + this.props.name};
// This binding is necessary to make `this`
// work in the button callback
this.getPythonHello = this.getPythonHello.bind(this);
}
}
➤ Add this function to the Hello class:
➤ This will re-render the greeting on our website to a new one when called.
personaliseGreeting(greeting) {
this.setState({greeting: greeting + ' ' + this.props.name + '!'});
}
LET’S FINALLY RENDER OUR HELLO!
render () {
return (
<h1>{this.state.greeting}</h1>
<hr/>
<Button onClick={this.getPythonHello}>
Say Hello!
</Button>
);
}
CREATE A NICE LAYOUT WITH CSS
➤ Webpack ONLY understands JavaScript.
➤ Install the following loaders and plugins:
➤ style-loader
➤ css-loader
➤ extract-text-webpack-plugin
➤ Add a plugin to the webpack config:
plugins: [
new ExtractTextPlugin('styles.css'),
]
OUR UPDATED DIRECTORY TREE
.
├── README.md
└── fullstack_template/
├── server/
│ └── server.py
└── static/
├── css/
│ └── fullstack.css
├── dist/
│ ├── bundle.js
│ └── styles.css
├── images/
├── js/
│ ├── index.jsx
│ ├── App.jsx
│ └── Hello.jsx
├── index.html
├── package.json
└── webpack.config.js
➤ Add fullstack.css to the css folder
➤ Add a few css rules for our header
➤ require fullstack.css in App.jsx:
require(‘../css/fullstack.css');
➤ Add the bundled css to the index.html:
<link rel="stylesheet" href="dist/styles.css">
OUR UPDATED DIRECTORY TREE
.
├── README.md
└── fullstack_template/
├── server/
│ └── server.py
└── static/
├── css/
│ └── fullstack.css
├── dist/
│ ├── bundle.js
│ └── styles.css
├── images/
│ └── header.png
├── js/
│ ├── index.jsx
│ ├── App.jsx
│ └── Hello.jsx
├── index.html
├── package.json
└── webpack.config.js
ADD A NICE BACKGROUND IMAGE
1. Add the file-loader loader
2. Add an image to your images/ folder
3. Set the image to be your header background in the fullstack.css file
background-image: url(‘../images/header.jpg’);
4. NOTE: you have to load the image in your React app for it to show up!
IN APP.JSX
import HeaderBackgroundImage from ‘../images/header.jpg’;
➤ Add this fn to your class:
addHeaderImg() {
let headerBg = new Image();
headerBg.src = HeaderBackgroundImage;
}
➤ And this to your render():
{this.addHeaderImg()}
THANK YOU! ANY QUESTIONS?
@angineering
@angineering - The code is on GitHub:
https://github.com/angineering/FullStackTemplate
@angineering - This talk is also a blogpost

More Related Content

What's hot

Vagrant crash course
Vagrant crash courseVagrant crash course
Vagrant crash courseMarcus Deglos
 
Fast Paced Drupal 8: Accelerating Development with Composer, Drupal Console a...
Fast Paced Drupal 8: Accelerating Development with Composer, Drupal Console a...Fast Paced Drupal 8: Accelerating Development with Composer, Drupal Console a...
Fast Paced Drupal 8: Accelerating Development with Composer, Drupal Console a...Acquia
 
Godefroid Chapelle Ajax With Plone 3 Kss Development Patterns
Godefroid Chapelle   Ajax With Plone 3   Kss Development PatternsGodefroid Chapelle   Ajax With Plone 3   Kss Development Patterns
Godefroid Chapelle Ajax With Plone 3 Kss Development PatternsVincenzo Barone
 
Hitchhiker's guide to the front end development
Hitchhiker's guide to the front end developmentHitchhiker's guide to the front end development
Hitchhiker's guide to the front end development정윤 김
 
Front end performance optimization
Front end performance optimizationFront end performance optimization
Front end performance optimizationStevie T
 
Vagrant for real codemotion (moar tips! ;-))
Vagrant for real codemotion (moar tips! ;-))Vagrant for real codemotion (moar tips! ;-))
Vagrant for real codemotion (moar tips! ;-))Michele Orselli
 
Introduction to Webpack - Ordina JWorks - CC JS & Web
Introduction to Webpack - Ordina JWorks - CC JS & WebIntroduction to Webpack - Ordina JWorks - CC JS & Web
Introduction to Webpack - Ordina JWorks - CC JS & WebJWORKS powered by Ordina
 
Vagrant for Virtualized Development
Vagrant for Virtualized DevelopmentVagrant for Virtualized Development
Vagrant for Virtualized DevelopmentAdam Culp
 
Rock-solid Magento Development and Deployment Workflows
Rock-solid Magento Development and Deployment WorkflowsRock-solid Magento Development and Deployment Workflows
Rock-solid Magento Development and Deployment WorkflowsAOE
 
Front end performance tip
Front end performance tipFront end performance tip
Front end performance tipSteve Yu
 
WebPagetest Power Users - Velocity 2014
WebPagetest Power Users - Velocity 2014WebPagetest Power Users - Velocity 2014
WebPagetest Power Users - Velocity 2014Patrick Meenan
 
Node JS Express : Steps to Create Restful Web App
Node JS Express : Steps to Create Restful Web AppNode JS Express : Steps to Create Restful Web App
Node JS Express : Steps to Create Restful Web AppEdureka!
 
#3 Hanoi Magento Meetup - Part 2: Scalable Magento Development With Containers
#3 Hanoi Magento Meetup - Part 2: Scalable Magento Development With Containers#3 Hanoi Magento Meetup - Part 2: Scalable Magento Development With Containers
#3 Hanoi Magento Meetup - Part 2: Scalable Magento Development With ContainersHanoi MagentoMeetup
 
Single page apps with drupal 7
Single page apps with drupal 7Single page apps with drupal 7
Single page apps with drupal 7Chris Tankersley
 
Pyramid Deployment and Maintenance
Pyramid Deployment and MaintenancePyramid Deployment and Maintenance
Pyramid Deployment and MaintenanceJazkarta, Inc.
 

What's hot (20)

Vagrant crash course
Vagrant crash courseVagrant crash course
Vagrant crash course
 
WPDay Bologna 2013
WPDay Bologna 2013WPDay Bologna 2013
WPDay Bologna 2013
 
Fast Paced Drupal 8: Accelerating Development with Composer, Drupal Console a...
Fast Paced Drupal 8: Accelerating Development with Composer, Drupal Console a...Fast Paced Drupal 8: Accelerating Development with Composer, Drupal Console a...
Fast Paced Drupal 8: Accelerating Development with Composer, Drupal Console a...
 
Godefroid Chapelle Ajax With Plone 3 Kss Development Patterns
Godefroid Chapelle   Ajax With Plone 3   Kss Development PatternsGodefroid Chapelle   Ajax With Plone 3   Kss Development Patterns
Godefroid Chapelle Ajax With Plone 3 Kss Development Patterns
 
BPMS1
BPMS1BPMS1
BPMS1
 
Hitchhiker's guide to the front end development
Hitchhiker's guide to the front end developmentHitchhiker's guide to the front end development
Hitchhiker's guide to the front end development
 
Front end performance optimization
Front end performance optimizationFront end performance optimization
Front end performance optimization
 
Vagrant
VagrantVagrant
Vagrant
 
Front End Performance
Front End PerformanceFront End Performance
Front End Performance
 
GlassFish Embedded API
GlassFish Embedded APIGlassFish Embedded API
GlassFish Embedded API
 
Vagrant for real codemotion (moar tips! ;-))
Vagrant for real codemotion (moar tips! ;-))Vagrant for real codemotion (moar tips! ;-))
Vagrant for real codemotion (moar tips! ;-))
 
Introduction to Webpack - Ordina JWorks - CC JS & Web
Introduction to Webpack - Ordina JWorks - CC JS & WebIntroduction to Webpack - Ordina JWorks - CC JS & Web
Introduction to Webpack - Ordina JWorks - CC JS & Web
 
Vagrant for Virtualized Development
Vagrant for Virtualized DevelopmentVagrant for Virtualized Development
Vagrant for Virtualized Development
 
Rock-solid Magento Development and Deployment Workflows
Rock-solid Magento Development and Deployment WorkflowsRock-solid Magento Development and Deployment Workflows
Rock-solid Magento Development and Deployment Workflows
 
Front end performance tip
Front end performance tipFront end performance tip
Front end performance tip
 
WebPagetest Power Users - Velocity 2014
WebPagetest Power Users - Velocity 2014WebPagetest Power Users - Velocity 2014
WebPagetest Power Users - Velocity 2014
 
Node JS Express : Steps to Create Restful Web App
Node JS Express : Steps to Create Restful Web AppNode JS Express : Steps to Create Restful Web App
Node JS Express : Steps to Create Restful Web App
 
#3 Hanoi Magento Meetup - Part 2: Scalable Magento Development With Containers
#3 Hanoi Magento Meetup - Part 2: Scalable Magento Development With Containers#3 Hanoi Magento Meetup - Part 2: Scalable Magento Development With Containers
#3 Hanoi Magento Meetup - Part 2: Scalable Magento Development With Containers
 
Single page apps with drupal 7
Single page apps with drupal 7Single page apps with drupal 7
Single page apps with drupal 7
 
Pyramid Deployment and Maintenance
Pyramid Deployment and MaintenancePyramid Deployment and Maintenance
Pyramid Deployment and Maintenance
 

Similar to Create Full Stack Web Apps with Python, React & Webpack

WEBPACK
WEBPACKWEBPACK
WEBPACKhome
 
How to Webpack your Django!
How to Webpack your Django!How to Webpack your Django!
How to Webpack your Django!David Gibbons
 
Webpack presentation
Webpack presentationWebpack presentation
Webpack presentationRAHUL SHARMA
 
Improving build solutions dependency management with webpack
Improving build solutions  dependency management with webpackImproving build solutions  dependency management with webpack
Improving build solutions dependency management with webpackNodeXperts
 
Ultimate Survival - React-Native edition
Ultimate Survival - React-Native editionUltimate Survival - React-Native edition
Ultimate Survival - React-Native editionRichard Radics
 
Introduction of webpack 4
Introduction of webpack 4Introduction of webpack 4
Introduction of webpack 4Vijay Shukla
 
Modern Web Application Development Workflow - EclipseCon Europe 2014
Modern Web Application Development Workflow - EclipseCon Europe 2014Modern Web Application Development Workflow - EclipseCon Europe 2014
Modern Web Application Development Workflow - EclipseCon Europe 2014Stéphane Bégaudeau
 
Magento 2 Development
Magento 2 DevelopmentMagento 2 Development
Magento 2 DevelopmentDuke Dao
 
Zero Downtime Deployment with Ansible
Zero Downtime Deployment with AnsibleZero Downtime Deployment with Ansible
Zero Downtime Deployment with AnsibleStein Inge Morisbak
 
2019 Chef InSpec Jumpstart Part 2 of 2
2019 Chef InSpec Jumpstart Part 2 of 22019 Chef InSpec Jumpstart Part 2 of 2
2019 Chef InSpec Jumpstart Part 2 of 2Larry Eichenbaum
 
Modern Web Application Development Workflow - EclipseCon France 2014
Modern Web Application Development Workflow - EclipseCon France 2014Modern Web Application Development Workflow - EclipseCon France 2014
Modern Web Application Development Workflow - EclipseCon France 2014Stéphane Bégaudeau
 
ReactJS software installation
ReactJS software installationReactJS software installation
ReactJS software installationHopeTutors1
 
How to install ReactJS software
How to install ReactJS software How to install ReactJS software
How to install ReactJS software VigneshVijay21
 
Zero Downtime Deployment with Ansible
Zero Downtime Deployment with AnsibleZero Downtime Deployment with Ansible
Zero Downtime Deployment with AnsibleStein Inge Morisbak
 
Room with a Vue - Introduction to Vue.js
Room with a Vue - Introduction to Vue.jsRoom with a Vue - Introduction to Vue.js
Room with a Vue - Introduction to Vue.jsZachary Klein
 
Getting Started with React v16
Getting Started with React v16Getting Started with React v16
Getting Started with React v16Benny Neugebauer
 

Similar to Create Full Stack Web Apps with Python, React & Webpack (20)

WEBPACK
WEBPACKWEBPACK
WEBPACK
 
How to Webpack your Django!
How to Webpack your Django!How to Webpack your Django!
How to Webpack your Django!
 
Webpack presentation
Webpack presentationWebpack presentation
Webpack presentation
 
Improving build solutions dependency management with webpack
Improving build solutions  dependency management with webpackImproving build solutions  dependency management with webpack
Improving build solutions dependency management with webpack
 
Nuxtjs cheat-sheet
Nuxtjs cheat-sheetNuxtjs cheat-sheet
Nuxtjs cheat-sheet
 
Ultimate Survival - React-Native edition
Ultimate Survival - React-Native editionUltimate Survival - React-Native edition
Ultimate Survival - React-Native edition
 
ReactJS Workflows
ReactJS WorkflowsReactJS Workflows
ReactJS Workflows
 
Introduction of webpack 4
Introduction of webpack 4Introduction of webpack 4
Introduction of webpack 4
 
Modern Web Application Development Workflow - EclipseCon Europe 2014
Modern Web Application Development Workflow - EclipseCon Europe 2014Modern Web Application Development Workflow - EclipseCon Europe 2014
Modern Web Application Development Workflow - EclipseCon Europe 2014
 
Magento 2 Development
Magento 2 DevelopmentMagento 2 Development
Magento 2 Development
 
Zero Downtime Deployment with Ansible
Zero Downtime Deployment with AnsibleZero Downtime Deployment with Ansible
Zero Downtime Deployment with Ansible
 
2019 Chef InSpec Jumpstart Part 2 of 2
2019 Chef InSpec Jumpstart Part 2 of 22019 Chef InSpec Jumpstart Part 2 of 2
2019 Chef InSpec Jumpstart Part 2 of 2
 
Modern Web Application Development Workflow - EclipseCon France 2014
Modern Web Application Development Workflow - EclipseCon France 2014Modern Web Application Development Workflow - EclipseCon France 2014
Modern Web Application Development Workflow - EclipseCon France 2014
 
ReactJS software installation
ReactJS software installationReactJS software installation
ReactJS software installation
 
How to install ReactJS software
How to install ReactJS software How to install ReactJS software
How to install ReactJS software
 
Zero Downtime Deployment with Ansible
Zero Downtime Deployment with AnsibleZero Downtime Deployment with Ansible
Zero Downtime Deployment with Ansible
 
Learn react-js
Learn react-jsLearn react-js
Learn react-js
 
Room with a Vue - Introduction to Vue.js
Room with a Vue - Introduction to Vue.jsRoom with a Vue - Introduction to Vue.js
Room with a Vue - Introduction to Vue.js
 
Getting Started with React v16
Getting Started with React v16Getting Started with React v16
Getting Started with React v16
 
Love at first Vue
Love at first VueLove at first Vue
Love at first Vue
 

Recently uploaded

Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...OnePlan Solutions
 
2024 DevNexus Patterns for Resiliency: Shuffle shards
2024 DevNexus Patterns for Resiliency: Shuffle shards2024 DevNexus Patterns for Resiliency: Shuffle shards
2024 DevNexus Patterns for Resiliency: Shuffle shardsChristopher Curtin
 
VictoriaMetrics Q1 Meet Up '24 - Community & News Update
VictoriaMetrics Q1 Meet Up '24 - Community & News UpdateVictoriaMetrics Q1 Meet Up '24 - Community & News Update
VictoriaMetrics Q1 Meet Up '24 - Community & News UpdateVictoriaMetrics
 
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptx
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptxThe Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptx
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptxRTS corp
 
Pros and Cons of Selenium In Automation Testing_ A Comprehensive Assessment.pdf
Pros and Cons of Selenium In Automation Testing_ A Comprehensive Assessment.pdfPros and Cons of Selenium In Automation Testing_ A Comprehensive Assessment.pdf
Pros and Cons of Selenium In Automation Testing_ A Comprehensive Assessment.pdfkalichargn70th171
 
Best Angular 17 Classroom & Online training - Naresh IT
Best Angular 17 Classroom & Online training - Naresh ITBest Angular 17 Classroom & Online training - Naresh IT
Best Angular 17 Classroom & Online training - Naresh ITmanoharjgpsolutions
 
Data modeling 101 - Basics - Software Domain
Data modeling 101 - Basics - Software DomainData modeling 101 - Basics - Software Domain
Data modeling 101 - Basics - Software DomainAbdul Ahad
 
Understanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM ArchitectureUnderstanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM Architecturerahul_net
 
2024-04-09 - From Complexity to Clarity - AWS Summit AMS.pdf
2024-04-09 - From Complexity to Clarity - AWS Summit AMS.pdf2024-04-09 - From Complexity to Clarity - AWS Summit AMS.pdf
2024-04-09 - From Complexity to Clarity - AWS Summit AMS.pdfAndrey Devyatkin
 
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full Recording
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full RecordingOpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full Recording
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full RecordingShane Coughlan
 
Leveraging AI for Mobile App Testing on Real Devices | Applitools + Kobiton
Leveraging AI for Mobile App Testing on Real Devices | Applitools + KobitonLeveraging AI for Mobile App Testing on Real Devices | Applitools + Kobiton
Leveraging AI for Mobile App Testing on Real Devices | Applitools + KobitonApplitools
 
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdfEnhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdfRTS corp
 
Ronisha Informatics Private Limited Catalogue
Ronisha Informatics Private Limited CatalogueRonisha Informatics Private Limited Catalogue
Ronisha Informatics Private Limited Catalogueitservices996
 
GraphSummit Madrid - Product Vision and Roadmap - Luis Salvador Neo4j
GraphSummit Madrid - Product Vision and Roadmap - Luis Salvador Neo4jGraphSummit Madrid - Product Vision and Roadmap - Luis Salvador Neo4j
GraphSummit Madrid - Product Vision and Roadmap - Luis Salvador Neo4jNeo4j
 
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxUI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxAndreas Kunz
 
Strategies for using alternative queries to mitigate zero results
Strategies for using alternative queries to mitigate zero resultsStrategies for using alternative queries to mitigate zero results
Strategies for using alternative queries to mitigate zero resultsJean Silva
 
eSoftTools IMAP Backup Software and migration tools
eSoftTools IMAP Backup Software and migration toolseSoftTools IMAP Backup Software and migration tools
eSoftTools IMAP Backup Software and migration toolsosttopstonverter
 
Keeping your build tool updated in a multi repository world
Keeping your build tool updated in a multi repository worldKeeping your build tool updated in a multi repository world
Keeping your build tool updated in a multi repository worldRoberto Pérez Alcolea
 
What’s New in VictoriaMetrics: Q1 2024 Updates
What’s New in VictoriaMetrics: Q1 2024 UpdatesWhat’s New in VictoriaMetrics: Q1 2024 Updates
What’s New in VictoriaMetrics: Q1 2024 UpdatesVictoriaMetrics
 
Effectively Troubleshoot 9 Types of OutOfMemoryError
Effectively Troubleshoot 9 Types of OutOfMemoryErrorEffectively Troubleshoot 9 Types of OutOfMemoryError
Effectively Troubleshoot 9 Types of OutOfMemoryErrorTier1 app
 

Recently uploaded (20)

Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
 
2024 DevNexus Patterns for Resiliency: Shuffle shards
2024 DevNexus Patterns for Resiliency: Shuffle shards2024 DevNexus Patterns for Resiliency: Shuffle shards
2024 DevNexus Patterns for Resiliency: Shuffle shards
 
VictoriaMetrics Q1 Meet Up '24 - Community & News Update
VictoriaMetrics Q1 Meet Up '24 - Community & News UpdateVictoriaMetrics Q1 Meet Up '24 - Community & News Update
VictoriaMetrics Q1 Meet Up '24 - Community & News Update
 
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptx
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptxThe Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptx
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptx
 
Pros and Cons of Selenium In Automation Testing_ A Comprehensive Assessment.pdf
Pros and Cons of Selenium In Automation Testing_ A Comprehensive Assessment.pdfPros and Cons of Selenium In Automation Testing_ A Comprehensive Assessment.pdf
Pros and Cons of Selenium In Automation Testing_ A Comprehensive Assessment.pdf
 
Best Angular 17 Classroom & Online training - Naresh IT
Best Angular 17 Classroom & Online training - Naresh ITBest Angular 17 Classroom & Online training - Naresh IT
Best Angular 17 Classroom & Online training - Naresh IT
 
Data modeling 101 - Basics - Software Domain
Data modeling 101 - Basics - Software DomainData modeling 101 - Basics - Software Domain
Data modeling 101 - Basics - Software Domain
 
Understanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM ArchitectureUnderstanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM Architecture
 
2024-04-09 - From Complexity to Clarity - AWS Summit AMS.pdf
2024-04-09 - From Complexity to Clarity - AWS Summit AMS.pdf2024-04-09 - From Complexity to Clarity - AWS Summit AMS.pdf
2024-04-09 - From Complexity to Clarity - AWS Summit AMS.pdf
 
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full Recording
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full RecordingOpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full Recording
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full Recording
 
Leveraging AI for Mobile App Testing on Real Devices | Applitools + Kobiton
Leveraging AI for Mobile App Testing on Real Devices | Applitools + KobitonLeveraging AI for Mobile App Testing on Real Devices | Applitools + Kobiton
Leveraging AI for Mobile App Testing on Real Devices | Applitools + Kobiton
 
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdfEnhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
 
Ronisha Informatics Private Limited Catalogue
Ronisha Informatics Private Limited CatalogueRonisha Informatics Private Limited Catalogue
Ronisha Informatics Private Limited Catalogue
 
GraphSummit Madrid - Product Vision and Roadmap - Luis Salvador Neo4j
GraphSummit Madrid - Product Vision and Roadmap - Luis Salvador Neo4jGraphSummit Madrid - Product Vision and Roadmap - Luis Salvador Neo4j
GraphSummit Madrid - Product Vision and Roadmap - Luis Salvador Neo4j
 
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxUI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
 
Strategies for using alternative queries to mitigate zero results
Strategies for using alternative queries to mitigate zero resultsStrategies for using alternative queries to mitigate zero results
Strategies for using alternative queries to mitigate zero results
 
eSoftTools IMAP Backup Software and migration tools
eSoftTools IMAP Backup Software and migration toolseSoftTools IMAP Backup Software and migration tools
eSoftTools IMAP Backup Software and migration tools
 
Keeping your build tool updated in a multi repository world
Keeping your build tool updated in a multi repository worldKeeping your build tool updated in a multi repository world
Keeping your build tool updated in a multi repository world
 
What’s New in VictoriaMetrics: Q1 2024 Updates
What’s New in VictoriaMetrics: Q1 2024 UpdatesWhat’s New in VictoriaMetrics: Q1 2024 Updates
What’s New in VictoriaMetrics: Q1 2024 Updates
 
Effectively Troubleshoot 9 Types of OutOfMemoryError
Effectively Troubleshoot 9 Types of OutOfMemoryErrorEffectively Troubleshoot 9 Types of OutOfMemoryError
Effectively Troubleshoot 9 Types of OutOfMemoryError
 

Create Full Stack Web Apps with Python, React & Webpack

  • 1. CREATING A FULL STACK WEB APP WITH PYTHON, NPM, WEBPACK AND REACT by Angela Branaes
  • 2.
  • 3.
  • 4.
  • 5.
  • 6. THE STRUCTURE OF A WEB APP ➤ Separated into front and back end. ➤ Multiple technologies. ➤ Front end is: ➤ Look and feel. ➤ User interaction. ➤ Back end is: ➤ Long running operations. ➤ Data, and data processing. ➤ Application logic.
  • 7. INITIAL PROJECT SETUP ➤ Create the following directory structure . ├── README.md └── fullstack_template/ ├── server/ └── static/ ├── css/ ├── dist/ ├── images/ └── js/ $ cd fullstack_template/static
  • 8. WE’RE GOING TO NEED A JAVASCRIPT PACKAGE MANAGER ➤ Using a package manager makes it painless to: ➤ Keep your project dependencies up to date. ➤ Fetch and install new packages. ➤ Similar to brew, pip, pacman etc.
  • 9. NPM
  • 10. NPM = NODE PACKAGE MANAGER ➤ Automatically included with Node.js ➤ Easy to use ➤ well documented ➤ nearly 500 000 packages available ➤ Initialise NPM: $ npm init ➤ This creates a file called package.json
  • 11. OUR UPDATED DIRECTORY TREE . ├── README.md └── fullstack_template/ ├── server/ └── static/ ├── css/ ├── dist/ ├── images/ ├── js/ └── package.json
  • 12. THE PURPOSE OF PACKAGE.JSON 1. Keeps track of dependencies and versions. 2. Informs other developers about your project. 3. Makes installing, running and updating a project automatic and reproducible
  • 13. THIS IS MY PACKAGE.JSON { "name": "FullStackTemplate", "version": "1.0.0", "description": "Fullstack Template", "main": "index.jsx", "scripts": { "test": "echo "Error: no test specified" && exit 1", }, "keywords": [ "python", "react", "npm", "webpack" ], "author": "Angela Branaes", "license": "MIT", "devDependencies": { "webpack": "^3.0.0" } }
  • 14. WHY WE NEED A MODULE BUNDLER ➤ Minimises the number of <script> tags in your HTML ➤ This means faster loading, and less hassle. ➤ Don’t need to worry about bundle import ordering! ➤ Don’t have to use globals or namespacing. ➤ Lazy module loading. ➤ We will be using Webpack.
  • 16. WEBPACK ➤ Only understands JavaScript. ➤ Everything else needs a loader or plugin. ➤ Everything is a module. ➤ You can require() JavaScript, React, CSS or images. ➤ Creates a dependency tree of all your required modules, and packages those into bundles. ➤ Easy to get started with, if you only need JavaScript. ➤ Minor learning curve for css/less and image loading. ➤ Lets you split your bundles and load them asynchronously and lazily. ➤ Integrates seamlessly with npm.
  • 17. INSTALL & CONFIGURE WEBPACK ➤ Install webpack: $ npm i webpack --save-dev ➤ Add a file named webpack.config.js: const webpack = require(‘webpack'); const config = { entry: __dirname + '/js/index.jsx', output: { path: __dirname + '/dist', filename: 'bundle.js', }, resolve: { extensions: ['.js', '.jsx', '.css'] }, }; module.exports = config;
  • 18. OUR UPDATED DIRECTORY TREE . ├── README.md └── fullstack_template/ ├── server/ └── static/ ├── css/ ├── dist/ ├── images/ ├── js/ ├── package.json └── webpack.config.js
  • 19. SINGLE VS MULTI PAGE APPLICATIONS ➤ I mostly use Webpack for single page applications. ➤ You can also use webpack for multi page applications: entry: {
 “indexPage”: __dirname + “js/index.jsx”,
 “aboutPage”: __dirname + “js/about.jsx” }, output: { path: __dirname + “/dist”,
 filename: “[name].js” //e.g. aboutPage.js }
  • 21. OUR UPDATED DIRECTORY TREE . ├── README.md └── fullstack_template/ ├── server/ └── static/ ├── css/ ├── dist/ │ └── bundle.js ├── images/ ├── js/ │ └── index.jsx ├── index.html ├── package.json └── webpack.config.js
  • 22. CREATE INDEX.HTML ➤ A really simple index.html is all you need. ➤ The index.html just loads your JavaScript bundle <body> <div id="content" /> <script src="dist/bundle.js" type=“text/javascript”> </script> </body> ➤ All the layout and behaviour live in the JS/React files!
  • 23. CREATE INDEX.JSX ➤ Just 1 line of Plain Old JavaScript alert(“Hello World!”);
  • 24. BUILDING YOUR APPLICATION ➤ Create run commands to simplify building your code. ➤ Run commands are just aliases. ➤ Example from my package.json: “scripts": { "watch": "webpack --progress -d --config webpack.config.js —watch" } ➤ Makes the dev process more fluid. ➤ I always add the following: ➤ build ➤ dev-build ➤ watch
  • 25. START THE WATCH COMMAND ➤ Any changes get built automatically $ npm run watch ➤ Open index.html….
  • 26.
  • 27. CREATING A SIMPLE REACT APP
  • 28. THE BENEFITS OF USING REACT ➤ Easy to build UIs composed of small, distinct components. ➤ Encourages design of reusable UI components. ➤ Easier to understand what’s going on when markup lives with the code (JSX). ➤ Automatic re-rendering of components on change. ➤ Easy to maintain.
  • 29. INSTALL REACT $ npm i react react-dom —save-dev
  • 30. REACTIFY INDEX.JSX import React from "react"; import ReactDOM from "react-dom"; import App from “./App"; ReactDOM.render(<App />, document.getElementById("content"));
  • 31. ADD A REACT “APP” CLASS ➤ Remember to export your react classes! // App.jsx import React from “react”; export default class App extends React.Component { render () { return <p> Hello React!</p>; } }
  • 32. OUR UPDATED DIRECTORY TREE . ├── README.md └── fullstack_template/ ├── server/ └── static/ ├── css/ ├── dist/ ├── images/ ├── js/ │ ├── index.jsx │ └── App.jsx ├── index.html ├── package.json └── webpack.config.js
  • 33. WHAT IS JSX? ➤ Syntax extension to JavaScript. ➤ Optimised on compilation, so faster than JavaScript. ➤ Statically typed and mostly type-safe. JavaScript is not. ➤ Lets you write HTML tags in your JavaScript functions: <Hello name=“Rimini” /> instead of React.createElement(Hello, {name: “Rimini}, null) ➤ Recognises upper-case element-types as written in React. E.g. <Hello /> ➤ How do we make our browser understand JSX?
  • 34. INTRODUCING BABEL Write next-generation javascript right now! Transform JSX to JS.
  • 35. ADD BABEL ➤ Install Babel ➤ Add the Babel presets to the package.json: “babel”: { “presets”: [ “es2015”, “react” ] },
  • 36. ADD A BABEL-LOADER RULE TO THE WEBPACK CONFIG: module: { rules: [ { test: /.jsx?/, exclude: /node_modules/, use: 'babel-loader' } ] }
  • 37. OPEN INDEX.HTML IN YOUR BROWSER ➤ This should now show the “Hello React” paragraph we added in our new React App.jsx file.
  • 38.
  • 40. PYTHON ➤ Go to the server folder ➤ Ensure you’re in a Python virtualenv $ mkvirtualenv fullstack ➤ Install Flask (fullstack)$ pip install flask ➤ Create a file called server.py in the server folder
  • 41. OUR UPDATED DIRECTORY TREE . ├── README.md └── fullstack_template/ ├── server/ │ └── server.py └── static/ ├── css/ ├── dist/ ├── images/ ├── js/ │ ├── index.jsx │ └── App.jsx ├── index.html ├── package.json └── webpack.config.js
  • 42. SERVER.PY from flask import Flask, render_template app = Flask(__name__, static_folder=“../static/dist", template_folder="../static") @app.route("/") def index(): return render_template("index.html") @app.route("/hello") def hello(): return "Hello World!” if __name__ == "__main__": app.run()
  • 43. START THE SERVER ➤ Go to: http://localhost:5000/ $ python server.py
  • 44. REQUEST INFO FROM THE SERVER var $ = require(‘jquery'); getPythonHello() { $.get(window.location.href + 'hello', (data) => { console.log(data); this.personaliseGreeting(data); }); }
  • 45. MAKE PYTHON DO SOMETHING MORE INTERESTING ➤ We call get_hello() whenever we hit the /hello endpoint def get_hello(): greeting_list = ['Ciao', 'Hei', 'Salut', 'Hola', 'Hallo', 'Hej'] return random.choice(greeting_list)
  • 46. SAY HI TO SOMEONE SPECIAL ➤ There should be a class for that! ➤ Change the App.jsx render method to the following: render () { return ( <PageHeader> <div className='header-contents'> <Hello name='Rimini' /> </div> </PageHeader> ); )
  • 47. OUR UPDATED DIRECTORY TREE . ├── README.md └── fullstack_template/ ├── server/ │ └── server.py └── static/ ├── css/ ├── dist/ ├── images/ ├── js/ │ ├── index.jsx │ ├── App.jsx │ └── Hello.jsx ├── index.html ├── package.json └── webpack.config.js
  • 48. CREATE THE HELLO CLASS export default class Hello extends React.Component { constructor(props) { super(props); // greeting is now “Hello Rimini” this.state = {greeting: 'Hello ' + this.props.name}; // This binding is necessary to make `this` // work in the button callback this.getPythonHello = this.getPythonHello.bind(this); } }
  • 49. ➤ Add this function to the Hello class: ➤ This will re-render the greeting on our website to a new one when called. personaliseGreeting(greeting) { this.setState({greeting: greeting + ' ' + this.props.name + '!'}); }
  • 50. LET’S FINALLY RENDER OUR HELLO! render () { return ( <h1>{this.state.greeting}</h1> <hr/> <Button onClick={this.getPythonHello}> Say Hello! </Button> ); }
  • 51.
  • 52.
  • 53. CREATE A NICE LAYOUT WITH CSS ➤ Webpack ONLY understands JavaScript. ➤ Install the following loaders and plugins: ➤ style-loader ➤ css-loader ➤ extract-text-webpack-plugin ➤ Add a plugin to the webpack config: plugins: [ new ExtractTextPlugin('styles.css'), ]
  • 54. OUR UPDATED DIRECTORY TREE . ├── README.md └── fullstack_template/ ├── server/ │ └── server.py └── static/ ├── css/ │ └── fullstack.css ├── dist/ │ ├── bundle.js │ └── styles.css ├── images/ ├── js/ │ ├── index.jsx │ ├── App.jsx │ └── Hello.jsx ├── index.html ├── package.json └── webpack.config.js
  • 55. ➤ Add fullstack.css to the css folder ➤ Add a few css rules for our header ➤ require fullstack.css in App.jsx: require(‘../css/fullstack.css'); ➤ Add the bundled css to the index.html: <link rel="stylesheet" href="dist/styles.css">
  • 56.
  • 57. OUR UPDATED DIRECTORY TREE . ├── README.md └── fullstack_template/ ├── server/ │ └── server.py └── static/ ├── css/ │ └── fullstack.css ├── dist/ │ ├── bundle.js │ └── styles.css ├── images/ │ └── header.png ├── js/ │ ├── index.jsx │ ├── App.jsx │ └── Hello.jsx ├── index.html ├── package.json └── webpack.config.js
  • 58. ADD A NICE BACKGROUND IMAGE 1. Add the file-loader loader 2. Add an image to your images/ folder 3. Set the image to be your header background in the fullstack.css file background-image: url(‘../images/header.jpg’); 4. NOTE: you have to load the image in your React app for it to show up!
  • 59. IN APP.JSX import HeaderBackgroundImage from ‘../images/header.jpg’; ➤ Add this fn to your class: addHeaderImg() { let headerBg = new Image(); headerBg.src = HeaderBackgroundImage; } ➤ And this to your render(): {this.addHeaderImg()}
  • 60.
  • 61.
  • 62.
  • 63.
  • 64. THANK YOU! ANY QUESTIONS? @angineering @angineering - The code is on GitHub: https://github.com/angineering/FullStackTemplate @angineering - This talk is also a blogpost