Fullstack Developer Guide
Fullstack Developer Guide
5/3/2023
Prepared By
W3 Engineers Ltd
Contents
....................................................................................................................................................... 0
Introduction................................................................................................................................... 4
About Internship Program..........................................................................................................4
Training and Development of Intern:.........................................................................................4
Details of Internship Program.................................................................................................4
About Office etiquette, Organization, and office norms............................................................4
Others Office Policy (HR Policy)..................................................................................................4
Conventions and best practices.....................................................................................................5
Mistakes..................................................................................................................................... 5
Productivity................................................................................................................................ 5
Coding........................................................................................................................................ 6
New Project................................................................................................................................8
CONFIDENTIAL
Deployment............................................................................................................................... 9
Process Hierarchy.......................................................................................................................9
Web Architecture.......................................................................................................................... 9
The diagram............................................................................................................................. 10
How WWW [Web Addresses] Translates.................................................................................11
Monoliths................................................................................................................................. 11
Overview.............................................................................................................................. 11
Benefits.................................................................................................................................12
Drawbacks............................................................................................................................ 12
Microservices........................................................................................................................... 13
Overview.............................................................................................................................. 13
Benefits.................................................................................................................................13
Drawbacks............................................................................................................................ 14
Conclusion............................................................................................................................ 15
Micro frontends....................................................................................................................... 15
Quick Summary.................................................................................................................... 15
What is Micro-frontend Architecture?.................................................................................16
Benefits.................................................................................................................................16
Drawbacks............................................................................................................................ 16
How it works?.......................................................................................................................17
Programming languages.............................................................................................................. 17
Frontends................................................................................................................................. 17
HTML & CSS for responsive web...........................................................................................17
HTML5 Basic overview............................................................................................................. 17
CSS3 Basic overview..............................................................................................................19
JavaScript core......................................................................................................................42
NodeJs.................................................................................................................................. 50
Reactive framework..............................................................................................................52
Backends.................................................................................................................................. 61
RDBMS & No SQL..................................................................................................................61
CONFIDENTIAL
Python.................................................................................................................................. 62
Golang.................................................................................................................................. 86
Cloud Infrastructure...................................................................................................................101
Deployment tools and techniques.........................................................................................101
Cloud Infrastructure...............................................................................................................101
Amazon Web Service (AWS)...................................................................................................102
EC2......................................................................................................................................102
VPC..................................................................................................................................... 102
S3........................................................................................................................................ 102
CloudFront..........................................................................................................................103
RDS..................................................................................................................................... 103
NoSQL................................................................................................................................. 104
Route53.............................................................................................................................. 104
SQS..................................................................................................................................... 105
Elastic Beanstalk................................................................................................................. 105
Elasticsearch....................................................................................................................... 105
Lambda............................................................................................................................... 106
CloudFormation..................................................................................................................106
Linux (OS)............................................................................................................................... 106
Docker.................................................................................................................................... 107
Docker Compose................................................................................................................ 108
GIT.......................................................................................................................................... 109
IDE.......................................................................................................................................... 110
Automation Tools...................................................................................................................111
CONFIDENTIAL
Introduction
Course Brief Time: 3 hours
Mistakes
Spell mistakes
Naming things incorrectly
Incorrect file names. E.g., OS dependent
Over abstraction. E.g. Over thinking of product
Messy inheritance. E.g. Vehicle / boat, airplane
ü Syntax error. E.g. Not testing or overlook
ü Permissions error. E.g. test, development or production mess up
ü Memory Hungry Loop. E.g. large datasets?
Incorrect operators. E.g. >/>=?, &/and?, brackets
Self-doubt
CONFIDENTIAL
Productivity
Hot keys, even in browsers
Multiple screen/Large Screen
Proper development environment
Real time notes and to-do app. E.g. Wunderlist, Evernote/OneNote
Refactor code. E.g. Think to make it more efficient
Read/Follow open-source codes
Automate as much as possible
Read books
Re-useable codes, don’t re-invent the wheel rather learn to use
Coding
Prevention is better than the cure!
CONFIDENTIAL
o My code my responsibility
o For every professional there are some basic rules. E.g.
o Doctor wear aprons
o Accountants have a calculator
o Chefs wears toque
o Easy to understand + Easy to change
o Redundant layers
o No meaningful names
o Careful yourself with dependencies. E.g.
o Singular direction.
o Commenting
o Tests
o Integration test
o Unit test
o Development Strategy
Web Architecture
Course Brief Time: 2 hours
The diagram
CONFIDENTIAL
How WWW [Web Addresses] Translates
CONFIDENTIAL
Monoliths
Overview
Monolith means composed all in one piece. The Monolithic application describes a single-
tiered software application in which different components combined into a single program
from a single platform. Components can be:
- Authorization
- Presentation
- Business Logic
- Database Layer
- Integrations
Figure: Monolithic Architecture (for E-Commerce Application)
Benefits
Simple to develop — At the beginning of a project it is much easier to go with
Monolithic Architecture.
CONFIDENTIAL
Simple to test. For example, you can implement end-to-end testing by simply launching
the application and testing the UI with Selenium.
Simple to deploy. You have to copy the packaged application to a server.
Simple to scale horizontally by running multiple copies behind a load balancer.
Drawbacks
Maintenance — If Application is too large and complex to understand entirely, it is
challenging to make changes fast and correctly.
The size of the application can slow down the start-up time.
You must redeploy the entire application on each update.
Monolithic applications can also be challenging to scale when different modules have
conflicting resource requirements.
Reliability — Bug in any module (e.g. memory leak) can potentially bring down the
entire process. Moreover, since all instances of the application are identical, that bug
impact the availability of the entire application
Regardless of how easy the initial stages may seem; Monolithic applications have
difficulty to adopting new and advance technologies. Since changes in languages or
frameworks affect an entire application, it requires efforts to thoroughly work with the
app details, hence it is costly considering both time and efforts.
Microservices
Overview
Microservices are an approach to application development in which a large application is built
as a suite of modular services (i.e. loosely coupled modules/components). Each module
supports a specific business goal and uses a simple, well-defined interface to communicate with
other sets of services.
Instead of sharing a single database as in Monolithic application, each microservice has its own
database. Having a database per service is essential if you want to benefit from microservices,
because it ensures loose coupling. Each of the services has its own database. Moreover, a
service can use a type of database that is best suited to its needs.
CONFIDENTIAL
CONFIDENTIAL
Micro frontends
Quick Summary
The micro-frontend architecture has slowly but gradually gained popularity and has now
become one of the most sought-after frontend development strategies. Developers appreciate
the agility and freedom that comes along with this architecture and organizational stability it
imparts is making life easier for CTOs worldwide. With multiple implementation strategies and
tons of advantages, the micro-frontend architecture seems set to revolutionize frontend
development and scaling.
What is Micro-frontend Architecture?
Micro-frontend architecture is a strategy in which the traditionally monolithic frontend
codebase is split into smaller apps, ideally addressing the various business domains. All these
smaller elements form a seamless frontend interface that delivers top-notch user experience
and is easy to modify and scale.
CONFIDENTIAL
Benefits
- Design and development flexibility
- Decoupled codebases
- Automation
- Fault isolation
- Scalability
- Faster build time
- Simpler maintenance
- Independent Deployment
- Autonomous team
- Reusability
Drawbacks
- Operational complexities
- Inconsistent user experience
- Poor communication between components
- Larger payloads
How it works?
Programming languages
CONFIDENTIAL
Frontends
HTML5 is the next major revision of the HTML standard superseding HTML 4.01, XHTML 1.0,
and XHTML 1.1. HTML5 is a standard for structuring and presenting content on the World Wide
Web.
HTML5 is a cooperation between the World Wide Web Consortium (W3C) and the Web
Hypertext Application Technology Working Group (WHATWG).
The new standard incorporates features like video playback and drag-and-drop that have been
previously dependent on third-party browser plug-ins such as Adobe Flash, Microsoft
Silverlight, and Google Gears.
CONFIDENTIAL
HTML5 Tags
The following section contains a complete list of standard tags belonging to the latest HTML5
and XHTML 1.1 specifications. All the tags are listed alphabetically.
Ref: https://www.tutorialrepublic.com/html-reference/html5-tags.php
CSS (Cascading Style Sheets) consist of a group of formatting rules that you use to control the
layout and appearance of the content on a web page. One really great feature of CSS is that you
can store all the CSS rules in one document and keep that document separate from the HTML
content and link the two together. Then, when you make a change to the CSS that change is
instantly and automatically updated on all the HTML files. Another great feature is that it
“cleans up” the appearance of the code on web pages. In addition, it will speed up browser
CONFIDENTIAL
loading times.
What CSS gives you is incredible control over the appearance of your page. You can control
properties such as font sizes, bolding, italics, text shadows and color, link color and much more.
And of course, you can go far beyond that with page layout tools, boxes, formatting,
positioning, etc. In CSS3, there are many options, a few which we’ll look at here. These include
animation, gradients, media queries, shadows, transitions, the font-face rule that allows you to
embed fonts on a web page, and more.
CSS Save Lots of Time — CSS gives lots of flexibility to set the style properties of an
element. You can write CSS once; and then the same code can be applied to the groups
of HTML elements, and can also be reused in multiple HTML pages.
Easy Maintenance — CSS provides an easy means to update the formatting of the
documents, and to maintain the consistency across multiple documents. Because the
content of the entire set of web pages can be easily controlled using one or more style
sheets.
Pages Load Faster — CSS enables multiple pages to share the formatting information,
which reduces complexity and repetition in the structural contents of the documents. It
significantly reduces the file transfer size, which results in a faster page loading.
Superior Styles to HTML — CSS has much wider presentation capabilities than HTML
and provide much better control over the layout of your web pages. So you can give far
better look to your web pages in comparison to the HTML presentational elements and
attributes. CONFIDENTIAL
Multiple Device Compatibility — CSS also allows web pages to be optimized for more
than one type of device or media. Using CSS the same HTML document can be
presented in different viewing styles for different rendering devices such as desktop, cell
phones, etc.
Ref : https://www.tutorialrepublic.com/css-tutorial/css-get-started.php
CONFIDENTIAL
What is Stylus?
Stylus is a dynamic stylesheet preprocessor language that is compiled into Cascading Style
Sheets (CSS). Its design is influenced by Sass and LESS. It's regarded as the fourth most used CSS
preprocessor syntax. It was created by TJ Holowaychuk, a former programmer for Node
CSS in itself is devoid of complex logic and functionality which is required to write reusable and
organized code. As a result, a developer is bound by limitations and would face extreme
difficulty in code maintenance and scalability, especially when working on large projects
involving extensive code and multiple CSS stylesheets. This is where CSS Preprocessors come to
the rescue.
A CSS Preprocessor is a tool used to extend the basic functionality of default vanilla CSS through
its own scripting language. It helps us to use complex logical syntax like – variables, functions,
mixins, code nesting, and inheritance to name a few, supercharging your vanilla CSS. By using
CSS Preprocessors, you can seamlessly automate menial tasks, build reusable code snippets,
avoid code repetition and bloating and write nested code blocks that are well organized and
easy to read.
However, browsers can only understand native vanilla CSS code and will be unable to interpret
the CSS Preprocessor syntax. Therefore, the complex and advanced Preprocessor syntax needs
to be first compiled into native CSS syntax which can then be interpreted by the browsers to
avoid cross browser compatibility issues. While different Preprocessors have their own unique
syntaxes, eventually all of them are compiled to the same native CSS code.
Moving forward in the article, we will take a look at the 3 most popular CSS Preprocessors
currently being used by developers around the world i.e Sass, LESS, and Stylus.
CONFIDENTIAL
 
