Building a full-stack web application with Python, NPM, Webpack and React
This is a modal window.
The media could not be loaded, either because the server or network failed or because the format is not supported.
Formal Metadata
Title |
| |
Title of Series | ||
Number of Parts | 160 | |
Author | ||
License | CC Attribution - NonCommercial - ShareAlike 3.0 Unported: You are free to use, adapt and copy, distribute and transmit the work or content in adapted or unchanged form for any legal and non-commercial purpose as long as the work is attributed to the author in the manner specified by the author or licensor and the work or content is shared also in adapted form only under the conditions of this | |
Identifiers | 10.5446/33678 (DOI) | |
Publisher | ||
Release Date | ||
Language |
Content Metadata
Subject Area | ||
Genre | ||
Abstract |
|
EuroPython 2017144 / 160
10
14
17
19
21
32
37
39
40
41
43
46
54
57
70
73
85
89
92
95
98
99
102
103
108
113
114
115
119
121
122
130
135
136
141
142
143
146
149
153
157
158
00:00
Metropolitan area networkSoftware developerProduct (business)Cartesian coordinate systemWeb applicationWeb 2.0Gastropod shellPublic key certificateQuantumLecture/Conference
00:57
Stack (abstract data type)Mobile appWorld Wide Web ConsortiumDimensional analysisData structureOperations researchProcess (computing)Hausdorff spaceDirectory serviceComputer-generated imagerySimilarity (geometry)Software developerTrailRevision controlTemplate (C++)Scripting languageWeb browserLevel (video gaming)Data managementServer (computing)Cartesian coordinate systemWebsiteDivisorReading (process)DebuggerFormal languageComputer fileScripting languageRepresentation (politics)Expert systemBitDefault (computer science)TheoremHome pageProjective planeRevision controlWordDependent and independent variablesRight angleSkeleton (computer programming)AdditionVideo gameFluid staticsProcess (computing)Single-precision floating-point formatWeb pageWeb applicationWeb 2.0Query languageSoftware developerData conversionDifferent (Kate Ryan album)Directory serviceComputer configurationData structureNormal (geometry)Library (computing)Subject indexingFront and back endsProgram flowchart
06:45
Revision controlStack (abstract data type)Template (C++)Price indexScripting languageSoftware testingError messageFiber bundleModule (mathematics)Similarity (geometry)Scripting languageOrder (biology)Structural loadMultiplication signFiber bundleNumberWeb pageSubject indexingNetwork topologyBitComputer filePoint (geometry)CodeModule (mathematics)Profil (magazine)Endliche ModelltheorieRight angleWeb 2.0Computer animationXML
08:05
Cloud computingCross-site scriptingBootingFiber bundleComputer-generated imageryJava appletScripting languageNetwork topologyModul <Datentyp>Module (mathematics)Module (mathematics)Asynchronous Transfer ModeTerm (mathematics)Web 2.0Scripting languageComputer fileBitBootingCurveProcess (computing)Plug-in (computing)Automatic differentiationProgram flowchartComputer animationXML
09:24
Price indexFunction (mathematics)Extension (kinesiology)Fiber bundleInstallation artModule (mathematics)Server (computing)Fluid staticsComputer-generated imageryNetwork topologyDirectory serviceWeb pageMultiplicationSingle-precision floating-point formatReading (process)Function (mathematics)Point (geometry)Task (computing)WebsiteDifferent (Kate Ryan album)Cartesian coordinate systemWeb pageMultiplicationHome pageFiber bundleComputer fileSubject indexingSingle-precision floating-point formatDirectory serviceCASE <Informatik>Network topologyPoisson-KlammerScripting languageOperator (mathematics)Product (business)Office suiteComputer animation
10:52
HypertextScripting languageFiber bundleStructural loadJava appletPrice indexCodeBuildingProcess (computing)Open setAdditionComponent-based software engineeringMarkup languageVolumenvisualisierungSocial classMobile appDefault (computer science)Euclidean vectorReading (process)Server (computing)Fluid staticsDirectory serviceNetwork topologyExtension (kinesiology)Compilation albumFunction (mathematics)Element (mathematics)Type theoryWeb browserWritingMathematicsSoftware developerConnectivity (graph theory)Line (geometry)Computer fileWindowComputer scienceCodeElement (mathematics)Web browserAliasingSubject indexingWordParameter (computer programming)Process (computing)Cartesian coordinate systemPoint (geometry)MereologyLogicSocial classMobile appPoisson-KlammerUser interfaceGoodness of fitDefault (computer science)Dot productExtension (kinesiology)Directory serviceTheoryFiber bundleSchmelze <Betrieb>1 (number)NavigationCASE <Informatik>Profil (magazine)VolumenvisualisierungGroup codeArithmetic meanClient (computing)Bit rateInterface (computing)Java appletScripting languageMIDIComputer animation
15:35
WritingWeb browserGroup actionSet (mathematics)Standard deviationJSONXMLUML
16:00
Installation artBootingRule of inferenceModule (mathematics)Server (computing)Stack (abstract data type)Template (C++)Computer virusPrice indexVideo game consoleInfinityRandom numberContent (media)VolumenvisualisierungMathematicsFluid staticsComputer-generated imageryDirectory serviceNetwork topologyDefault (computer science)Euclidean vectorSocial classFunction (mathematics)WebsitePlug-in (computing)Java appletScripting languageCross-site scriptingFiber bundleEmailCodeFreezingTable (information)Set (mathematics)Type theoryDifferent (Kate Ryan album)Functional (mathematics)WordElectronic mailing listCartesian coordinate systemSystem callUniform resource locatorBitSeries (mathematics)VolumenvisualisierungPoint (geometry)Front and back endsTelecommunicationLibrary (computing)Server (computing)Module (mathematics)QuicksortDirectory serviceConstructor (object-oriented programming)Fiber bundleWeb pageExpert systemRule of inferenceInformationParameter (computer programming)MathematicsAreaSocial classScripting languageCASE <Informatik>BootingGoogolRevision controlSpacetimeMedical imagingMultiplication signCodeObject (grammar)Computer fileDefault (computer science)Formal language1 (number)Vector spaceGame theoryBit rateRoutingGreatest elementService (economics)PlanningClient (computing)Presentation of a groupNoise (electronics)WebsiteTerm (mathematics)Office suiteLogicComplex (psychology)NeuroinformatikBootstrap aggregatingVideo gameSound effectNichtlineares GleichungssystemData structureFluid staticsVirtual realityNormal (geometry)ResultantFunction (mathematics)Forcing (mathematics)Projective planeCellular automatonInterior (topology)BlogProduct (business)State of matterEmailWeb 2.0Process (computing)Archaeological field surveySubsetNetwork topologySoftware frameworkDataflowRepository (publishing)Perspective (visual)Structural loadStack (abstract data type)MultiplicationTwitterSlide ruleSource codeVideo game consoleSubject indexingConfiguration spaceWeb browserMobile appComputer virusCross-site scriptingPlug-in (computing)Line (geometry)Generic programmingFlow separationDebuggerComputer iconComputer animation
Transcript: English(auto-generated)
00:04
Good morning, I hope you're all having a great conference so far My name is Angela and I work for man HL which is a systematic hedge fund based in London Where I'm a quant developer I'm really excited to be here today to tell you about how you can make a full stack application
00:21
with Python and PM webpack and react now being able to Transform an idea into an actual product is an incredibly valuable skill both for your career and for you as a person it can kind of take you from thinking of something and
00:42
making a minimal viable product that you can either use to start a startup make a new application at work and Get that promotion that you're looking for because you can show that you can actually create things and make something happen So today I am going to be showing you how to make a simple web application like this
01:05
this is a single page web application When you click the button it changes Which what it says we're giving you hello in a different European language. It has a background
01:21
It has some style, but it's not really doing anything very complicated So What does a web app look like this is an example of this web application Which I would say is in general quite a good representation of what a web application would look like
01:41
it has a front end and it has a back end the front end is what you see here in blue and green and it consists of What the user sees and how the user interacts with the web application I'm going to explain this with the assumption that you have a basic understanding of what HTML CSS JavaScript and Python is
02:06
And if you are a perfect expert in all of these things then this talk might be a little bit basic for you But bear with me. So the index of HTML page is what essentially creates a structure for your website
02:21
Historically, this would be an entire skeleton of what your website looks like But because we are using react react actually componentizes all the pieces of your website so all of these things actually live in react now instead of in HTML and We will essentially just be loading in our compressed JavaScript react files into our
02:44
HTML file and that's literally what that file was going to be We then have these two light blue files at the top It is our style file and our JavaScript file. These have both been bundled By our extra tools. So if you look in these dark blue files
03:03
They are our react files. We take our react files which have been written in JSX they are passed into the Babel converter Babel conversion to normal JavaScript Webpack then converts this to something that
03:21
our browser can understand Because webpack only understands normal JavaScript and then we attach those things to our browser When we talking to the back end when we are Clicking that little button. What happens is that we are using a JavaScript library called jQuery to do our HTTP
03:41
Request to ask the server. Hey, can I get a new type of hello, please and the server will return that to us And we will display it on our website So for this example, we are going to be using flask Which I'll get back to more later. So first things first This is going to be our initial project setup. You have a folder in your folder
04:04
you will have a readme to tell other people about your project and what you're doing and you'll have a Project folder respectively. This project folder has a server folder and a static folder The static folder is a front end. It holds your JavaScript your webpack your Babel your NPM
04:25
And we're going to start by going in there and building our front end so the first thing we are going to need is a JavaScript package manager and Package manager, I'm sure you're all familiar with from using things like PIP or apt-get
04:43
And it really just manages your packages It makes life so much easier because you don't have to worry about Going through this website to download the new version of that package making sure you have all the right dependencies What are even my dependencies? By using a package manager
05:00
You just say oh I want this file in this file in this file and it downloads the version you want or the latest version And you can easily see what's going on So we are going to be using NPM NPM is automatically included with node.js if you still install that but it is really a separate application
05:21
And you can use it with other languages and just node.js, but it is a JavaScript package manager It's very easy to use it has a lot of packages it has about half a million packages It's well documented and it is actively being developed So it is essentially a safe option that isn't just going to be deprecated in two months
05:41
At least I hope not So the first thing we're just going to do is initializing NPM for our project This has really good defaults and you basically just follow the defaults and this creates a package.json file The package.json file ends up in our static directory like you can see here in pink
06:02
So for reference everything that's pink is the things that have changed The package.json is really useful for multiple reasons It is just a file you can look at it and it tells you who is responsible for the project What version is the project? How do I contact the developers? What keywords are relevant to this project?
06:26
And it also means that any other developers can very easily install and run your project and it should be completely reproducible So this is what my package.json looks like As you can see, there's a name. There is a version
06:43
There's dependencies and a license. So everything I really need to know about how this front-end works The next thing we're going to need is a module bundler This minimizes the number of script tags in your JavaScript So if you've done a bit of JavaScript before you know that once you start kind of having quite a few JavaScript files
07:02
You need to add them all to your HTML index or similar and you need to add them in the right order because if you add them in the wrong order then Everything is a global and depending on you know, how you do this It gets quite messy and it takes a long time to load so By using webpack this bundles our dependencies
07:23
Essentially give it an entry point and based on this entry point. It creates a dependency tree of all your dependencies And then you attach this bundled JavaScript file To your HTML that is one script tag for one entry point
07:41
And this basically means that you no longer have to worry about globals You no longer have to worry about which order do I import things in you no longer have to worry about Having loads of script tags and having a really unreadable code. It's easy to see what's attached and how do I run it? it also does lazy module loading which means that
08:01
It's actually essentially your pages are going to be loading faster Right, so this is what webpack looks like with its Mode basically, it's bundling so we could create takes all your normal modules and turns them into static modules One important thing to note about note about webpack is it only understands JavaScript this means that anything else
08:27
Needs to be converted into JavaScript to be used. This is both a benefit and a bit of a problem This means that we need to add a loader or a plug-in for everything else you want to add This means you want to add CSS. There's a loader for that. Do you want to add files?
08:43
There's a loader for that you want a background image. There's a loader for that. Obviously, there's a little bit of a Learning curve here, but once you kind of start getting the hang of it, it's actually quite okay But the benefit of everything being a module is that you can attach it and require it inside your JavaScript
09:02
So I can require my CSS file in my JavaScript and I can require my background image in my JavaScript Which is actually what quite really quite powerful And it also integrates seamlessly with NPM, so this is how we get started with webpack You install it using NPM
09:22
And then you add a file called webpack.js It really just has to be in the police Everything you need to get started is an entry point and the output The entry point is just going to be our JavaScript directory and the index file in there And then our output is just going to be a bundle.js
09:44
And then we export this and it ends up here in our static folder And we can really get ready to use that. Now if you want to have a If you have an application that is a multi-page application Instead of the single page application we are using
10:02
This is how you would do it. So you can have multiple different entry points for your different sites You can have an index page and about site and they would all have a different entry point Creating a different bundle So in this case you can look at what happens in the output where we have the bracket named.js
10:21
And this would just be named after your entry point name Okay, so let's actually do something interesting with this. We're going to start by displaying an alert This is going to be our updated directory tree. We're just adding an index of HTML file and a JavaScript file And then you can also see where our bundle ends up
10:41
So okay the index This is super easy as I mentioned previously you literally just add your Bundle to the body of your file and that's it. Everything you need to do All the layout and behavior is in react In our index.jsx file all we're going to do is add an alert. This is literally the only file
11:07
Only sentence effectively that is in our file And that's enough to create an alert We don't need to build our application as well I always add some run commands when I build my application
11:24
A run command is just an alias. For example, if you add a watch command As you can see I can just then use watch as the word instead of that remembering that entire line and all the parameters And it just makes your development process a lot more fluid
11:41
It means that you don't have to remember the giant lines and you can kind of just do a build and it just builds It's similar to using a makefile So When you start the watch command watch is special in the sense that you start in a different tab and you just keep it running and It automatically builds any change files and we create a new bundle for you. So you don't need to worry about actually
12:07
Making sure that you've compiled your code manually because watch is going to do that for you That means you can refresh your browser window and see your changes immediately instead of sitting there going Okay, I made some changes, but they're not displaying and five minutes later you realize it's because you forgot to build
12:23
We open the index of HTML page. Tada. We have an alert great. Okay, let's do something more interesting We're going to add React to this Now why am I using react? I really like react because it allows you to build small componentized
12:42
UIs with reusable components It Makes it really easy to basically do repetitive things without having to write The same code over and over and over again, which is very good computer science Methodology in general it's easy to maintain and
13:02
It's easy to re-render components and change and all the logic for a component lives within that component, which makes it very easy to Basically see what's going on see what lives where and switch out one component for another one without problem so we're going to install react and
13:21
then we are going to add a React file which is basically replacing that alert we had previously with this text So for react you always need to import react to be able to use react obviously There's a few things to note here the react dom means that we are essentially displaying things in
13:43
With react As you can see when I'm importing my app, there's a dot slash in front of it this means I'm importing it from a local file that I created instead of an external dependency and You might think that being able to use brackets is kind of weird inside my JavaScript code
14:04
But this is essentially what JSX does it allows you to use custom effectively HTML tags with your own created classes So the app here is effectively our entry point into this part of our react code around our application
14:21
We are then going to add the app class, which is something that actually does something In this case, we are going to just have it display. Hello react And we need to export default on this class so You always need to be able to you always need to export your classes to be able to import them somewhere else And it's good practice to only have one class per file and which which means that we can basically just export default
14:47
This is where our new file ends up in the JavaScript directory next to the index file Now what is JSX? It's effectively a Syntax extension to JavaScript. It means that you can use
15:03
XML and HTML tags in your JavaScript code and you can use your custom classes directly in your JavaScript code So it lets you write those HTML tags you see there instead of react dot create element blah blah blah Which makes your code a lot more readable?
15:22
But how do we make our browser understand JSX? Okay. So for this we need to use Babel Babel is fantastic it converts your You know top state-of-the-art Really modern JavaScript into JavaScript that any browser can understand so it allows you to use JavaScript
15:44
And allows you to use JavaScript That is modern without having to wait three years for your browser to start eventually being compatible with it It also allows you to use JSX because it converts JSX into standard old JavaScript So
16:01
To be able to use Babel we need to add presets and Babel has presets basically means what types of JavaScript Do you want me to understand and convert between so? We're gonna add ES 2015 and we're going to add react which basically means these are the currently the two types we can use
16:20
We then need to go to our webpack config and also add a rule for how we're going to treat JSX files Note for this that we are excluding node modules node modules is The directory where all your external dependencies end up This basically means that when we're not compiling this we are going to save a lot of time every time we're rebuilding our bundle
16:43
Because we're not interested in retranslating this every time We're going to open the index of HTML page in a browser and they should say hello react which it does We then need to add a Python flask server
17:00
You need to go to the server folder and ensure you are in a Python virtual environment You don't need to basically install flask because we are going to be using flask So I'm produce flask for a project like this because it's a microsurvey or a micro framework
17:20
It's really easy to use and get started with if I was doing a big industry project I would probably be using something like pyramid or Django instead, but it really depends on what you need to use it for And we're just adding a file called server.py to our server folder in here setting up flask is very easy
17:47
So you just need to point at where your static bundle is and where you inducted HTML is And then you need to
18:05
So we have two two routes to our server We have the default route that you get to when you just go to the server And then you have the route to get to you when you go to slash hello we are going to be using the Default route to just load our website and then we're going to be using the slash hello endpoint
18:24
To get all those different hellos that you saw in the beginning For now, it's just going to return a static hello world We can start our server and go to localhost 5000 and you will see that hello react we saw previously Because then it's basically connected your react and your Python backend
18:46
now This is great. But how do we actually make react communicate with that back end? We need to use jQuery or Whatever other library of your preference, but I quite like using jQuery so
19:01
with jQuery we basically just Call the URL in question, which is our localhost URL with slash hello And then we get some data back and with that data We are going to display it in our console to check that it works And we are also going to be passing it to a different function to handle that data
19:22
So this function you see here we are going to be adding to our react code We are then going to be changing the Python in the back end to do something a little bit more interesting So instead of just returning that static hello world
19:43
We are going to be returning a series of different European hellos Notice that there is no English hello because then we would have to update our code in about a year to remove it anyway So, yeah, and we just return a random word from that list
20:04
And I think it's nice to be able to say hello to someone special instead of saying just a generic hello So we are actually going to be making a few changes to our react code here We are going to be using a class instead of just putting all our code in in our app file
20:23
Because that means that we could technically have 10 things Saying hello to someone on our front page instead of just one but for the sake of this we'll just do one So you might recognize this as the render function from previously in our app.jsx file
20:42
I've made it a bit more interesting by adding a page header, which is where all our information is going to go and Also, we have this class now called. Hello Which is passing in a name called Remini What we want to do is we want to create a class called hello.jsx And we want to pass in a parameter to it. That is the name. We want to say hello to
21:03
Okay, so how do we do that? to do that you need to add a hello.jsx file naturally and Then you need to create the hello class As previously you need to export default on the class to make sure it's accessible outside
21:21
And you need to have a constructor the constructor passes in this thing called props The props here is essentially everything you passed in on creation of the class Props are immutable and you're not allowed to change them We then therefore need to also have a state
21:41
States are internal. You can change them and when changing state that's generally when data is actually updated on your website So when we click that button and you see a different type of hello That is because we've changed the state and on updating of the state your UI gets re-rendered
22:00
But we never touch the props So as you can see here, we are initiating the state with a greeting key And it just says hello and the name we pass in which is Remini. So hello Remini Also note that we have to rebind this This is because this is not bound by default
22:23
So when we are trying to call a function when we click a button if we don't rebind this on that function We're just going to get undefined if we're trying to use this within the function and this is just a JavaScript thing It's not really a react thing as such But it's important to keep in mind
22:42
So we are going to be adding this function to our hello class and this is the function that handles the data we passed in So we get a new type of hello from our server We pass it to this function as data and then we re-render the state When you re-render the state you always have to use this.setState with your key
23:03
Because if you try to do what we just did in the constructor, it's not actually going to re-render the UI So that's why you always have to use this.setState So, okay, let's render that hello We want it to be output as a big hello, a little bit of a line and then a button that you can click
23:25
to change your hello. To do this, I've added an h1 with our actual greeting an HR in the middle and then a button that goes say hello whenever you click hello And I've used the bootstrap buttons for this because they come by default with quite a nice UI without you having to do anything
23:46
And they have every active version that you can just import that already has this functionality. So what do we get now? We get the UI that says hello Remini and a button. Great. Okay, so How do we go from this to something a little bit more interesting?
24:05
I want to add some CSS And as previously JavaScript only or webpack only understands JavaScript, so I need to add a loader And I'm going to install the style loader, the CSS loader and an extract plugin
24:24
we need these two loaders to convert our CSS files and then we need the extract plugin to be able to extract our Bundled CSS from our generic JavaScript bundle into something we can actually attach directly
24:41
To our index of HTML file so you can render our JavaScript and our CSS Separately if you don't extract it and attach it separately You're basically going to have your UI probably be rendered after all your JavaScript has gotten been rendered Which is going to have very weird side effects
25:01
So we need to add a plugin which is the extract plugin and The name in pink you can see there is what we've decided to name our bundled CSS file And that is what it's going to look like in our directory tree. Note that there is a difference between my CSS file full stack dot CSS and
25:22
My bundled file style at CSS and this is because our browser only has access to the bundle files If you try to load up the normal CSS file, you're not really going to get the result you expect It's just not going to apply your styles. So you need to attach the bundle one and
25:42
Basically load that up So how we do that is Adding a full stack dot CSS to our folder I'm added a few styles to it. Just something to make you look a bit nicer And then I need to require my full stacks of CSS file in my react code
26:01
If you don't load it into your react code It's not going to be picked up when webpack is bundling and it's going to think you have no styles applied And as a result, it's not actually going to get compiled And then we need to add the style sheet, which is the bundle style sheet To our index of HTML page and what we end up with then is this
26:26
And now you can see our style has been applied It looks different and it's quite nice, but I would still like to basically add a background image adding a background image Is just adding an image to our image folder
26:44
We need to then use a file loader to load that image When you use a file loader, you can specify what types of files you want it to load So in our case, we are going to specify that we will load JPEGs PNGs, etc. And that is just another rule in your webpack config
27:04
and then you need to Basically add a background URL to your CSS as you've done here But the caveat here is just adding this to your CSS is not going to actually make your image show up You need to also load your image in your react code to be able to have that image show up
27:24
And this is something that a lot of people seem to be quite confused about Just judging by googling it Because basically you need to import your image You then need to create a new image object and add your image as the source
27:44
For that new image object and then you need to render your image In your render function in that file and only if you do all of those steps Are your image is actually going to show up? Otherwise you you're not going to see anything. You're going to see that white page we saw previously
28:05
So what we have now is an app that has a background image it Has some nice CSS. We have managed to position it where we wanted to on the page And when you click the button it says hello in different European languages
28:23
So, thank you for listening and any questions You can find me on engineering the Twitter This is also the same handle I use on GitHub and medium and there's a blog post about how you can do this step-by-step and all the code is also on
28:42
GitHub so you can either follow the blog post and do this step-by-step or you can go to github and just get all the code immediately The slides are also been uploaded on the Europe icon website, of course. Thank you
29:04
Any questions? Yes Hi, thank you for a talk Is there a reason you don't use a yarn in place of NPM?
29:25
No particular reason it's I Really like using NPM. I've been using it for a while. It is really good support. It works really well I've never had an issue with using it. No compatibility issues And it basically does what I need so I've seen no reason to switch at present
29:52
Any other questions? Have you got any suggestion about a trade-off between the server-side code and the client-side code?
30:06
because sometimes of course the Rendering the page client-side gives you benefits in terms of speed, but of course Many times your device is not
30:22
It's not powerful enough to to render your your page, so maybe you have some trade-offs that for some suggestion that you want to share and Or maybe I don't know you have some tips and tricks about that. Yes, so
30:41
Technically you can react render react server-side as well But I would say in general It's quite good practice to just try to minimize the sizes of your web pages use lazy loading Try to split up what you're doing on different pages To not try to load
31:00
You know a multi megabyte image immediately with all your functions and trying to do 10 different calls so kind of try to optimize your page in that way and also you obviously want to put all your Application logic in your back end to any long-running applications any complex computations Anything like that. I would always put in my back end and just leave the front end as
31:25
Rendering the nice things anything I can kind of do a synchronously in the back end. It's perfect basically So, yeah any other questions, okay. Thank you for listening