COMPILED CSS
In both cases, be it Sass or SCSS, the compiled CSS code will be the same –
Syntax Declaration: Stylus
Uses .styl extension. Stylus offers a great deal of flexibility in writing syntax, supports native CSS
as well as allows omission of brackets colons and semicolons. Also, note that Stylus does not
use @ or $ symbols for defining variables. Instead, Stylus uses the assignment operators to
indicate a variable declaration.
Stylus
CONFIDENTIAL
COMPILED CSS
More Information:
SASS docs: http://sass-lang.com/
Stylus docs: http://stylus-lang.com/
CSS Flexbox: A Complete Guide
This guide explains everything about flexbox, focusing on different properties for the flex
container (the parent element) and the flex items (the child elements). It includes various
examples and lifehacks.
CSS flexbox (Flexible Box Layout Module) is a layout module that consists of the flex container
(the parent element) and the flex items (the children elements). The flex items can be
organized as a row or as a column, and the available free space can be distributed between
them in various ways.
CONFIDENTIAL
CONFIDENTIAL
Ø And more
Flexbox elements can have many properties some of which are set on the flex container and
the others are set on the flex items.
Properties that apply to the flex container:
Ø align-content
Ø align-items
Ø display
Ø flex-direction
Ø flex-flow
Ø flex-wrap
Ø justify-content
Ø flex
Ø flex-basis
Ø flex-grow
Ø flex-shrink
Ø order
How to Create the Flex Container
The display: flex; property applies to the container, makes the container a block element, and
enables the flex layout for all its direct children.
The display: inline-flex; works in the same way. Only it creates a container as an inline element.
How to Create a Row or Column
If you want to arrange the flex items to look like a row or a column, apply the flex-direction
property to the container.
The flex-direction: row; property will make a horizontal row. The row is the default value.
CONFIDENTIAL
If you have more items that can fit in one row and you still want a horizontal layout, the flex-
wrap: wrap; property will come in handy. This way, the flex items will wrap onto multiple lines
inside the flex container. The default value is flex-wrap: nowrap;.
To make a vertical column, apply the flex-direction: column; to the container.
CONFIDENTIAL
CONFIDENTIAL
Ø space-between: items are evenly distributed in the line (the first item is on the left, the
last item on the right)
Ø space-around: items are evenly distributed in the line with equal space on both sides of
the items. Note that visually the spaces aren’t equal since all the items have equal space
on both sides. The margins of adjacent flex items do not collapse. The first item will have
one unit of space against the container edge, but two units of space between the next
item because that next item has its own spacing that applies
Ø space-evenly: items are distributed so that the spacing between any two items (and the
space to the edges) is equal
CONFIDENTIAL
How to Align Elements Vertically
To align flex items vertically, use the align-items, align-content or align-self properties.
Align-items
To define the vertical alignment of several items, apply the align-items property to the
container. This property may have one of the following values:
Ø stretch: items are stretched to fill the container, still respecting min-width and max-
width properties (it’s the default value)
Ø flex-start: items are placed in the top part of the container
CONFIDENTIAL
Align-content
To define the vertical alignment of several lines of items, use the align-content property. This
property has no effect when there is only one line of flex items.
This property only works if two conditions are met:
Ø The wrap value should be applied toCONFIDENTIAL
the flex container
Ø The flex container should be higher than the lines of the flex items
In other words, there must be additional vertical space inside the container, which should be
larger than the sum of all the heights of the rows of elements.
This property may have one of the following values:
Ø stretch: lines stretch to take up all the available space in the container (it’s the default
value)
Ø flex-start: lines are placed in the top part of the container
Ø space-around: lines are evenly distributed with equal space around each line
CONFIDENTIAL
Align-self
To vertically align individual items, use the align-self property. It applies to the flex items, not
to the flex container. It is useful to override the alignment specified for the flex container with
the help of the align-items property.
The align-self property may have one of the following values (the same ones as in the case of
the align-items property plus auto):
Ø auto: equals to the value specified in the align-items property for the flex container (it’s
the default value)
Ø stretch: items are stretched to fill the container, still respecting min-width and max-
width properties
CONFIDENTIAL
CONFIDENTIAL
To arrange flex items in a column bottom to top, use the flex-direction: column-reverse;
property.
CONFIDENTIAL
Instead of flex-direction, you can choose the shorter flex-flow property to apply those values:
Wrap-reverse
There is also the flex-wrap: wrap-reverse; property that allows wrapping flex items onto
multiple lines from bottom to top.
How to Make the Elements Grow or Shrink
The flexibility of flex items is determined by the flex-basis, flex-grow, and flex-shrink
properties.
Flex-basis CONFIDENTIAL
The flex-basis property defines the default size of the flex item before the available space is
distributed. You can set an absolute value (e. g. 200px or 10em), a percentage value (e. g. 50%)
or a keyword (auto, content).
The flex-basis property can be interpreted as the minimum width of the flex item. If you specify
a flex-basis value, it will set the width for the specific item, but depending on other flex
parameters the flex item may become wider (or narrower) than the flex-basis value.
The default value is auto. It retrieves the value of the width property. And the content value is
based on the flex item’s content.
If you do not set a flex-basis value and set the flex-grow value to 0, the element will be
compressed to its minimum size.
Flex-grow
The flex-grow property applies to individual flex items and defines the ability of a flex item to
grow. It dictates what amount of the available space inside the flex container the item should
take up. It accepts a unitless value that serves as a proportion. The default value is 0. Negative
numbers are invalid.
If all items have flex-grow set to 1, the remaining space in the container will be distributed
equally to all children. If the flex-grow value of an item is set to 2, it will get 2 times more pixels
to the original width than other items with the flex-grow value 1.
Flex-shrink
The flex-shrink property applies to the flex items and indicates how much each element
will be reduced if there is not enough available space. It accepts a unitless value that
serves as a proportion. The default value is 1. The value 0 allows keeping the item’s
original size. Negative numbers are invalid.
The idea of responsive design is that the product can adapt itself to any reading device the user may use. It’s
more or less like transforming the content into water, mimicking the liquid’s ability to fill any type of glass. This
CONFIDENTIAL
shows that the old way of creating websites, using fixed positions, is all but dead and buried.
Web pages can be viewed using many different devices. Your web page should look good and needs to be
interactive, regardless of the device. When you use CSS to resize, hide, shrink and enlarge content to make it look
better, it is called CSS Responsive Design. CSS Responsive Design responds to the needs of the users and the
devices they are using. The layout changes based on the size and capabilities of the device. CSS Responsive Design
ensure that web pages don't leave out information to fit smaller devices, but rather adapt its content to fit any
device such as Desktop, Tablet or Phone.
Single breakpoint
@media (min-width: 768px) and (max-width: 991.98px) { ... }
Max-width
// X-Small devices (portrait phones, less than 576px)
CONFIDENTIAL
@media (max-width: 575.98px) { ... }
// Small devices (landscape phones, less than 768px)
@media (max-width: 767.98px) { ... }
// Medium devices (tablets, less than 992px)
@media (max-width: 991.98px) { ... }
// Large devices (desktops, less than 1200px)
@media (max-width: 1199.98px) { ... }
// X-Large devices (large desktops, less than 1400px)
@media (max-width: 1399.98px) { ... }
Assignment:
Using HTML5, CSS3 and JAVASCRIPT complete a Restaurant Responsive Website Design with
Google font and JS library
Introduction
JavaScript is the world's most popular programming language.
JavaScript is the mother language of the Web.
JavaScript is easy to learn.
JavaScript is one of the 3 languages all web developers must learn:
1. HTML to define the content of web pages
2. CSS to specify the layout of web pages
3. JavaScript to program the behavior of web pages
CONFIDENTIAL
JS Functions CONFIDENTIAL
Self-Invoking Functions
For function parameters:
Arguments are Passed by Value
Objects are Passed by Reference
CONFIDENTIAL
CONFIDENTIAL
With the object model, JavaScript gets all the power it needs to create dynamic HTML:
JSON
JSON stands for JavaScript Object Notation
JSON is a text format for storing and transporting data
JSON is "self-describing" and easy to understand
name
age
car
Each property has a value.
Use the JavaScript function JSON.parse() to convert text into a JavaScript object:
Is similar to
CONFIDENTIAL
When a user visits a web page, his/her name can be stored in a cookie.
Next time the user visits the page, the cookie "remembers" his/her name.
More storages are localStorage, sessionStorage.
We can set cookie expiry but localStorage does not have any expiry.
sessionStorage gets cleared when browser closed.
localStorage and sessionStorage did not pass to header on page visits like cookie.
Among them only cookie can be read/written both from frontend JS and backend.
JS Library
jQuery was created in 2006 by John Resig. It was designed to handle Browser Incompatibilities
and to simplify HTML DOM Manipulation, Event Handling, Animations, and Ajax.
For more than 10 years, jQuery has been the most popular JavaScript library in the world.
However, after JavaScript Version 5 (2009), most of the jQuery utilities can be solved with a few
lines of standard JavaScript.
Web API
When JavaScript runs in browser it can't do any OS operation except window.print() method
which open printer window of the OS.
All browsers have a set of built-in Web APIs to support complex operations, and to help
accessing data.
For example, the Geolocation API can return the coordinates of where the browser is located.
JS Class
CONFIDENTIAL
ECMAScript 2015, also known as ES6, introduced JavaScript Classes.
JavaScript Classes are templates for JavaScript Objects.
If you want to give support for old browsers before 2015 then you have to write all of your
JavaScript code using version ES5.
JS Assignment:
Introduction
Node.js is an open-source server environment.
Node.js allows you to run JavaScript on the server.
Node.js uses asynchronous programming!
Node.js can generate dynamic page content.
Node.js can create, open, read, write, delete, and close files on the server.
Node.js can collect form data.
Node.js can add, delete, modify data in your database.
Node.js can be used as a Backend system with help of its HTTP package.
Unlike browser JavaScript when program inCONFIDENTIAL
Node.js try using Latest LTS version of Node and
latest stable version of libraries and you can use latest JS version code without any doubt.
Getting Started
Create your app.js file and add following content.
Node Library
For Node.js npm and yarn are the two most popular package manager.
It creates a package.json in the project directory when install any library like below
npm install mongodb
Node MVC framework
Express JS is a Fast, unopinionated, minimalist web framework for node.
npm install -g express-generator
Install package.json and Run Project
npm install
node app.js or npm start
Install a new plugin and save in package.json
npm install –save express-validator CONFIDENTIAL
Environment setup:
https://www.tutorialspoint.com/vuejs/vuejs_environment_setup.htm
• VueJs overview
Basic structure:
• https://www.tutorialspoint.com/vuejs/vuejs_introduction.htm
• https://www.w3schools.com/whatis/whatis_vue.asp
// options
})
Example:
index.html
<html>
<head>
<title>VueJs Instance</title>
<script type = "text/javascript" src = "js/vue.js"></script>
</head>
<body>
CONFIDENTIAL
<div id = "vue_det">
<h1>Firstname : {{firstname}}</h1>
<h1>Lastname : {{lastname}}</h1>
<h1>{{mydetails()}}</h1>
</div>
<script type = "text/javascript" src = "js/index.js"> </script>
</body>
</html>
index.js
var vm = new Vue({
el: '#vue_det',
data: {
firstname : "John",
lastname : "Doe",
address : "Florida"
},
methods: {
mydetails : function() {
return "I am "+this.firstname +" "+
this.lastname;
}
}
})
In the above code snippet, el takes HTML DOM to render data to view. data: includes
variables declaration and initializations. methods: includes all the functions used in the
page.
More details: https://www.tutorialspoint.com/vuejs/vuejs_instances.htm
• Directives: Directives are instruction for VueJS to do things in a certain way. We have
CONFIDENTIAL
already
seen directives such as v-if, v-show, v-else, v-for, v-bind , v-model, v-on, v-html etc.
o v-if/v-else: Implement conditional expression
o v-show: Control visibility of an element
o v-for: Implement loop
o v-bind: bind one or more attributes, or a component prop to an element
o v-model: The v-model is a two-way binding which means if you change the input
value, the bound data will be changed. The v-model directive is used to create
two-way data bindings on form input, textarea, and select elements.
o v-on: The v-on directive is a Vue.js directive used to add a event listener to an
element. First, we will create a div element with id as app and let’s apply the v-
on:click directive to a element. Further, we can execute a function when click
even occurs.
o v-html: With v-html directive Vue js can render HTML directly. It is useful to
render dynamic HTML in real time.
• Computed: These properties may at first look like they’d be used like a method, but are
not. In Vue, we use data to track changes to a particular property that we’d like to be
reactive. Computed properties allow us to define a property that is used the same way
as data, but can also have some custom logic that is cached based on its dependencies.
You can consider computed properties another view into your data.
More details: https://www.tutorialspoint.com/vuejs/vuejs_computed_properties.htm
• Watchers: Watchers allow us to listen data change event with an efficient way. We can
watch change event and act accordingly with custom logic.
More details: https://www.geeksforgeeks.org/vue-js-watchers/
• Mixin: Mixins are used to reuse code in Vue components that perform the same action.
Mixins are like functions in C programming. We can define some actions in mixins and
use it wherever it is necessary. Code reusability is simple with the help of mixins.
More details: https://www.geeksforgeeks.org/vue-js-mixins/
VueJs Advance
• Vue Cli: Vue Cli has been very popular to develop SPA (Single Page Application). Using
some simple command we can create and install the environment,
create/debug/run/test vue js project from the command line interface.
Prepare environment: https://cli.vuejs.org/guide/installation.html
Create and run project: https://cli.vuejs.org/guide/creating-a-project.html
• Vue component: One important feature of Vue is the ability to use components.
CONFIDENTIAL
Components are reusable Vue instances with custom HTML elements. Components can
be reused as many times as you want or used in another component, making it a child
component. Data, computed, watch, and methods can be used in a Vue component.
CONFIDENTIAL
• Single file component: When creating large web applications with different
functionalities, it’s best to break down the application into single file components. This
enables you to have your templates, scripts, and styles all in one file with a .vue file
extension
More details: https://www.educative.io/edpresso/what-are-vue-components
• Props and event emitter: One component can communicate with another component
with props and event emitter. Props share data and event emitter listen and trigger
custom event in real time.
More details: https://www.geeksforgeeks.org/communication-between-components-
using-emit-and-props-in-vue-js/
• Routing: Vue JS router allows the user to switch between pages without refreshing the
page. This is what makes navigation easy and really nice in your web applications.
More details: https://www.freecodecamp.org/news/how-to-use-routing-in-vue-js-to-
create-a-better-user-experience-98d225bbcdd9/
CONFIDENTIAL
• State management with Vuex: Vuex is a state management library for Vue applications.
It serves as a single source of truth in the whole application and centralizes the flow of
data to various components. As we know passing props can be tedious for complex
applications with many components, Vuex makes this interaction very seamless and
scalable.
CONFIDENTIAL
VueJs Assignment
Develop a Vue JS component with a Datepicker
Develop a Vue JS component of price picker slider
Develop a dashboard page based on multiple component
o Resources
https://www.creative-tim.com/product/material-dashboard
https://demos.creative-tim.com/material-dashboard/examples/
dashboard.html
Backends
RDBMS & No SQL
Course Brief Time: 2 hours
RDBMS: Relational databases accessed with SQL (Structured Query Language) were developed
in the 1970s with a focus on reducing data duplication as storage was much more costly than
developer time.
o MySQL/MariaDB
o PostgreSQL
o Oracle
o MSSQL
All of above databases are available as a scalable service called AWS RDS
NOSQL: NoSQL (“non-SQL” or “not only SQL”) databases were developed in the late 2000s with
a focus on scaling, fast queries, allowing for frequent application changes, and making
programming simpler for developers. One of the most frequently cited drawbacks of NoSQL
CONFIDENTIAL
databases is that they don’t support ACID (atomicity, consistency, isolation, durability)
transactions across multiple documents. To address these use cases MongoDB added support
for multi-document ACID transactions in the 4.0 release, and extended them in 4.2 to span
sharded clusters.
5. MongoDB
6. AWS DynamoDB
7. SOLR
8. Elasticsearch
9. Aerospike
Elasticsearch is also available in AWS as a service. Kibana is a developer guy for Elasticsearch.
Every popular programming language like PHP, Python, Go, Node.js and many frameworks have
database driver for these SQL and NOSQL databases.
It is recommended to install your local databases using docker.
Example: https://hub.docker.com/_/mongo
Database Assignment:
Step-1) To download and install Python, visit the official website of Python
https://www.python.org/downloads/ and choose your version
Step 2) Once the download is completed, run the .exe file to install Python. Now click on Install
Now.
How to Install PyCharm
Step 1) To download PyCharm visit the website
https://www.jetbrains.com/pycharm/download/ and Click the “DOWNLOAD” link under the
Community Section.
Step 2) Once the download is complete, run the exe for install PyCharm. The setup wizard
should have started. Click “Next”.
What is a Variable in Python?
A Python variable is a reserved memory location to store values. In other words, a variable in a
python program gives data to the computer for processing
Python Variable Types
Every value in Python has a datatype. Different data types in Python are Numbers, List, Tuple,
Strings, Dictionary, etc. Variables in Python can be declared by any name or even alphabets like
a, aa, abc, etc.
How to Declare and use a Variable
a=100
print (a)
Re-declare a Variable
f=0
print f
f = 'guru99'
print f
Python String Concatenation and Variable
a="Guru"
b = 99
print(a+str(b))
Python Variable Types: Local & Global
There are two types of variables in Python, Global variable and Local variable. When
you want to use the same variable for rest of your program or module you declare it
CONFIDENTIAL
as a global variable, while if you want to use the variable in a specific function or
method, you use a local variable while Python variable declaration.
# Declare a variable and initialize it
f = 101
print f
# Global vs. local variables in functions
def someFunction():
# global f
f = 'I am learning Python'
print f
someFunction()
print f
Data Structure
Lists
Lists are very similar to arrays. They can contain any type of variable, and they can contain as
many variables as you wish. Example
mylist = []
mylist.append(1)
mylist.append(2)
mylist.append(3)
print(mylist[0]) # prints 1
print(mylist[1]) # prints 2
print(mylist[2]) # prints 3
Dictionary
A Dictionary in Python is the unordered and changeable collection of data values that
holds key-value pairs
Dict = {'Tim': 18,'Charlie':12,'Tiffany':22,'Robert':25} print (Dict['Tiffany'])
Updating Dictionary
Dict = {'Tim': 18,'Charlie':12,'Tiffany':22,'Robert':25}Dict.update({"Sarah":9})
Delete Keys from the dictionary
Dict = {'Tim': 18,'Charlie':12,'Tiffany':22,'Robert':25}del Dict ['Charlie']
CONFIDENTIAL
Tuples
Tuples are used to store multiple items in a single variable.
A tuple is a collection which is ordered and unchangeable
thistuple = ("apple", "banana", "cherry")
print(thistuple)
Conditional Loops
Conditions
Python uses boolean logic to evaluate conditions. The boolean values True and False are
returned when an expression is compared or evaluated. For example:
x=2
print(x == 2) # prints out True
print(x == 3) # prints out False
print(x < 3) # prints out True
The "and" and "or" boolean operators allow building complex boolean expressions, for
example:
name = "John"
age = 23
if name == "John" and age == 23:
print("Your name is John, and you are also 23 years old.")
if name == "John" or name == "Rick":
print("Your name is either John or Rick.")
The "in" operator could be used to check if a specified object exists within an iterable object
container, such as a list:
name = "John"
if name in ["John", "Rick"]:
print("Your name is either John or Rick.")
Loops
There are two types of loops in Python, for and while.
For loops iterate over a given sequence. Here is an example:
primes = [2, 3, 5, 7]
for prime in primes:
print(prime)
While loops repeat as long as a certain boolean condition is met. For example:
count = 0 CONFIDENTIAL
while count < 5:
print(count)
count += 1
break is used to exit a for loop or a while loop, whereas continue is used to skip the current
block, and return to the "for" or "while" statement. A few examples:
Functions
Functions are a convenient way to divide your code into useful blocks, allowing us to order our
code, make it more readable, reuse it and save some time. Also functions are a key way to
define interfaces so programmers can share their code.
Functions in python are defined using the block keyword "def", followed with the function's
name as the block's name. For example:
def my_function():
print("Hello From My Function!")
Functions may also receive arguments (variables passed from the caller to the function). For
example:
def my_function_with_args(username, greeting):
print("Hello, %s , From My Function!, I wish you %s"%(username, greeting))
Functions may return a value to the caller, using the keyword- 'return'. For example:
def sum_two_numbers(a, b): CONFIDENTIAL
return a + b
How do you call functions in Python?
def my_function():
print("Hello From My Function!")
my_function()
File Handling
In Python, there is no need for importing external library to read and write files. Python
provides an inbuilt function for creating, writing, and reading files.
How to Create a Text File in Python
Step 1) Open the .txt file
f= open("guru99.txt","w+")
Step 2) Enter data into the file
for i in range(10):
f.write("This is line %d\r\n" % (i+1))
Step 3) Close the file instance
f.close()
You can read a file in Python by calling .txt file in a “read mode”(r).
Step 1) Open the file in Read mode
f=open("guru99.txt", "r")
Step 2) We use the mode function in the code to check that the file is in open mode. If yes, we
proceed ahead
if f.mode == 'r':
Step 3) Use f.read to read file data and store it in variable content for reading files in Python
contents =f.read()
Classes and Objects
Objects are an encapsulation of variables and functions into a single entity. Objects get their
variables and functions from classes. Classes are essentially a template to create your objects.
A very basic class would look something like this:
class MyClass:
variable = "blah" CONFIDENTIAL
def function(self):
print("This is a message inside the class.")
To access the variable inside of the newly created object "myobjectx" you would do the
following:
class MyClass:
variable = "blah"
def function(self):
print("This is a message inside the class.")
myobjectx = MyClass()
myobjectx.variable
To access a function inside of an object you use notation similar to accessing a variable:
myobjectx.function()
Modules
Modules in Python are simply Python files with a .py extension. The name of the module will be
the name of the file. A Python module can have a set of functions, classes or variables defined
and implemented. In the example above, we will have two files, we will have:
mygame/
mygame/game.py
mygame/draw.py
Modules are imported from other modules using the import command. In this example, the
game.py script may look something like this:
CONFIDENTIAL
We may also use the import * command to import all objects from a specific module, like this:
from draw import *
def main():
result = play_game()
draw_game(result)
References
https://www.learnpython.org/
https://www.guru99.com/python-tutorials.html
https://docs.python.org/3.9/tutorial/index.html
Assignments
1. Print the following pattern
2. Display numbers from a list using loop
Write a program to display only those numbers from a list that satisfy the following conditions
CONFIDENTIAL
6. Given a Python list of numbers. Turn every item of a list into its square
CONFIDENTIAL
Django is easy to set up and run. It offers a variety of options to get started
It provides a ready-to-use user interface for administrative activities
It enables multilingual websites by using its built-in internationalization system
Django helps you to provide end-to-end application testing
Helps you to document your API with an HTML output
REST Framework has rich support for several authentication protocols
Features of Django
Below are the features of Django: 10 Behavioral Interview Questions and Answers
Components of Django
Form:
Django has a powerful form library which handles rendering forms as HTML. The library helps
in validating submitted data and converting it to Python types.
Authentication:
It handles user accounts, groups, cookie-based user sessions, etc.
Admin:
It reads metadata in your models to provide a robust interface which can be used to manage
content on your site.
Internationalization:
Django provides support for translating text into various languages, locale-specific formatting
of dates, times, numbers, and timezones.
Security:
Django provides safeguard against the following attacks:
Django Basics
Install Django by giving following command-pip install django
Creating a Project
To initiate a project of Django on Your PC, open Terminal and Enter the following command
django-admin startproject projectName
A New Folder with name projectName will be created. To enter in the project using terminal
enter command cd projectName
Now run, python manage.py runserver
To create a basic app in your Django project you need to go to directory containing manage.py
and from there enter the command: python manage.py startapp projectApp
To consider the app in your project you need to specify your project name in INSTALLED_APPS
list as follows in settings.py:
INSTALLED_APPS = [
'projectApp'
]
Now in the list of URL patterns, you need to
specify app name for including your app urls.
Here is the code for it –
urlpatterns = [
path('admin/', admin.site.urls),
# Enter the app name in following syntax for
this to work
path('', include("projectApp.urls")),
CONFIDENTIAL
]
Django Views
Django views are divided into two major categories: -
Function-Based Views
Class-Based Views
Function based view Example –
Let’s Create a function-based view list view to display instances of a model. Let’s create a view
and template for the same. In geeks/views.py,
Class-based views are simpler and efficient to manage than function-based views. A function-
based view with tons of lines of code can be converted into class-based views with few lines
only. This is where Object-Oriented Programming comes into impact.
Django Models
A Django model is the built-in feature that Django uses to create tables, their fields, and various
constraints. In short, Django Models is the SQL of Database one uses with Django
Basics of a model include –
CONFIDENTIAL
Whenever we create a Model, Delete a Model, or update anything in any of models.py of our
project. We need to run two commands makemigrations and migrate
So when we run, Python manage.py makemigrations
SQL Query to create above Model as a Table is created and Python manage.py migrate
creates the table in the database.
Django Forms
When one creates a Form class, the most important part is defining the fields of the form. Each
field has custom validation logic, along with a few other hooks.
Django handles three distinct parts of the work involved in forms:
CONFIDENTIAL
CONFIDENTIAL
References
https://www.geeksforgeeks.org/django-tutorial/
https://docs.djangoproject.com/en/3.2/
https://www.tutorialspoint.com/django/index.htm
Assignment
Show vacation rental properties from database
Search functionaliies using location name and show location wise properties
Example: https://www.rentbyowner.com/listing?q=Destin,%20FL,%20USA&ref=home
Flask
What is Flask
Flask is a web framework that provides libraries to build lightweight web applications in python.
It is based on WSGI toolkit and jinja2 template engine. Flask is considered as a micro
framework.
Features of Flask
Here, are important features of Flask
Ø Integrated support for unit testing.
Ø RESTful request dispatching.
Ø Uses a Ninja2 template engine.
Ø It is based on Werkzeug toolkit.
Ø Support for secure cookies (client-side sessions).
Ø Extensive documentation.
Ø Google app engine compatibility.
Ø APIs are nicely shaped and coherent
Ø Easily deployable in production
CONFIDENTIAL
CONFIDENTIAL
CONFIDENTIAL
Flask Templates
Flask provides us the render_template() function which can be used to render the external
HTML file to be returned as the response from the view function.
Consider the following example.
Message.html
Script.py
Flask Redirect and Errors
Flask class provides the redirect() function which redirects the user to some specified URL with
the specified status code. Example
CONFIDENTIAL
@app.route('/validate', methods = ["POST"])
def validate():
return redirect(url_for("success"))
return redirect(url_for("login"))
The abort() function is used to handle the cases where the errors are involved in the requests
from the client side, such as bad requests, unauthorized access and many more. Example:
def validate():
return redirect(url_for("success"))
else:
abort(401)
Flask WTF
WTF stands for WT Forms which is intended to provide the interactive user interface for the
user. The WTF is a built-in module of the flask which provides an alternative way of designing
forms in the flask web applications.
Install flask WTF pip install flask-wtf
Example:
CONFIDENTIAL
References
https://www.javatpoint.com/flask-tutorial
https://flask.palletsprojects.com/en/2.0.x/
https://www.tutorialspoint.com/flask/index.htm
Assignment
Show property details page from database
Example: https://www.rentbyowner.com/property/universal-s-aventura-hotel/BC-
2327796
The following covers the primary components included with your new project. First, take a look
at the generated directory:
CONFIDENTIAL
Adding Features
Before we can create anything, we need some way to store it. For this project, we've chosen
TinyDB, a light-weight key-value database that stores data on disk in a single JSON file.
Let's begin by adding the dependency to our requirements.txt file
Install the new requirements with pip: pip install -r requirements.txt
Find and modify the following section of todo/main.py in order to define a default configuration
for our database file called db_file:
CONFIG = init_defaults('todo')
CONFIG['todo']['db_file'] = '~/.todo/db.json'
CONFIDENTIAL
Add the following hooks meta option to our Todo app in todo/main.py:
Controllers
When using application controllers there must be a single base controller responsible for
handling runtime dispatch. All other controllers are then stacked on top of the base controller
(or other controllers already stacked on base). The base controller is the root of the
application's command-line namespace.
Controller method example:
@ex(help="Add Task”)
def add_task():
print(”Add Task”)
How to Run
python setup.py install
todo add-task.py
References
https://docs.builtoncement.com/
CONFIDENTIAL
Assignment
Write a script for insert data into rental_properties table from json file.
Rental_properties tables fields
o Id
o Property_name
o Property_description
o Price
o Amenities
o Property_ type
o Image_link
Click
Tutorial
Click is a Python package for creating beautiful command line interfaces in a composable way
with as little code as necessary. It’s the “Command Line Interface Creation Kit”. It’s highly
configurable but comes with sensible defaults out of the box
Click in three points:
Hello John!
References
https://click.palletsprojects.com/en/8.0.x/
Assignment
Write a script for insert data into rental_properties table from json file.
Rental_properties tables fields
o Id
o Property_name
o Property_description
o Price
o Amenities
o Property_ type
o Image_link
Golang
Course Brief Time: 8 hours
Setup Environment
Installation: https://golang.org/doc/install
IDE:
o Goland (Activator)
o VSCode with Go Extension
Prepare Workspace
o Create go workspace directory inside your home directory
Windows: C:/Users/name/go/src
Mac/Ubuntu: $HOME/go/src
o Few important commands
Set GOPATH:
Windows: SET GOPATH=C:/Users/<name>/go/bin
Mac/Ubuntu: export GOPATH=$HOME/go/bin
Get Go Path: go env GOPATH
Set GOBIN:
Windows: SET GOBIN=C:/Users/<name>/go/bin
Mac/Ubuntu: export GOBIN=$HOME/go/bin
Check Go environment variables: go env
Run go program: go run main.go
Build go program: go build main.go
CONFIDENTIAL
More details: https://www.tutorialspoint.com/go/go_environment.htm
Golang Basics
Why Golang: Go language is a programming language initially developed at Google in
the year 2007 by Robert Griesemer, Rob Pike, and Ken Thompson. It is a statically-typed
language having syntax similar to that of C. It provides garbage collection, type safety,
dynamic-typing capability, many advanced built-in types such as variable length arrays
and key-value maps. It also provides a rich standard library. The Go programming
language was launched in November 2009 and is used in some of the Google's
production systems.
Golang structure and syntax:
A Go program basically consists of the following parts −
o Package Declaration
o Import Packages
o Functions
o Variables
o Statements and Expressions
o Comments
Let us look at a simple code that would print the words "Hello World" −
package main
import "fmt"
func main() {
/* This is my first sample program. */
fmt.Println("Hello, World!")
}
Data types: In the Go programming language, data types refer to an extensive system
used for declaring variables or functions of different types. The type of a variable
determines how much space it occupies in storage and how the bit pattern stored is
interpreted.
o Boolean types: They are boolean types and consists of the two predefined
constants: (a) true (b) false
o Numeric types: They are again arithmetic types and they represents a) integer
types or b) floating point values throughout the program.
o String types: A string type represents the set of string values. Its value is a
sequence of bytes. Strings are immutable types that is once created, it is not
possible to change the contents of a string. The predeclared string type is string.
o Derived types: They include (a)CONFIDENTIAL
Pointer types, (b) Array types, (c) Structure types,
(d) Union types and (e) Function types f) Slice types g) Interface types h) Map
types i) Channel Types
More details: https://www.tutorialspoint.com/go/go_data_types.htm
Variables: A variable is nothing but a name given to a storage area that the programs
can manipulate. Each variable in Go has a specific type, which determines the size and
layout of the variable's memory, the range of values that can be stored within that
memory, and the set of operations that can be applied to the variable.
The name of a variable can be composed of letters, digits, and the underscore character.
It must begin with either a letter or an underscore. Upper and lowercase letters are
distinct because Go is case-sensitive.
o Static Type Declaration: var x float64
o Dynamic Type Declaration / Type Inference: y := 42
o Mixed Variable Declaration: var a, b, c = 3, 4, "foo"
Constants: Constants are treated just like regular variables except that their values
cannot be modified after their definition. Example: const LENGTH int = 10
Operators: An operator is a symbol that tells the compiler to perform specific
mathematical or logical manipulations. Go language is rich in built-in operators
and provides the following types of operators:
o Arithmetic Operators: +, -, *, /, %, ++, --
o Relational Operators: ==, !=, >, <, >=, <=,
o Logical Operators: &&, ||, !
o Bitwise Operators: &, |, ^, <<, >>
o Assignment Operators: =, +=, -=, *=, /=, %=, <<=, >>=, &=, |=, ^=1
o Miscellaneous Operators:
&: return address
*: return pointer
Array:
package main
import "fmt"
func main() {
var theArray [3]string
theArray[0] = "India"
theArray[1] = "Canada"
theArray[2] = "Japan"
fmt.Println(theArray)CONFIDENTIAL
Slice: Slices looks like array in golang but it is a bit flexible and powerful than array.
Array is fixed but slice is variable. Slices can be resized using the built-in append
function.
var theArray [3]string // Array
var theArray []string // Slice
var intSlice = make([]int, 10) // Slice
Slice example:
package main
import (
"fmt"
"reflect"
)
func main() {
var intSlice = make([]int, 10) // when length and
capacity is same
var strSlice = make([]string, 10, 20) // when length and
capacity is different
fmt.Printf("intSlice \tLen: %v \tCap: %v\n", len(intSlice),
cap(intSlice))
fmt.Println(reflect.ValueOf(intSlice).Kind())
fmt.Printf("strSlice \tLen: %v \tCap: %v\n", len(strSlice),
cap(strSlice))
fmt.Println(reflect.ValueOf(strSlice).Kind())
}
Length is the current number of element and capacity is the number of elements a slice
can store. CONFIDENTIAL
Map: A map is a data structure that provides you with an unordered collection of
key/value pairs (maps are also sometimes called associative arrays in Php, hash tables in
Java, or dictionaries in Python). Maps are used to look up a value by its associated key.
You store values into the map based on a key.
package main
import "fmt"
func main() {
var employee = make(map[string]int)
employee["Mark"] = 10
employee["Sandy"] = 20
fmt.Println(employee)
employeeList := make(map[string]int)
employeeList["Mark"] = 10
employeeList["Sandy"] = 20
fmt.Println(employeeList)
}
Structs: Structs are the only way to create concrete user-defined types in Golang. Struct
types are declared by composing a fixed set of unique fields. Structs can improve
modularity and allow to create and pass complex data structures around the system.
You can also consider Structs as a template for creating a data record, like an employee
record or an e-commerce product.
Struct with primitive data type:
package main
import "fmt"
type rectangle struct {
length float64
breadth float64
color string CONFIDENTIAL
}
func main() {
fmt.Println(rectangle{10.5, 25.10, "red"})
}
JSON struct, marshal and unmarshal: We can create a struct for JSON data. The JSON
data can be encoded and decoded with a defined struct in the following way.
package main
import (
"fmt"
"encoding/json"
)
type Employee struct {
FirstName string `json:"firstname"`
LastName string `json:"lastname"`
City string `json:"city"`
}
func main() {
json_string := ` {
"firstname": "Rocky", "lastname":
"Sting", "city": "London" }`
emp1 := new(Employee)
json.Unmarshal([]byte(json_string), emp1)
fmt.Println(emp1.FirstName, emp1.LastName, emp1.City)
emp2 := new(Employee)
emp2.FirstName = "Ramesh"
emp2.LastName = "Soni"
emp2.City = "Mumbai"
jsonStr, _ := json.Marshal(emp2)
CONFIDENTIAL
fmt.Printf("%s\n", jsonStr)
}
Decision making:
Decision making with if, else and else if:
package main
import ("fmt")
func main() {
x := 100
if x == 50 {
fmt.Println("Germany")
} else if x == 100 {
fmt.Println("Japan")
} else {
fmt.Println("Canada")
}
}
Decision making with switch and case:
package main
import (
"fmt"
"time"
)
func main() {
switch today := time.Now(); {
case today.Day() < 5:
fmt.Println("Clean your house.")
case today.Day() <= 10:
fmt.Println("Buy some wine.")
case today.Day() > 15:
CONFIDENTIAL
fmt.Println("Visit a doctor.")
case today.Day() == 25:
fmt.Println("Buy some food.")
default:
fmt.Println("No information available for that day.")
}
}
Loop:
package main
import "fmt"
func main() {
for k := 1; k <= 10; k++ {
fmt.Println(k)
}
k = 1
for k <= 10 {
fmt.Println(k)
k++
}
for k := 1; ; k++ {
fmt.Println(k)
if k == 10 {
break
}
}
}
Range:
package main
import "fmt" CONFIDENTIAL
func main() {
// Example 1
strDict := map[string]string{"Japan": "Tokyo", "China":
"Beijing", "Canada": "Ottawa"}
for index, element := range strDict {
fmt.Println("Index :", index, " Element :", element)
}
// Example 2
for key := range strDict {
fmt.Println(key)
}
// Example 3
for _, value := range strDict {
fmt.Println(value)
}
}
Function: func keyword has been used to declare a function in golang. We can return
multiple variable from a function in golang.
package main
import "fmt"
// SimpleFunction prints a message
func SimpleFunction() {
fmt.Println("Hello World")
}
func main() {
SimpleFunction()
}
Scope: In golang a variable declared inside main function is a local variable, outside of
main is a global variable and a variable/function outside of main with capital character
can be accessed from any other package.
package main
CONFIDENTIAL
import "fmt"
package main
import (
"fmt"
"time"
)
func main() {
go concurrentFunc("First process")
go concurrentFunc("Second process")
go concurrentFunc("Third process")
time.Sleep(1 * time.Second) // to wait
main function
}
Example:
package main
import (
"fmt"
)
func main() {
data := make(chan string)
go concurrentFunc("First process", data)
message := <-data
fmt.Println(message)
}
Type casting:
Structure (convert string to int): intVar, err := strconv.Atoi(strVar)
More details: https://www.golangprograms.com/go-language/integer-float-string-
boolean.html
Error handling: Go programming provides a pretty simple error handling framework with
inbuilt error interface type
result, err:= Sqrt(-1)
if err != nil {
fmt.Println(err)
}
HTTP request: CONFIDENTIAL
Get request:
package main
import (
"io/ioutil"
"log"
"net/http"
)
func main() {
resp, err :=
http.Get("https://jsonplaceholder.typicode.com/posts")
if err != nil {
log.Fatalln(err)
}
//We Read the response body on the line below.
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Fatalln(err)
}
//Convert the body to type string
sb := string(body)
log.Printf(sb)
}
POST Request:
package main
import (
"bytes"
"encoding/json"
"io/ioutil"
"log"
"net/http"
)
func main() {
//Encode the data
postBody, _ := json.Marshal(map[string]string{
"name": "Toby",
"email": "[email protected]",
})
responseBody := bytes.NewBuffer(postBody)
//Leverage Go's HTTP Post function to make request
resp, err := http.Post("https://postman-echo.com/post",
"application/json", responseBody)
//Handle Error
if err != nil { CONFIDENTIAL
log.Fatalf("An Error Occured %v", err)
}
defer resp.Body.Close()
//Read the response body
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Fatalln(err)
}
sb := string(body)
log.Printf(sb)
}
Golang Assignment
Develop a REST API with POST request for user registration with following fields: First
Name, Last Name, Email, Phone, Password, Date of birth
o Use PostgreSQL to store those data
o Use appropriate data type
o Store password hash instead of direct string
o Implement appropriate form validation
o API should return JSON including success with user id or error with message
Develop a REST API with POST request to upload user image with following fields: image
and user id
Implement a login API with Email and Password with GET request.
All the API should work under separate goroutine
Web Frameworks
Beego is a RESTful HTTP framework for the rapid development of Go applications including
APIs, web apps and backend services with integrated Go specific features such as interfaces and
struct embedding.
Beego architecture:
CONFIDENTIAL
File structure:
Develop a homepage with a banner and three horizontal sections: Popular, Trending
and TV series. Each item should show horizontal list of movie images and title receives
from API.
Implement movie details page with movie image, title, star rating, details and play
trailer feature
Develop a REST API in Golang to store favorite movies in DB
Implement API to add movies into favorite list
Show list of favorite movies in a newCONFIDENTIAL
page
Cloud Infrastructure
Deployment tools and techniques
Course Brief Time: 4 hours
Cloud Infrastructure
The collection of hardware and software elements needed to enable cloud computing. It
includes computing power, networking, and storage, as well as an interface for users to access
their virtualized resources, without direct active management by the user.
Cloud computing has created the opportunity for organizations to access the data storage and
computing capabilities that they require, on an as-needed basis and with a significantly reduced
up-front cost, instead of establishing their own on-premise IT infrastructure. Some of the top
cloud service providers
VPC
A virtual private cloud (VPC) is a virtual network dedicated to one AWS account. It’s logically
isolated from other virtual networks in AWS. One can lunch AWS resources under the VPC he
has. Under VPC you will get other related service like Subnet, Route Tables, Internet Gateways,
Elastic IPs, Network ACLs, Security Groups etc.
S3
Simple Storage Service - This is an object Storage Service, provides data availability, stability,
security and performance. Durability 99.999999999 % (11 9’s) and grows automatically with
your needs, pay as you use policy. Keeps copy of data on multiple devices on multiple zones.
The total volume of data and number of objects you can store are unlimited. Individual Amazon
S3 objects can range 0 bytes to 5TB.
Types: (Provides configurable life cycle policy)
Ø S3 Standard
Ø S3 Intelligent-Tiering
Ø S3 IA (Infrequent Access)
Ø S3 One Zone-IA
Ø Amazon Glacier
Ø S3 Glacier Deep Archive
CloudFront
CDN service that securely delivers data, videos, application, and APIs to customers globally with
low latency, high transfer speeds. CloudFront is directly connected with all AWS services /
Global infrastructure. Works as a caching server near you.
Currently AWS has a Global network of 230+ Points of Presence – 218 Edge Location & 12
Regional Edge Caches.
Some benefit:
CONFIDENTIAL
RDS
Amazon Relational Database Service (Amazon RDS), a managed service which makes it easy to
set up, operate, and scale a relational database in the cloud. It reduces administration tasks
such as hardware provisioning, database setup, patching and backups. It frees you to focus on
your applications so you can give them the fast performance, high availability, security and
compatibility they need. Aws RDS provides you with six familiar database engines to choose
from.
o Amazon Aurora
o PostgreSQL
o MySQL,
o MariaDB
o Oracle Database
o SQL Server
NoSQL
NoSQL databases (aka "not only SQL") are non-tabular, and store data differently than
relational tables.
NoSQL database have the following facilities:
Flexibility: NoSQL databases generally provide flexible schemas that enable faster and
more iterative development. The flexible data model makes NoSQL databases ideal for
semi-structured and unstructured data.
Scalability: NoSQL databases are generally designed to scale out by using distributed
clusters of hardware instead of scaling up by adding expensive and robust servers. Some
cloud providers handle these operations behind-the-scenes as a fully managed service.
High-performance: NoSQL database are optimized for specific data models and access
patterns that enable higher performance than trying to accomplish similar functionality
with relational databases.
Highly functional: NoSQL databases provide highly functional APIs and data types that
CONFIDENTIAL
are purpose built for each of their respective data models.
AWS provides different types of NoSQL database.
Route53
AWS Route 53: is a scalable & highly available Domain Name System (DNS) web service. Its
easily routes traffic to all its pointed services as well as route users to infrastructure outside of
AWS.
Key Features:
• Domain Registration
• Resolver
• Traffic flow
• Latency based routing
• DNS Failover
• Health checks and monitoring
• ELB, S3 integration
SQS
Simple Queue Service
A fully managed message queuing service that enables you to decouple and scale microservices,
distributed systems, and serverless applications.
With SQS one can send, store, and receive messages between software components at any
volume, without losing messages or requiring other services to be available.
Queue Types:
Ø Standard queue.
Ø FIFO
Elastic Beanstalk
Elastic Beanstalk, one can quickly deploy and manage applications in the AWS Cloud without
having to learn about the infrastructure that runs those applications. Elastic Beanstalk reduces
management complexity without restricting choice or control. You simply upload your
CONFIDENTIAL
application, and Elastic Beanstalk automatically handles the details of capacity provisioning,
load balancing, scaling, and application health monitoring. Elastic Beanstalk supports
applications developed in Go, Docker, Java, .NET, Node.js, PHP, Python, and Ruby.
Elasticsearch
Elasticsearch is an open-source, RESTful, distributed search and analytic engine built on Apache
Lucene.
Elasticsearch usages a data structure called an inverted index, which is allows to allow very fast
full-text search. An inverted index lists every unique world that appears in any documents all of
the documents each word occurs in.
Known as ELK (Elasticsearch, Logstash, Kibana).
Why use Elasticsearch?
Ø Elasticsearch is free
Ø Elasticsearch is fast
Ø Elasticsearch is distributed by nature
o Elasticsearch comes with a wide set of features
The Elastic Stack simplifies data ingest, visualization, and reporting.
Elasticsearch used for.
Application search
Website search
Logging and log analytics
Geospatial data analysis and visualization
Security analytics
Business analytics
Lambda
AWS Lambda is a serverless computing service provided by Amazon Web Services (AWS).
Lambda lets you run code without provisioning or managing servers. Lambda runs your code on
a high-availability compute infrastructure and performs all of the administration of the
compute resources, including server and operating system maintenance, capacity provisioning
and automatic scaling, code monitoring and logging.
AWS Lambda natively supports Java, Go, PowerShell, Node.js, C#, Python, and Ruby code, and
provides a Runtime API which allows you to use any additional programming languages to
author your functions.
CONFIDENTIAL
CloudFormation
CloudFormation - Infrastructure as Code, is a service that gives an easy way to create a
collection of related AWS and third-party resources, and provision and manage them in an
orderly and predictable fashion. You can create templates using YAML or JSON for the service
or application architectures you want and have, AWS CloudFormation use those templates for
quick and reliable provisioning of the services or applications (called “stacks”). You can also
easily update or replicate the stacks as needed.
Linux (OS)
Linux is a Unix-like, open source and community-developed operating system. An operating
system is the software that directly manages a system’s hardware and resources, like CPU,
memory, and storage. Some popular Linux distribution
Ubuntu
Fedora
CentOS
Linux Mint Cinnamon
Debian GNU/Linux
Linux terminal is the place where one will run commands. Some basic commands to learn:
Docker
Docker is a software platform that allows you to build, test, and deploy applications quickly, it’s
use OS-level virtualization to deliver software in packages called containers & they are isolated
from one another and bundle their own software, libraries and configuration files; they can
communicate with each other through well-defined channels. The software that hosts the
containers is called Docker Engine.
Some basic docker command:
# Pull an image from a registry
docker pull myimage:1.0
# Re-tag a local image with a new image name and tag
docker tag myimage:1.0 myrepo/myimage:2.0
# Push an image to a registry
docker push myrepo/myimage:2.0
# Build an image from the Dockerfile in the current directory and tag the image
docker build -t myimage:version .
# List all images that are locally stored with the Docker Engine
docker image ls
# Delete an image from the local image store
docker image rm alpine:3.4
# Run a container from the Alpine version 3.9 image, name the running container “web” and
expose port #5000 externally, mapped to port 80 inside the container.
docker container run --name web -p 5000:80 alpine:3.9
# Stop a running container
docker container stop web
# List only active containers
docker ps
# List all containers
docker ps -a
# Stop a container
docker stop [container-name|container-id]
# List the networks
CONFIDENTIAL
docker network ls
# List the running containers (add --all to include stopped containers)
docker containerName/ID ls
# Delete all running and stopped containers
docker container rm -f $(docker ps -aq)
# Print the last 100 lines of a container’s logs
docker container logs --tail 100 containerName/ID
# Print the container’s logs (use -f to follow)
docker container logs containerName/ID
Docker Compose
Docker Compose is a tool for running multi-container applications on Docker defined using the
Compose file format. A Compose file is written using YAML, which used to define how the one
or more containers that make up your application are configured. Once you have a Compose
file, you can create and start your application with a single command: docker-compose up.
Compose is basically a three-step process:
Define your app’s environment with a Dockerfile so it can be reproduced anywhere.
Define the services that make up your app in docker-compose.yml so they can be run
together in an isolated environment.
Run docker-compose up, which bring your app to live.
Below is an example of docker-compose file.
version: '3'
services:
web:
image: nginx
db:
image: mysql
ports:
- "3306:3306"
environment:
- MYSQL_ROOT_PASSWORD=password
- MYSQL_USER=user
- MYSQL_PASSWORD=password
- MYSQL_DATABASE=demodb
GIT
Open-Source Distributed Version Control System, is a tool used for source code management,
able to tracking changes in any set of files, used for coordinating work among programmers for
collaboratively developing source code during software development.
Some git command that we use very frequently: CONFIDENTIAL
## Clone a project
git clone [URL]
## Pull a branch
git pull
## downloads commit, files, and refs from a remote repository into your local repo.
git fetch
## lists all the files that have to be committed
git status
## list the version history for the current branch
git log
## list branch
git branch
## check all remote branch
git branch -a
## to create a new branch
git branch branchName
## to delete a branch
git branch -d branchName
## switch from one branch to another.
git checkout branchName
## Create a new branch and switch to it.
git checkout -b branchName
## push your update to remote
git add .
git commit -m "messages"
git push
## push a new local branch to remote
git push -u origin branchName
## merge a branch
git merge branchName
## diff of what is changed but not staged
git diff
## diff of what is staged but not yet committed
git diff --staged
IDE
An integrated Development environment (IDE) is software for building applications that
combines common developer tools into a single graphical user interface (GUI). Typically consists
of:
CONFIDENTIAL
Source code editor
Local build automation
Debugger
IDE popularity depends on:
Ansible CONFIDENTIAL
Terraform
Can deploy apps on the top of infrastructure. Can deploy Load balancers, VPCs, etc.
With Ansible, you need to dictate each step Terraform can carry out all steps to present
to achieve the end result. the final output, once given the end
instruction.