0% found this document useful (0 votes)
51 views

FastAPI Slides

Uploaded by

Hợp Đức
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
51 views

FastAPI Slides

Uploaded by

Hợp Đức
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 332

Installing Python

Is Python 3 Installed?

• Inside your “terminal” for Mac, or “command prompt” for windows.

• Type “python3 --version” for Mac or “python --version” for windows

ericroby@Erics-MacBook-Pro ~% python3 --version

Python 3.11.2

Could be a different version for you, requirement for FastAPI is version 3.7

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
Python Integrated Development Environment
WHAT IS AN INTEGRATED
DEVELOPMENT ENVIRONMENT

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
What is an IDE?

• IDEs are simply a source code editor. This means an IDE will help and
assist in writing software!

• Many of them have terminals and other useful build automation tools
embedded within.

• IDEs have debugger tools that allow you to dive deep within the code
to nd bugs and create solutions

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
fi
Why do developers use IDEs?

• IDEs allow developers to begin work quickly and ef ciently due to all
the tools that come out of the box

• IDEs also parse all code, and helps nd bugs before they are committed
by human error

• The GUIs of IDEs is created with one goal in mind, help developers be
ef cient.

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
fi
fi
fi
Python Integrated Development Environment
WHAT IS AN INTEGRATED
DEVELOPMENT ENVIRONMENT

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
What is an IDE?

• IDEs are simply a source code editor. This means an IDE will help and
assist in writing software!

• Many of them have terminals and other useful build automation tools
embedded within.

• IDEs have debugger tools that allow you to dive deep within the code
to nd bugs and create solutions

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
fi
Why do developers use IDEs?

• IDEs allow developers to begin work quickly and ef ciently due to all
the tools that come out of the box

• IDEs also parse all code, and helps nd bugs before they are committed
by human error

• The GUIs of IDEs is created with one goal in mind, help developers be
ef cient.

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
fi
fi
fi
Python Virtual Environments
Python Virtual Environments

• A virtual environment is a Python environment that is isolated from


those in other Python environments.

FastAPI A.I. Internet of Things

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
How to Install Dependencies
• Pip is the Python package manager.

• Pip is used to install and update packages.

• You will want to make sure you have the latest version of pip
installed.

ericroby@Erics-MacBook-Pro ~% python3 -m pip --version

pip 22.3.1

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
Setting Up Virtual Environment
• I started by creating a brand-new folder / directory called “FastAPI”

• Within our pip we will be checking what dependencies we already


have installed.

• Python already has an included dependency for virtual environments


called venv.

• Creating a new FastAPI environment as a virtual environment

• Activating our virtual environment to install our dependencies in

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
How To Get The Most
Out Of This Course
How To Get The Most Out Of This Course
Control the speed of videos to be
Watch all the videos
your pace

Pause videos to take exercises before


Take the exercises
seeing solutions

Advance on your own and search for


Search & Practice
additional information

Ask Questions Ask in Q&A section!

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
Course Content
Course Content!
Introduction

Python Refresher Project 2 Database & ORM

Classes, Handling
Project 1 Authentication JWT
errors

Get/Post/Put/Delete
Project 3 Routing
and more!

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
Course Content!

Unit & Integration


Project 3.5 Git / GitHub Setup
Testing

DB & Data Migration Project 5 Deployment

Full Stack
Project 4
Development

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
FASTAPI OVERVIEW

LET’S CODE TOGETHER © CODINGWITHROBY


WHAT IS FASTAPI?

FastAPI is a Python web-framework for building modern


APIs
Fast (Performance)
Fast (Development)
Key Notes:
Few Bugs
Quick & Easy
Robust
Standards

LET’S CODE TOGETHER © CODINGWITHROBY


WHAT DOES THIS ALL MEAN FOR YOU?

FastAPI is a web-framework for building modern RESTful APIs

Official
documentation

https://fastapi.tiangolo.com/

LET’S CODE TOGETHER © CODINGWITHROBY


WHERE DOES FASTAPI FIT WITHIN AN APPLICATION ARCHITECTURE?

Full
RestStack Application
API for data
Web Page Server

Handles all business logic for the application

LET’S CODE TOGETHER © CODINGWITHROBY


WHO HAS USED FASTAPI?

Netflix Uber Microsoft

LET’S CODE TOGETHER © CODINGWITHROBY


CAN’T I JUST WRITE EVERYTHING MYSELF?

FAQ: Why do I need a web framework?


You may be able to write everything yourself, but why reinvent
the wheel?
Web-frameworks allow a simplified way for rapid
development.
Includes many years of development, which allows you to
have a secure and fast application! ☺

LET’S CODE TOGETHER © CODINGWITHROBY


Books Project
What will we be creating?

• Creating and enhancing books to learn the basics of FastAPI


BOOKS = {
{‘title’: ‘Title One’, ‘author’: ‘Author One’, ‘category’: ‘science’},
{‘title’: ‘Title Two’, ‘author’: ‘Author Two’, ‘category’: ‘science’},
{‘title’: ‘Title Three’, ‘author’: ‘Author Three’, ‘category’:
‘history’},
{‘title’: ‘Title Four’, ‘author’: ‘Author Four’, ‘category’: ‘math’},
{‘title’: ‘Title Five’, ‘author’: ‘Author Five’, ‘category’: ‘math’},

CRUD Operations
Create Read Update Delete

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
Request and Response

HTTP Request Methods

Web Page Server

Response

CRUD Operations

Create Read Update Delete

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
HTTP Request Methods
CRUD HTTP Request Methods

Create POST

Read GET

Update PUT

Delete DELETE

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
GET HTTP Request Method
Creating a FastAPI application
File: books.py

from fastapi import FastAPI

app = FastAPI()

@app.get(“/api-endpoint”)
async def first_api():
return {‘message’: ‘Hello Eric!’}

Lets dive into the first function

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
Dive in
API Endpoint:

@app.get(“/api-endpoint”)
async def first_api():
return {‘message’: ‘Hello Eric!’}
Read

Get URL : 127.0.0.1:8000/api-endpoint


Response:
{
“message”: “Hello Eric!”
}

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
Start FastAPI Application
API Endpoint:

@app.get(“/api-endpoint”)
async def first_api():
Read return {‘message’: ‘Hello Eric!’}

Get Run FastAPI application:


ericroby@Erics-MacBook-Pro ~% uvicorn books:app --reload

URL : 127.0.0.1:8000

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
Change Endpoint for Books

Read @app.get(“/api-endpoint”)
@app.get(“/books”)
async
async def
def read_all_books():
read_all_books():
return
return BOOKS
BOOKS

Get

URL :URL
127.0.0.1:8000/api-endpoint
: 127.0.0.1:8000/books

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
Path Parameters
What are Path Parameters

• Path Parameters are request parameters that have been attached to the
URL

• Path Parameters are usually de ned as a way to nd information based


on location

• Think of a computer le system:

• You can identify the speci c resources based on the le you are in

/Users/codingwithroby/Documents/python/fastapi/section1

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
fi
fi
fi
fi
fi
Path Parameters
REQUEST:
URL : 127.0.0.1:8000/books
Read
@app.get(“/books”)
async def read_all_books():
return BOOKS
Get

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
Path Parameters
REQUEST:
URL : 127.0.0.1:8000/books/book_one
Read
@app.get(“/books /{dynamic_param}”)
async def read_all_books(dynamic_param):
return {‘dynamic_param’: dynamic_param}

Get

RESPONSE:
{
“dynamic_param”: “book_one”
}

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
Order Matters with Path Parameters
REQUEST:
URL : 127.0.0.1:8000/books/mybook
Read
@app.get(“/books/mybook”)
@app.get(“/books/{dynamic_param}”)
async def read_all_books():
read_all_books(dynamic_param):
return {‘book_title’:
{‘dynamic_param’:
’Mydynamic_param}
Favorite Book’}

Get @app.get(“/books/{dynamic_param}”)
@app.get(“/books/mybook”)
async def read_all_books(dynamic_param):
read_all_books():
return {‘dynamic_param’:
{‘book_title’: ’Mydynamic_param}
Favorite Book’}

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
Path Parameters
Read
REQUEST:
URL : 127.0.0.1:8000/books/title%20four = title four

Get
@app.get(“/books/{book_title}”)
async def read_book(book_title: str):
for book in BOOKS:
if book.get(‘title’).casefold() ==
book_title.casefold():

RESPONSE:
{
“title”: “Title Four”,
“author”: “Author Four”,
“category”: “math”
}

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
Query Parameters
What are Query Parameters

• Query Parameters are request parameters that have been attached after
a “?”

• Query Parameters have name=value pairs

• Example:

• 127.0.0.1:8000/books/?category=math

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
Query Parameters
REQUEST:
URL : 127.0.0.1:8000/books/?category=science

@app.get(“/books/”)
async def read_category_by_query(category: str):
books_to_return = []
for book in BOOKS:
if book.get(‘category’).casefold() == category.casefold():
books_to_return.append(book)

return books_to_return

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
Query Parameters
REQUEST:
URL : 127.0.0.1:8000/books/author%20four/?category=science

@app.get(“/books/{book_author}/”)
async def read_category_by_query(book_author: str, category: str):
books_to_return = []
for book in BOOKS:
if book.get(‘author’).casefold() == book_author.casefold() and
book.get(‘category’).casefold() == category.casefold():
books_to_return.append(book)

return books_to_return

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
POST HTTP Request Method
What is the POST Request Method

• Used to create data

• POST can have a body that has additional information that GET does
not have

• Example of Body:

{“title”:”Title Seven”, “author”:”Author Two”, “category”:

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
POST Request Method
REQUEST:
URL : 127.0.0.1:8000/books/create_book
Create
@app.post(“/books/create_book”)
async def create_book(new_book=Body()):
BOOKS.append(new_book)
Post

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
PUT HTTP Request Method
What is the PUT Request Method

• Used to update data

• PUT can have a body that has additional information (like POST) that
GET does not have

• Example of Body:

{“title”:”Title Six”, “author”:”Author Two”, “category”:

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
PUT Request Method
Update
REQUEST:
Put URL : 127.0.0.1:8000/books/update_book

@app.put(“/books/update_book”)
async def update_book(updated_book=Body()):
for i in range(len(BOOKS)):
if BOOKS[i].get(‘title’).casefold() == updated_book.get(‘title’).casefold():
BOOKS[i] = updated_book

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
DELETE HTTP Request Method
What is the DELETE Request Method
• Used to delete data

Delete

REQUEST:
Delete URL : 127.0.0.1:8000/books/delete_book/{book_title}

@app.delete(“/books/delete_book/{book_title}”)
async def delete_book(book_title: str):
for i in range(len(BOOKS)):
if BOOKS[i].get(‘title’).casefold() == book_title.casefold():
BOOKS.pop(i)
break

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
Books 2 Project
Project 2

• Project two will still be focused on creating Book API Endpoints

• Continued Education includes:

• GET, POST, PUT, DELETE Request Methods

• New Information will include:

• Data Validation, Exception Handling, Status Codes, Swagger


Con guration, Python Request Objects

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
fi
Creating a new books project
• We will create a new class called Book

• We will be using these books throughout this


project:
class Book:
id: int
title: str
author: str
description: str
rating: int

def __init__ (self, id, title, author, description, rating):


self.id = id
self.title = title
self.author = author
self.description = description
self.rating = rating

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
HTTP Request Methods
CRUD HTTP Request Methods

Create POST

Read GET

Update PUT

Delete DELETE

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
Pydantics
What is Pydantics

• Python library that is used for data modeling, data parsing and has
ef cient error handling.

• Pydantics is commonly used as a resource for data validation and how to


handle data coming to our FastAPI application.

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
fi
We will be implementing Pydantics
• Create a different request model for data validation

• Field data validation on each variable / element

class BookRequest(BaseModel):
id: int
title: str = Field(min_length=3)
author: str = Field(min_length=1)
description: str = Field(min_length=1, max_length=100)
rating: int = Field(gt=0, lt=5)

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
BookRequest and Book Conversion
• We will convert the Pydantics Request into a Book

• Here is an example within an upcoming Post Request Method

@app.post(“/create-book”)
async def create_book(book_request: BookRequest):
new_book = Book(**book_request.dict())
BOOKS.append(new_book)

** operator will pass the key/value from BookRequest() into the Book() constructor

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
Status Codes
What are Status Codes?

• An HTTP Status Code is used to help the Client (the user or system
submitting data to the server) to understand what happened on the
server side application.

• Status Codes are international standards on how a Client/Server should


handle the result of a request.

• It allows everyone who sends a request to know if their submission was


successful or not.

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
Status Codes:
1xx Information Response: Request Processing.

2xx Success: Request Successfully complete

3xx Redirection: Further action must be complete

4xx Client Errors: An error was caused by the client.

5xx Server Errors: An error occurred on the server.

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
2xx Successful Status Codes:
Standard Response for a Successful Request. Commonly
200: OK used for successful Get requests when data is being
returned.

201: The request has been successful, creating a new resource.


Used when a POST creates an entity.

204: No The request has been successful, did not create an entity
nor return anything. Commonly used with PUT requests.

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
4xx Client Errors Status Codes:
400: Bad Cannot process request due to client error. Commonly used
for invalid request methods.

Client does not have valid authentication for target


401: Unauthorized
resource

404: Not The clients requested resource can not be found

422: Unprocessable Semantic Errors in Client Request


Entity

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
5xx Server Status Codes:

Generic Error Message, when an unexpected issue on the


500: Internal Server
server happened.
Error

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
Project 3
Project 3

• Project three we will be switching our focus to TODOS instead of BOOKS

• New Information will include:

• Full SQL Database

• Authentication Continued learning from


• Authorization other projects

• Hashing Passwords

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
Creating a Todo Table
• We will create new Todo Table Models for our application

• We will be using these Todos to save records throughout this project

Authorization & Authentication Retrieving the user and saving Todos

Database

Web Page Server

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
SQL Database Introduction
What is a database?
• Organized collection of structured information of data, which is stored in
a computer system.

• The data can be easily accessed

• The data can be modi ed


What is Data?
• The data can be controlled and organized

• Many databases use a structured query language (SQL) to modify and


write data

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
fi
What is a database?
• Data can be related to just about any object.

• For example, a user on an application may have:

• Name

• Age

• Email
All of this is Data
• Password

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
What is a database?
• A database is a collection of data

• Since data, on its own, is just data. A database allows management of this
data

• Databases are organized in how data can be retrieved, stored and


modi ed

• There are many types of Database Management Systems (DBMS)

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
fi
What is a SQL?
• Pronounced either as S-Q-L or “See Quel”

• Standard language for dealing with relational databases

• SQL can be used to do different things with database records:

• Create

• Read

• Update

• Delete

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
What is Alembic?
What is Alembic?
• Lightweight database migration tool for when using SQLAlchemy

• Migration tools allow us to plan, transfer and upgrade resources within


databases

• Alembic allows you to change a SQLAlchemy database table after it has


been created

• Currently SQLAlchemy will only create new database tables for us, not
enhance any.

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
How does Alembic work?
• Alembic provides the creation and invocation of change management
scripts

• This allows you to be able to create migration environments and be able


to change data how you like

• In this section we will learn how we can use Alembic for our project

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
How does Alembic work?
• We already have some data within our database

• Let’s take a look at our current users table

• Create a new column on our data that already exists

ID email first_name …… phone_number

1 codingwithroby@e Eric <Other Columns> (1) 111-111-1111


mail.com

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
How does Alembic work?
• Alembic is a powerful migration tool that allows us to modify our
database schemes

• As our application evolves, our database will need to evolve as well

• Alembic helps us be able to keep modifying our database to keep up with


rapid development requirements

• It works on tables that already have data. This allows us to be able to


continually create additional content that works within our application!

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
Alembic?
What is Alembic?
• Lightweight database migration tool for when using SQLAlchemy

• We need to install Alembic into our project

ericroby@FastAPI-Project ~% pip install alembic

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
What is Alembic?
Alembic Command Details

alembic init <folder name> Initializes a new, generic environment

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
What is Alembic?
Alembic Command Details

alembic init <folder name> Initializes a new, generic environment

Creates a new revision of the


alembic revision -m <message>
environment

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
What is Alembic?
Alembic Command Details

alembic init <folder name> Initializes a new, generic environment

Creates a new revision of the


alembic revision -m <message>
environment

Run our upgrade migration to our


alembic upgrade <revision #>
database

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
What is Alembic?
Alembic Command Details

alembic init <folder name> Initializes a new, generic environment

Creates a new revision of the


alembic revision -m <message>
environment

Run our upgrade migration to our


alembic upgrade <revision #>
database
Run our downgrade migration to our
alembic downgrade -1
database

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
How does Alembic work?
• After we initialize our project with alembic, two new items will appear in
our directory

• alembic.ini

• alembic directory

• These are created automatically by alembic so we can upgrade,


downgrade and keep data integrity of our application

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
Alembic.ini file
• File that alembic looks for when invoked

• Contains a bunch of con guration information for Alembic that we are


able to change to match our project

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
fi
Alembic Directory
• Has all environmental properties for alembic

• Holds all revisions of your application

• Where you can call the migrations for upgrading

• Where you can call the migrations for downgrading

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
Alembic Revisions
Alembic Revision?
• Alembic revision is how we create a new alembic le where we can add
some type of database upgrade

• When we run:

ericroby@FastAPI-Project ~%
alembic revision -m “create phone number col on users table”

• Creates a new le where we can write the upgrade code

• Each new revision will have a Revision Id

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
fi
fi
Alembic Upgrade?
• Alembic upgrade is how we actually run the migration

def upgrade() -> None:


op.add_column(‘users’, sa.Column(‘phone_number’, sa.String(),
nullable=True))

• Enhances our database to now have a new column within our users
tables called ‘phone_number’

• Previous data within database does not change

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
Alembic Upgrade?
• To run the the upgrade migration:

ericroby@FastAPI-Project ~%
alembic upgrade <revision id>

• This will successfully implement the change within the upgrade


functionality

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
Alembic Downgrade?
• Alembic downgrade is how we revert a migration

def downgrade() -> None:


op.drop_column(‘users’, ‘phone_number’)

• Reverts our database to remove the last migration change.

• Previous data within database does not change unless it was on the
column ‘phone_number’ because we deleted it.

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
Alembic Downgrade?
• To run the the downgrade migration:

ericroby@FastAPI-Project ~%
alembic downgrade -1

• Will revert the last migration

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
FastAPI Testing
What is Testing
• It is a way for us to make sure our application is working as intended.

• Part of the Software Development Lifecycle (SDLC) that aims to identify:

• Bugs

• Errors

• Defects

• Meets user requirements and speci cations.

• Ensuring Software is high quality, reliable, secure and user friendly.

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
fi
What is Testing

Manual Testing Unit Testing Integration Testing

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
Unit Testing
• Involves testing individual components or units of software in isolation
from the rest of the application.

• Validates that each unit of the software performs as designed.

• Unit = Testable part of the application.

• Developers write unit tests during the development phase.

• Tests are automated and executed by a testing framework (Pytest).

• Bene t is to identify bugs early in the development process.

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
fi
Integration Testing
• Focuses on testing the interactions between different units or components
of the piece of software.

• The scope is broader than unit testing, as we are testing multiple units
together.

• Helps identify problems for the entire solution.

• Example: Call an API endpoint and make sure the correct solution is
returned.

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
Pytest
• Popular testing framework for Python

• Known for simplicity, scalability and ability to handle both unit and
integration tests.

• Top reasons to use Pytest:

• Simple & Flexible - Native Assertions

• Fixtures - Feature setup and teardown

• Parameterized Testing - Run same tests with different data

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
What is Testing
Both

Manual Testing Unit Testing Integration Testing

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
Getting Started With Testing
First Step
• Create a new directory on our project call ‘test’.

• Inside our test directory create a new le called:

__init__.py

• Inside our test directory create a new le called:

test_example.py

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
fi
fi
test_example.py
• Pytest will run all tests automatically that sit within les that have the
name ‘test’ in them.

• For our demo, all tests will be in test_example.py so Pytest can nd them
easily.

• When we write tests for our application, we will create new tests from a
new le that matches naming convention of project.

• Example: todos.py will be tested by test_todos.py

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
fi
fi
fi
Create our first Unit Test
• Write our rst assertion test.

• Assertion = Statement that checks if a condition is true.

• If condition is true = test passes.

• If condition is false = test fails.


test_example.py:
Terminal:
def test_equal_or_not_equal():
assert 3 == 3 Test/test_example.py

============ 1 passed ============


Terminal:

ericroby@FastAPI-Project ~% pytest

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
fi
Create our first Unit Test
def test_equal_or_not_equal():
Pass
assert 3 == 3

def test_equal_or_not_equal():
Fail
assert 3 == 2

def test_equal_or_not_equal():
assert 3 != 1
Pass

def test_equal_or_not_equal():
assert 3 != 3
Fail

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
Pytest Basics
Pytest Basics
• Validate Integers

def test_equal_or_not_equal():
Pass
assert 3 == 3

• Validate Instances

def test_is_instance():
assert isInstance(‘this is a string’, str) Pass
assert not isInstance(‘10’, int)

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
Pytest Basics
• Validate Booleans

def test_boolean():
validated = True Pass
assert validated is True
assert (‘hello’ == ‘world’) is False

• Validate Types

def test_type():
assert type(‘Hello’ is str) Pass
assert type(‘World’ is not int)

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
Pytest Basics
• Validate Greater Than & Less Than

def test_greater_and_less_than():
assert 7 > 3 Pass
assert 4 < 10

• Validate Types
def test_list():
num_list = [1, 2, 3, 4, 5]
any_list = [False, False]
assert 1 in num_list Pass
assert 7 not in num_list
assert all(num_list)
assert not any(any_list)

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
Pytest Objects
Pytest Objects
• Create our Python Object

import pytest

class Student:
def __init__(self, first_name: str, last_name: str, major: str, years:
int):
self.first_name = first_name
self.last_name = last_name

def test_person_initialization():
p = Student(‘John’, ‘Doe’, ‘Computer Science’, 3)
assert p.first_name == ‘John’, ‘First name should be John’
assert p.last_name == ‘Doe’, ‘Last name should be Doe’
assert p.major == ‘Computer Science’
assert p.years == 3

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
Pytest Objects
• Create our Python Object

@pytest.fixture
def default_employee():
return Student(‘John’, ‘Doe’, ‘Computer Science’, 3)

def test_person_initialization():
test_person_initialization(default_employee):
p = Student(‘John’,
assert default_employee.first_name
‘Doe’, ‘Computer==Science’,
‘John’, ‘First
3) name should be John’
assert default_employee.last_name
p.first_name == ‘John’, ‘First
== ‘Doe’,
name should
‘Last name
be John’
should be Doe’
assert default_employee.major
p.last_name == ‘Doe’, ‘Last
== ‘Computer
name should
Science’
be Doe’
assert default_employee.years
p.major == ‘Computer Science’
== 3

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
Setup Test Dependencies & DB
Test Database
• Create a fake database that can store data.

• Create testing dependencies that are separate from our production


dependencies.

• This way we can do integration testing to make sure our entire project is
working correctly when we run our tests.

• App is live = production dependencies Separate shared


dependencies in a different
• App is testing = testing dependencies le later on.

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
fi
Testing dependencies
• Create a new le called:

test_todos.py todos.py

• Create new database engine for our testing environment

from sqlalchemy import create_engine

SQLALCHEMY_DATABASE_URL = “sqlite:///./testdb.db”

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
fi
Testing dependencies
• Add the new engine:
from sqlalchemy import create_engine
from sqlalchemy.pool import StaticPool

SQLALCHEMY_DATABASE_URL = “sqlite:///./testdb.db”
engine = create_engine(
SQLALCEMY_DATABASE_URL,
connect_args={“check_same_thread”: False},
Poolclass = StaticPool,
)

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
Testing dependencies
• Add TestingSessionLocal and Base
from sqlalchemy import create_engine
from sqlalchemy.pool import StaticPool
from ..database import Base

SQLALCHEMY_DATABASE_URL = “sqlite:///./testdb.db”
engine = create_engine(
SQLALCEMY_DATABASE_URL,
connect_args={“check_same_thread”: False},
Poolclass = StaticPool,
)
TestingSessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base.metadata.create_all() = bind=engine

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
Testing dependencies
• Setup get_testing_db dependency

def override_get_db():
db = TestingSessionLocal()
try:
yield db
finally:
db.close()

app.dependency_overrides[get_db] = override_get_db

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
Testing dependencies
• Mock our current logged in user for testing.

def override_get_db():
db = TestingSessionLocal()
try:
yield db
finally:
db.close()

def override_get_current_user():
return {‘username’: ‘codingwithroby’, ‘id’: 1, ‘user_role’: ‘admin’}

app.dependency_overrides[get_db] = override_get_db
app.dependency_overrides[get_current_user] = override_get_current_user

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
FastAPI
• Normal:
app = FastAPI()

• Wrap it in testing client:

client = TestClient(app)

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
JSON WEB TOKEN (JWT) OVERVIEW

FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
WHAT IS A JSON WEB TOKEN?

JSON Web Token is a self-contained way to securely


transmit data and information between two parties using a
JSON Object.
JSON Web Tokens can be trusted because each JWT can
be digitally signed, which in return allows the server to
know if the JWT has been changed at all
JWT should be used when dealing with authorization
JWT is a great way for information to be exchanged
between the server and client

FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
JSON WEB TOKEN STRUCTURE

A JSON Web Token is created of three separate parts separated


by dots ( . ) which include:
Header : (a)
Payload : (b)
Signature : (c)

FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
JWT HEADER

A JWT header usually consist of two


parts:
(alg) The algorithm for signing
“typ” The specific type of token
The JWT header is then encoded using
Base64 to create the first part of the JWT (a)

FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
JWT PAYLOAD

A JWT Payload consists of the data.


The Payloads data contains claims, and
there are three different types of claims.
Registered
Public
Private
The JWT Payload is then encoded using
Base64 to create the second part of the JWT
(b)

FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
JWT SIGNATURE

A JWT Signature is created by using the


algorithm in the header to hash out the
encoded header, encoded payload with a
secret.
The secret can be anything, but is saved
somewhere on the server that the client does
not have access to
The signature is the third and final part of a
JWT (c)

FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
JWT EXAMPLE

JWT Header JWT Payload JWT Signature

JSON Web Token

FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
https://jwt.io

FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
https://jwt.io

FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
JWT PRACTICAL USE CASE

78…
t h 5
y
e7a
App 1

e7a
yth
578

App 2

FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
PRODUCTION DATABASE INTRODUCTION

FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
PRODUCTION DATABASE

This section will go over installing a production


relational database for your application!
Before jumping in, lets take
The two DBMS applications we will be going over is
about
MySQL the difference between
and PostgreSQL.
Both DBMS systems are used widely through out
SQLite
enterprise andandproduction
applications, you cannot go wrongDBMS
with
either one

FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
PRODUCTION DBMS VS SQLITE3

SQLite3 strives to provide local data storage for


individual applications and devices.
SQLite3 emphasizes economy, efficiency and simplicity.
For most small / medium applications, SQLite3 will
works perfectly.
SQLite3 focuses on different concepts than a
production Database Management System.

FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
PRODUCTION DBMS VS SQLITE3

MySQL & PostgreSQL focuses on a big difference


compared to SQLite3.
These production DBMS focuses on scalability,
concurrency and control.
If you application is going to have 10s of thousands of
users, it may be wise to switch to a production DBMS
If you application is only you, and a few others, SQLite3
will work great!

FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
PRODUCTION DBMS KEY NOTES:

SQLite3 runs in-memory, which allows development of a


SQLite3 data to be easy, as it is part of your application!
Production DBMS run on their own server and port. Which
means you need to make sure the database is running, and
have authentication linking to the DBMS
(SQLite3) For deployment you can deploy a SQLite3 database
along with the application
(Prod DBMS) For deployment you will need to also deploy the
database separate from the application

FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
OVERVIEW OF SECTION (FOR BOTH MYSQL & POSTGRESQL)

We will install the production DBMS


Setup the tables and data within the production DBMS
Connect the production DBMS to our application
Push data from application to our production DBMS!

FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
BASIC SQL QUERIES

FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
INSERTING DATABASE TABLE (TODOS)

Id (PK) title description priority complete owner (FK)

FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
DELET THIS IS THE USERS TABLE
Id (PK) email username first_name last_name hashed_passwor is_active
d

FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
DELET THIS IS THE USERS TABLE
Id (PK) email username first_name last_name hashed_passwor is_active
d
1 codingwithroby codingwithroby Eric Roby 123abcEqw!.. 1
@gmail.com
2 exampleuser12 exampleuser Example User Gjjjd!2!.. 1
@example.com

FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
INSERTING DATABASE TABLE (TODOS)

INSERT INTO todos (title,


description, priority, complete)

VALUES (‘Go to store’, ‘To pick up


eggs’ 4, False);

Id (PK) title description priority complete

1 Go to store To pick up eggs 4 0

FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
INSERTING DATABASE TABLE (TODOS)

INSERT INTO todos (title,


description, priority, complete)

VALUES (‘Haircut’, ‘Need to get


length 1mm’ 3, False);

Id (PK) title description priority complete

1 Go to store To pick up eggs 4 0

2 Haircut Need to get length 3 0


1mm

FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
STARTING DATABASE TABLE (TODOS)

Id (PK) title description priority complete

1 Go to store To pick up eggs 4 0

2 Haircut Need to get length 3 0


1mm

FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
STARTING DATABASE TABLE (TODOS)

Id (PK) title description priority complete

1 Go to store To pick up eggs 4 0

2 Haircut Need to get length 3 0


1mm

3 Feed dog Make sure to use 5 0


new food brand

FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
STARTING DATABASE TABLE (TODOS)

Id (PK) title description priority complete

1 Go to store To pick up eggs 4 0

2 Haircut Need to get length 3 0


1mm

3 Feed dog Make sure to use 5 0


new food brand

4 Water plant Inside and Outside 4 0


plants

FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
STARTING DATABASE TABLE (TODOS)

Id (PK) title description priority complete

1 Go to store To pick up eggs 4 0

2 Haircut Need to get length 3 0


1mm

3 Feed dog Make sure to use 5 0


new food brand

4 Water plant Inside and Outside 4 0


plants

5 Learn something new Learn to program 5 0

FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
STARTING DATABASE TABLE (TODOS)

Id (PK) title description priority complete

1 Go to store To pick up eggs 4 0


2 Haircut Need to get length 3 0
1mm

3 Feed dog Make sure to use 5 0


new food brand

4 Water plant Inside and Outside 4 0


plants

5 Learn something new Learn to program 5 0

6 Shower You have not 5 0


showered in days

FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
DELETE

Id (PK) title description priority complete owner

3 Feed dog Make sure to use 5 0 2


new food brand
4 Water plant Inside and 4 0 2
Outside plants

6 Shower You have not 5 0 2


showered in days

FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
SELECT SQL QUERIES

SELECT * FROM todos;

Select ALL columns and rows

FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
SELECT SQL QUERIES

SELECT title FROM todos;

Select just title from columns

FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
SELECT SQL QUERIES

SELECT description FROM todos;

Select just description from columns

FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
SELECT SQL QUERIES

SELECT title, description FROM


todos;
Select title, description from columns

FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
SELECT SQL QUERIES

SELECT title, description, priority FROM


todos;
Select title, description and priority from columns

FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
WHERE SQL QUERIES

WHERE Clause

FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
WHERE SQL QUERIES

SELECT * FROM todos WHERE priority=5;

Select ALL rows & columns WHERE priority = 5

FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
WHERE SQL QUERIES

SELECT * FROM todos WHERE title=‘Feed dog’;

Select ALL rows & columns WHERE title= Feed dog

FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
WHERE SQL QUERIES

SELECT * FROM todos WHERE id=2;

Select ALL rows & columns WHERE id= 2

FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
UPDATE SQL QUERIES

UPDATE Clause

FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
WHERE SQL QUERIES

UPDATE todos SET complete=True WHERE


title=‘Learn something new’;

Update ALL rows & columns to now have complete = True


WHERE id = 5

1 == True
FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
WHERE SQL QUERIES

UPDATE todos SET complete=True WHERE id=5;

Update ALL rows & columns to now have complete = True


WHERE id = 5

1 == True
FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
DELETE SQL QUERIES

DELETE Clause

FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
DELETE SQL QUERIES

DELETE FROM todos WHERE id=5;

Delete ALL rows and columns where id =


5

FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
DELETE SQL QUERIES

DELETE FROM todos WHERE complete=0;

Delete ALL rows and columns where complete =


0

FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
ONE TO MANY INTRODUCTION

FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
WHAT IS A ONE TO MANY RELATIONSHIP

A user can have many todos

Todo

Todo
User
Todo

Todo

FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
WHAT IS A ONE TO MANY RELATIONSHIP

Users & Todos

FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
WHAT IS A ONE TO MANY RELATIONSHIP

Users & Todos


Id (PK) Id (PK)
email title
username description
first_name
last_name priority
hashed_password complete
is_active Owner (FK)

FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
WHAT IS A ONE TO MANY RELATIONSHIP
Add new
column

FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
WHAT IS A ONE TO MANY RELATIONSHIP

Users

Todos

FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
FOREIGN KEYS

FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
WHAT IS A FOREIGN KEY?

A foreign key (FK) is a column within a relational database table


that provides a link between two separate tables.
A foreign key references a primary key of another table
Most relational databases need foreign keys to be able to link
tables together to present data

FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
FOREIGN KEYS

SELECT * FROM todos;

Select ALL columns and rows

FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
FOREIGN KEYS

SELECT * FROM users;

Select ALL columns and rows

FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
Each API request a user will have their ID attached
If we have the user ID attached to each request, we can
use the ID to find their todos

FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
WHERE SQL QUERIES

SELECT * FROM todos WHERE owner=1;

Select ALL rows & columns WHERE owner = 1

FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
WHERE SQL QUERIES

SELECT * FROM todos WHERE owner=2;

Select ALL rows & columns WHERE owner = 1

FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
MYSQL INTRODUCTION

FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
WHAT IS MYSQL

Open-source relational database


management system
Requires a server
Production ready
Scalable
Secure

FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
WHO USES/USED MYSQL?

Facebook YouTube Tesla

FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
POSTGRESQL INTRODUCTION

FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
WHAT IS POSTGRESQL

Production ready
Open-source relational database
management system
Secure
Requires a server
Scalable

FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
WHAT WILL WE COVER?

How to install PostgreSQL


Windows
Mac
Setup SQL tables
Connect PostgreSQL to our
application

FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
WHO USES/USED POSTGRESQL?

Appl Reddit Twitch


e

FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
ROUTING INTRODUCTION

FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
WHAT IS ROUTING

Rare that you want your entire


application to be on a single file
Flexible tool to structure your
application
Scalable architecture
Organize file structure

FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
NEW PROJECT STRUCTURE
TodoApp

TodoApp/routers TodoApp/
main.py company (new)

auth.py companyapis.py
database.py

todos.py dependencies.py
models.py

FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
JINJA SCRIPTS

FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
WHAT JINJA?

Fast, expressive and extensible


templating language
Able to write code similar to Python
in the DOM
The template is passed data to
render within the final document

FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
WHAT ARE JINJA TEMPLATING TAGS AND SCRIPTS?

Jinja tags allows developers to be confident while working with backend data, using tags that are similar
to HTML.

FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
WHAT ARE JINJA TEMPLATING TAGS AND SCRIPTS?

Now image we have a list of todos that we retrieved from the database. We can pass the entire list
of todos into the front-end and loop through each todo with this simple ‘for loop’ on the template.

todos.py
Home.html

FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
WHAT ARE JINJA TEMPLATING TAGS AND SCRIPTS?

We can also use Jinja templating language with if else statements. One thing that may stand out is the double brackets with
todos|length

FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
LET’S LEARN GIT

LET’S CODE TOGETHER © © CODINGWITHROBY


WHAT IS GIT?

Free and open-source distributed


version control system
Can handle small to large
applications and projects
Allows team members to use same
files by distributed branches/
environments

LET’S CODE TOGETHER © © CODINGWITHROBY


GIT EXAMPLE?
Version 1

class MathFunctions: Simple Python Class

def addition(a, b): Addition Function


return a + b

We need to add subtraction to MathFunctions

LET’S CODE TOGETHER © CODINGWITHROBY


GIT EXAMPLE?
Version 2

class MathFunctions: Simple Python Class

def addition(a, b): Addition Function


return a + b

def subtraction(a, b):


Subtraction Function
return a - b

New Function New Version Of Code

LET’S CODE TOGETHER © © CODINGWITHROBY


GIT EXAMPLE?
Version 3

class MathFunctions: Simple Python Class

def addition(a, b): Addition Function


return a + b

def subtraction(a, b):


Subtraction Function
return a - b

def multiplication(a, b): Multiple Function


return a * b
LET’S CODE TOGETHER © © CODINGWITHROBY
GIT EXAMPLE?
Version 1
Version Control

Version 2

Version 3
Commit 1

Commit 2

LET’S CODE TOGETHER © © CODINGWITHROBY


WHAT IS GIT?

Class MathFunctions Bill’s Code Sarah’s Code

addition subtraction

Multiplication Division Square


Root Power

LET’S CODE TOGETHER © © CODINGWITHROBY


WHAT IS GIT?

Class MathFunctions) Bill’s Code Sarah’s Code

Functions

New New
Function Function

LET’S CODE TOGETHER © © CODINGWITHROBY


Git Repo & Version Control
GIT?
todos.py home.html
Commit 1
Code files (for app)

auth.py styles.css

todos.py home.html

Commit 2
todos.py
auth.py styles.css

new.py
Commit 3

LET’S CODE TOGETHER © © CODINGWITHROBY


WHAT IS GIT?

Free and open-


source distributed
version control
system

LET’S CODE TOGETHER © © CODINGWITHROBY


WHAT IS GIT?

Track Changes
Free and open- Version Control
source distributed Allows team members to use same
version control files without needing to sync every time
system

LET’S CODE TOGETHER © © CODINGWITHROBY


GIT BASICS

LET’S CODE TOGETHER © © CODINGWITHROBY


GIT EXAMPLE?
Version 1
Version Control

Version 2

Version 3
Commit 1

Commit 2

LET’S CODE TOGETHER © © CODINGWITHROBY


GIT EXAMPLE?
Git Command Details
git init Initializes a new, empty repository

LET’S CODE TOGETHER © © CODINGWITHROBY


GIT EXAMPLE?
Git Command Details
git init Initializes a new, empty repository

git add . Adds files from a non-staged area to


a staging GIT area

LET’S CODE TOGETHER © © CODINGWITHROBY


GIT EXAMPLE?
Git Command Details
git init Initializes a new, empty repository

git add . Adds files from a non-staged area to


a staging GIT area
git commit –m “info here” Move files from a staging area to a
commit

LET’S CODE TOGETHER © © CODINGWITHROBY


GIT EXAMPLE?
Git Command Details
git init Initializes a new, empty repository

git add . Adds files from a non-staged area to


a staging GIT area
git commit –m “info here” Move files from a staging area to a
commit
git checkout <commit #> Open up previous commit

LET’S CODE TOGETHER © © CODINGWITHROBY


GIT EXAMPLE?
Git Command Details
git init Initializes a new, empty repository

git add . Adds files from a non-staged area to


a staging GIT area
git commit –m “info here” Move files from a staging area to a
commit
git checkout <commit #> Open up previous commit

git log Shows committed Snapshots

LET’S CODE TOGETHER © © CODINGWITHROBY


GIT BASICS
python-git-basics GIT
git init

stashed
un-stashed

git add .

Commit 1 Complete git commit –m “First


commit.”
LET’S CODE TOGETHER © © CODINGWITHROBY
GIT BASICS python-git-basics

stashed

un-stashed

git add .

git commit –m “Added addition


Commit 2 Complete functionality”

LET’S CODE TOGETHER © © CODINGWITHROBY


GIT BASICS
2 Different Commits

commit
aabbccddee112233445566
python-git-basics Author: Eric Roby
git log “Added Addition Function”

commit
aabbccddee112233445567
Author: Eric Roby
git checkout “First Commit”
aabbccddee112233445567
LET’S CODE TOGETHER © © CODINGWITHROBY
GIT BRANCHES

LET’S CODE TOGETHER © © CODINGWITHROBY


WHAT IS A GIT BRANCH?

A pointer - to take a A pointer of data change


snapshot of a
Isolation of feature development
change. Branches
can be merged into Linear development
other branches

LET’S CODE TOGETHER © © CODINGWITHROBY


GIT EXAMPLE?
Git Command Details
git branch <branch name> Create new isolated branch

LET’S CODE TOGETHER © © CODINGWITHROBY


GIT EXAMPLE?
Git Command Details
git branch <branch name> Create new isolated branch

git checkout branch <branch name> Change root to branch selected

LET’S CODE TOGETHER © © CODINGWITHROBY


GIT EXAMPLE?
Git Command Details
git branch <branch name> Create new isolated branch

git checkout branch <branch name> Change root to branch selected

git switch branch <branch name> Same as above new command as of


Git (2.23)

LET’S CODE TOGETHER © © CODINGWITHROBY


GIT BRANCHES?

All code is currently in the master branch

git branch multiplication-branch New branch

Checkout new branch


git checkout multiplication-branch

Multiplication-
master branch
branch

LET’S CODE TOGETHER © © CODINGWITHROBY


GIT EXAMPLE?

Master Branch Multiplication-branch

addition addition

subtraction
subtraction

multiplication
multiplication

merge

LET’S CODE TOGETHER © © CODINGWITHROBY


GIT BRANCHES python-git-basics
detached-head
merge
multiplication-
branch
git checkout
master branch multiplication-branch

git merge <commit id>

master branch
git commit –m “adding
git merge multiplication-
multiplication function.”
branch
LET’S CODE TOGETHER © © CODINGWITHROBY
WHAT IS GITHUB?

LET’S CODE TOGETHER © © CODINGWITHROBY


WHAT IS GITHUB?

Git Repository hosting service


User friendly interface
Large development platform

LET’S CODE TOGETHER © © CODINGWITHROBY


WHAT IS GITHUB?

Free and open-


Top Git Repository
source distributed
hosting service
version control
available
system

LET’S CODE TOGETHER © © CODINGWITHROBY


WHAT IS GITHUB?
GitHub

Git

All Git data is saved on Cloud. Can


access version control and team’s
merges

LET’S CODE TOGETHER © © CODINGWITHROBY


WHAT IS RENDER?

LET’S CODE TOGETHER © CODINGWITHROBY


WHAT IS RENDER?

Platform as a service (PaaS)


Helps developers build, run and
operate applications entirely on the
cloud
Developers can focus on coding and
not have to worry about the
infrastructure of their applications

LET’S CODE TOGETHER © CODINGWITHROBY


RENDER PRICING?

Pricing depends on many factors of


how you want your application to
perform online
Free Trial
Free Plan
Businesses of all sizes use Render
as their cloud PaaS provider.

LET’S CODE TOGETHER © CODINGWITHROBY


WHAT IS RENDER?

Code deployment system


Continuous Integration & Continuous
Deployment (CI/CD)
Load Balancing
and more…

Focus on Code

LET’S CODE TOGETHER © CODINGWITHROBY


WHAT IS RENDER?

LET’S CODE TOGETHER © CODINGWITHROBY


DIFFERENT PLATFORMS?

LET’S CODE TOGETHER © CODINGWITHROBY


THANK YOU!!

FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
CONTACT ME!

[email protected]
Instagram: @codingwithroby

FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
LET'S LEARN PYTHON

Assignment!

LET’S CODE TOGETHER © © CODINGWITHROBY


LET'S LEARN PYTHON

Variables!

LET’S CODE TOGETHER © © CODINGWITHROBY


LET'S LEARN PYTHON

Comments!

LET’S CODE TOGETHER © © CODINGWITHROBY


LET'S LEARN PYTHON

String
Formatting!

LET’S CODE TOGETHER © © CODINGWITHROBY


LET'S LEARN PYTHON

User Input!

LET’S CODE TOGETHER © © CODINGWITHROBY


LET'S LEARN PYTHON

Lists!

LET’S CODE TOGETHER © © CODINGWITHROBY


LET'S LEARN PYTHON

Sets & Tuples!

LET’S CODE TOGETHER © © CODINGWITHROBY


LET'S LEARN PYTHON

Boolean &
Operators!

LET’S CODE TOGETHER © © CODINGWITHROBY


LET'S LEARN PYTHON

If Else!

LET’S CODE TOGETHER © © CODINGWITHROBY


LET'S LEARN PYTHON

Loops!

LET’S CODE TOGETHER © © CODINGWITHROBY


LET'S LEARN PYTHON

Dictionaries!

LET’S CODE TOGETHER © © CODINGWITHROBY


LET'S LEARN PYTHON

Functions!

LET’S CODE TOGETHER © © CODINGWITHROBY


Object Oriented Programming
What is Object Oriented Programming?

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
What is Object Oriented Programming?

• Object Oriented Programming (OOP) - is a programming paradigm


based on the concepts of objects, which can contain data and code.

• OOP has bene ts that include:

• Scalability

• Ef ciency

• Reusability

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
fi
fi
What are objects?
• There are objects around us in real life

• Looking out my window I see:

• Trees

• Houses

• My dog, Milo.

• All of these are real objects that we could create.

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
What are objects?
• Looking at these objects there are a two ways to de ne them:

• Behavior

• State

• Let’s take a closer look at my dog, Milo.

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC

fi
Behavior
• Milo has many behaviors that a normal dog would have:

• Barking

• Eating

• Drinking

• Sleeping

• Walking

• Running

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
State
• Milo has individual pieces of state:

• 4 legs

• 2 ears

• Goldendoodle

• 5 years old

• Yellow

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
Primitive Data Types

File: Main.py

legs: int = 4
ears: int = 2
type: str = ‘Goldendoodle’
age: int = 5
color: str = ‘Yellow’

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
Dog as an Object

File: Dog.py

class Dog:

legs: int = 4
ears: int = 2
type: str = ‘Goldendoodle’
age: int = 5
color: str = ‘Yellow’

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
Dog Object
File: Dog.py
File: Main.py

from Dog import *

dog = Dog()

dog.legs
dog.ears
dog.type
dog.age
dog.color

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
Four Pillars

Encapsulation Abstraction Inheritance Polymorphism

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
What are we creating?
What are we creating?

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
Drum roll….

• Small game where we can create enemies that ght each other!

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
fi
Acceptance Criteria

• Enemies that can ght one another

• Different types of enemies

• Zombie

• Ogre

• Each enemy has different powers, health points and attack damage

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
fi
What are we creating continued

• We will be implementing the four pillars of OOP:

Encapsulation Abstraction Inheritance Polymorphism

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
What do we need to start?
• Enemy Object:

• Name / Type of enemy

• Health points

• Attack damage

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
Enemy Object

File: Enemy.py

class Enemy:

type_of_enemy: str
health_points: int = 10
attack_damage: int = 1

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
Enemy Object
File: Main.py

from Enemy import *

enemy = Enemy()

print(f’{enemy.type_of_enemy} has {enemy.health_points} health points


And can do attack of {enemy.attack_damage}’)

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
Enemy Object
File: Main.py
File: Enemy.py

Terminal:

‘Enemy’ object has no attribute ‘type_of_enemy’

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
Enemy Object
File: Main.py

from Enemy import *

enemy = Enemy()

enemy.type_of_enemy =
‘Zombie’

print(f’{enemy.type_of_enemy} has {enemy.health_points} health points


And can do attack of {enemy.attack_damage}’)

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
Enemy Object
File: Main.py

File: Enemy.py

Terminal

Zombie has 10 health points and can do attack of 1

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
Abstraction
What is abstraction?

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
What is Abstraction?

• Let’s think of ashlight

• A ashlight has a ‘on' and ‘off’ switch

• When you turn the switch ‘on’, you expect a beam of light to shoot out of
the ashlight

• When the switch is ‘off’, you expect no light

• We do not know how the light inside the ashlight turns ‘on’ and ‘off’,
we just know that when the ashlight is ‘on’ we expect a beam of light.

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
fl
fl
fl
fl
fl
What is Abstraction?
• Abstraction - This means to hide the implementation and only show necessary details
to the user.

• Let’s say we add new code to allow the enemy to talk:

File: Enemy.py

class Enemy:

type_of_enemy: str
health_points: int = 10
attack_damage: int = 1

def talk(self):
print(‘I am an Enemy!’)

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
Now we can use Abstraction
File: Main.py

from Enemy import *

enemy = Enemy()

enemy.type_of_enemy = ‘Zombie’

enemy.talk()

print(f’{enemy.type_of_enemy} has {enemy.health_points} health points


And can do attack of {enemy.attack_damage}’)

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
Abstraction
• Make more methods for our Enemy.
File: Enemy.py

. . .

def talk():
print(f’I am a {self.type_of_enemy}. Be prepared to fight.’)

def walk_forward():
print(f’{self.type_of_enemy} moves closer to you.’)

def attack():
print(f’{self.type_of_enemy} attacks for {self.attack_damage} damage’)

. . .

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
Now we can use Abstraction
File: Main.py
Terminal

from Enemy import *

I am a Zombie be prepared to ght!


enemy = Enemy()
Zombie moves closer to you
enemy.type_of_enemy = ‘Zombie’

enemy.talk() Zombie attacks for 1 damage

enemy.walk_forward()

enemy.attack()

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
fi
Why use Abstraction?

• This allows users to not have to understand what the functionality is


behind scenes.

• You can create simple and reusable code

• Allows for a better use of the DRY principle (Don’t repeat yourself)

• Enables Python objects to become more scalable.

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
Constructors
How to use constructors?

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
What is constructors?
• Constructors - Are used to create and initialize an object of a class with or
without starting values.
from Enemy import *
Example of calling a constructor
enemy = Enemy()

enemy.type_of_enemy = ‘Zombie’

enemy.talk()

enemy.walk_forward()

enemy.attack()

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
Different types of constructors

• Default / Empty Constructors

• No Argument Constructors

• Parameter Constructors

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
Default / Empty Constructor
Default/Empty Constructor
File: Enemy.py

class Enemy:
Example:

type_of_enemy: str enemy = Enemy()


health_points: int = 10
attack_damage: int = 1

def __init__(self):
pass
Automatically created if no constructor is found

def talk(self):
print(‘I am an Enemy!’)
“self” refers to the current class/
object

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
No Argument Constructor

File: Enemy.py

class Enemy:
Example:

type_of_enemy: str enemy = Enemy()


health_points: int = 10
attack_damage: int = 1

def __init__(self):
print(‘New enemy created with no starting values’)

def talk(self):
print(‘I am an Enemy!’)

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
Parameter Constructor
File: Enemy.py

Example:

enemy = Enemy(‘Zombie’)

class Enemy:

def __init__(self, type_of_enemy, health_points=10, attack_damage=1):


self.type_of_enemy = type_of_enemy
self.health_points = health_points
self.attack_damage = attack_damage

def talk(self):
print(‘I am an Enemy!’)
Example:

enemy = Enemy(‘Zombie’, 15, 3)

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
Using parameters constructor
File: Main.py

from Enemy import *

enemy = Enemy(‘Zombie’, 15, 3)

print(f’{enemy.type_of_enemy} has {enemy.health_points} health points


And can do attack of {enemy.attack_damage}’)

Terminal

Zombie has 15 health points and can do attack of 3

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
Encapsulation
What is encapsulation?

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
What is Encapsulation?
• Encapsulation - Bundling of data

• Let’s take a closer look at the 3 attributes our Enemy currently has:
File: Enemy.py

class Enemy:
p
p
u
p
u
b def __init__(self, type_of_enemy, health_points=10, attack_damage=1):
u
b
l self.type_of_enemy = type_of_enemy
b
l
i self.health_points = health_points
l
i
c self.attack_damage = attack_damage
i
c
c def talk(self):
print(‘I am an Enemy!’)

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
What public class attributes mean?
File: Main.py

from Enemy import *

zombie = Enemy(‘Zombie’)

zombie.type_of_enemy = ‘Orc’

zombie.talk()

zombie.walk_forward()

zombie.attack()

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
What is Encapsulation?
• Changes our public attributes to private

File: Enemy.py

class Enemy:

def __init__(self, type_of_enemy, health_points=10, attack_damage=1):


self.__type_of_enemy = type_of_enemy
self.health_points = health_points
self.attack_damage = attack_damage

def talk(self):
print(‘I am an Enemy!’)
__ (double underscore)

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
What is Encapsulation?
File: Enemy.py GETTERS & SETTERS
class Enemy:

def __init__(self, type_of_enemy, health_points=10, attack_damage=1):


self.__type_of_enemy = type_of_enemy
self.health_points = health_points
self.attack_damage = attack_damage

def get_type_of_enemy(self):
return self.__type_of_enemy

def set_type_of_enemy(self, type_of_enemy):


self__type_of_enemy = type_of_enemy

def talk(self):
print(‘I am an Enemy!’)

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
Using Getters & Setters
File: Main.py

from Enemy import *

enemy = Enemy(‘Zombie’, 10, 1)

enemy.__type_of_enemy = ‘Zombie’
enemy.get_type_of_enemy()

enemy.talk()

enemy.walk_forward()

enemy.attack()

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
Why use Encapsulation?

• Helps keep related elds and methods together

• Makes our code cleaner and easier to read

• Provides more exibility to our code

• Provides more reusability with our code

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
fl
fi
Inheritance
What is inheritance?

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
What is Inheritance?
• Inheritance - Process of acquiring properties from one class to other
classes

• Creates a hierarchy between classes

Parent Class Child Class


class Animal
class Dog(Animal)
weight: int
** All Animal Attributes **
color: str
age: int
can_shed: bool
animal_type: str
domestic_name: str

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
Hierarchy thus far
Animal

Dog

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
What is Inheritance?
class Animal:

weight: int class Dog(Animal):


color: str
age: int ** All Animal Attributes **
animal_type: str
can_shed: bool
def eat(self): domestic_name: str
print(‘Animal eating’)
** All Animal Methods **
def sleep(self): }
print(‘Animal sleeping’)

dog = Dog()
dog.eat() Animal eating

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
What is Inheritance?
class Animal: class Dog(Animal):
weight: int ** All Animal Attributes **
color: str
age: int can_shed: bool
animal_type: str domestic_name: str
def eat(self):
def talk(self):
print(‘Animal eating’)
print(‘Bark!’)
def sleep(self):
print(‘Animal sleeping’) ** All Animal Methods **
}

dog = Dog() animal = Animal()


dog.talk() animal.talk()
Bark!

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
What is a method override?
• Our Animal eat() is pretty generic. What if we want to add our own Dog
eat()?
class Dog(Animal):
class Animal:
** All Animal Attributes **
** All Animal Attributes **
can_shed: bool
def eat(self):
domestic_name: str
print(‘Animal eating’)

def sleep(self): def talk(self):


print(‘Animal sleeping’) print(‘Bark!’)

def eat(self):
print(‘Chews on bone!’)

** All Animal Methods **


dog = Dog()
}
dog.eat() Animal
Chews on
eating
bone!
dog.sleep() Animal sleeping

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
What is method overriding?
• As we can see from the last example, both Dog() and Animal() have the
eat() functionality.

• Method overriding is when a child class has its own method already
present in the parent class.

• When the child class does not have the same method, it will default to the
parent method.

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
Let’s now add a Bird class

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
Hierarchy thus far
Animal

Bird Dog

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
What is Inheritance?
class Animal:
class Bird(Animal)
weight: int
color: str ** All Animal Attributes **
age: int birdType: str
animal_type: str
def talk(self):
def eat(self): print(‘Chirp!’)
print(‘Animal eating’)
def fly(self):
print(‘Bird begins to soar!’)
def sleep(self):
print(‘Animal sleeping’) ** All Animal Methods **

bird = Bird() Chirp! animal = Animal()


bird.talk() animal.talk()
bird.fly() Bird begins to soar! animal.fly()

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
Hierarchy thus far
Animal
An Animal() cannot fly

Bird Dog

A Bird() can fly() A Dog() cannot fly

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
self vs super
self vs super
• self is used to refer to the current object that is created or being
instantiated, while super is used to refer to the parent class.

• self is used when there is a need to differentiate between the instance


variables & parameters with the same name, while super is used to call
the parent class methods and/or constructors.

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
this vs super
• Student has an extra property: degree
• Student uses super to call the Person
class Person: constructor which assigns the properties
def __init__(self, name, age):
name and age.
self.name = name
self.age = age • Student uses self to reference the degree
property which is different from the degree
parameter/argument coming in.
class Student(Person):

def __init__(self, name, age, degree):


super().__init__(name=name, age=age)
self.degree = degree

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
How will we implement inheritance?
Parent and Child classes?
• Currently our only class is Enemy()

• Enemy() is our Parent Class

• We will now create two children classes

• Zombie() Enemy()

• Ogre()
Zombie() Ogre()

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
Take a look at the Zombie Class
class Enemy:
class Zombie(Enemy):
def __init__(self, type_of_enemy, health_points,
attack_damage): def __init__(self, health_points,
attack_damage):
self.__type_of_enemy = type_of_enemy
self.health_points = health_points super().__init__(type_of_enemy=‘Zombie’,
self.attack_damage = attack_damage health_points=health_points,
attack_damage=attack_damage)
def get_type_of_enemy(self):
return self.__type_of_enemy
def talk(self):
def talk(self): print(‘*Grumbling…*’)Method Overriding
print(‘I am an Enemy!’)
def spread_disease(self):
def walk_forward(self): print(‘The zombie is trying to spread
print(f’{self.__type_of_enemy} moves closer infection’)
to you’) New Zombie only Method

Parent class is also called the Super class

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
Take a look at the Ogre Class
class Enemy:

def __init__(self, type_of_enemy, health_points,


class Ogre(Enemy):
attack_damage):
def __init__(self, health_points,
self.__type_of_enemy = type_of_enemy
attack_damage):
self.health_points = health_points
self.attack_damage = attack_damage
super().__init__(type_of_enemy=‘Ogre’,
health_points=health_points,
def get_type_of_enemy(self):
attack_damage=attack_damage)
return self.__type_of_enemy

def talk(self):
def talk(self):
print(‘I am an Enemy!’)
print(‘Ogre is slamming hands all around.’)
def walk_forward(self): Method Overriding
print(f’{self.__type_of_enemy} moves closer
to you’)

Parent class is also called the Super class

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
Polymorphism
What is Polymorphism?
• Polymorphism means to have many forms

• Let’s go back to our Animal examples:

Animal()

Bird() Dog() Many other animal classes

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
What is Polymorphism?
zoo: Animal =[]

dog
dog == Animal()
Dog() class Dog(Animal):
dog2
zoo.append(dog)
= Dog() ** All Dog Methods **
bird = Bird()
This will work
lion = Lion() Animal() class Bird(Animal):

** All Bird Methods **

zoo.append(bird) class Lion(Animal):

zoo.append(dog2) Dog() ** All Lion Methods **


zoo.append(lion)

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
What is Polymorphism?
class Animal:

/* We already added some def talk(self):


print(‘Does not make a sound’)
animals to our zoo
*/ VALIDATE THIS
class Dog(Animal):

def talk(self):
for animal in zoo: print(‘Bark!’)
animal.talk()
class Bird(Animal):

def talk(self):
print(‘Chirp!’)
Bark!
Chirp! class Lion(Animal):
Bark!
def talk(self):
Roar! print(‘Roar!’)
}
Roar!

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
How will we implement Polymorphism?
Starting off..
• Create a new battle function within our main.py le

• Uses our enemy talk() and attack() methods


File: Main.py

def battle(Enemy e):


e.talk()
Enemy() e.attack()

Zombie() Ogre()

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC

fi
Now we can use Polymorphism
File: Main.py

def battle(Enemy e) {
e.talk()
e.attack() *Grumbling…*
Zombie attacks for 1 damage
zombie = Zombie(10, 1)
Ogre is slamming his hands all around
ogre = Ogre(20, 3) Ogre attacks for 3 damage

battle(zombie)
battle(ogre)

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
Time for a battle!
Starting off..
• Before we start a battle:

• Let’s give our Enemies a special attack.

• If the Enemy does not have a special attack, we print “Enemy does
not have a special attack.”
Enemy()
• Add code into the:

• Enemy (Parent)
Zombie() Ogre()
• Both Zombie and Ogre

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
Take a look at the Enemy Parent Class
class Enemy:

def __init__(self, type_of_enemy, health_points,


attack_damage):

self.__type_of_enemy = type_of_enemy • New special_attack() method that


self.health_points = health_points enemies can default to when they
self.attack_damage = attack_damage
do not have a special attack.
def get_type_of_enemy(self):
return self.__type_of_enemy

def talk(self):
print(‘I am an Enemy!’)

def walk_forward(self):
print(f’{self.__type_of_enemy} moves closer
to you’)

def special_attack(self):
print(’Enemy has no special attack’)

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
Take a look at the Zombie & Ogre Class
class Ogre(Enemy):
class Zombie(Enemy):
def __init__(self, health_points, attack_damage):
def __init__(self, health_points, attack_damage):
super().__init__(type_of_enemy=‘Ogre’,
super().__init__(type_of_enemy=‘Zombie’,
health_points=health_points,
health_points=health_points,
attack_damage=attack_damage)
attack_damage=attack_damage)

def talk(self):
def talk(self):
print(‘Ogre is slamming hands all around.’)
print(‘*Grumbling…*’)

def spread_disease(self):
def special_attack(self):
print(‘The zombie is trying to spread infection’)
did_special_attack_work = random.random() < 0.20
if did_special_attack_work:
self.attack_damage += 4
def special_attack(self):
print(‘Ogre attack has increased by 4!’)
did_special_attack_work = random.random() < 0.50
if did_special_attack_work:
self.health_points += 2
print(‘Zombie regenerated 2 HP!’)

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
Now we can enhance our main file
File: Main.py

def battle(e1: Enemy, e2: Enemy) {


e1.talk()
e2.talk()

while e1.health_points > 0 and e2.health_points > 0


e1.special_attack()
e2.special_attack()
e2.attack()
e1.health_points -= e2.attack_damage
e1.attack()
e2.health_points -= e1.attack_damage

if e1.health_points > 0:
print(“Enemy 1 wins!”)
else:
print(“Enemy 2 wins!”)

zombie = Zombie(10, 1)
ogre = Ogre(20, 3)

battle(zombie, ogre)

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
Composition
What is a composition?
• A way to create objects made up of other objects
• In composition, a class contains one or more objects of another class as instance
variables.
• Provide layered functionality to the object
car.getEngine().engineOn()
• Known as a HAS-A relationship

Vehicle() Engine()

Car() Truck() engineOn() engineOff()

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
What is composition

class Engine: class Vehicle:

def __init__(self, engineType): def __init__(self, type, forSale, engine):


self.engineType = engineType self.type = type
self.forSale = forSale
def startEngine(self): self.engine = engine
print(“Engine is running”)

def stopEngine(self):
print(“Engine is off”)

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
What is composition

engine = Engine(“V6”)
vehicle = Vehicle(“Car”, True, engine)
vehicle.engine.startEngine()

Engine is running

• Using composition here because the vehicle HAS-A engine.


• This is different from an interface IS-A relationship.
• A vehicle must have an engine, but an engine does not need to have a vehicle.

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
Implementation of Composition
Composition implementation?
• We will create a new Hero class

• We will create a new Weapon class

• Our Hero will have a HAS-A (composition) relationship


with our Weapon class

Hero() Weapon()

weapon_type attack_increase

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
Composition implementation

class Weapon:

def __init__(self, weapon_type, attack_increase):


self.weapon_type = weapon_type
self.attack_increase = attack_increase

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
Composition implementation

class Hero:

def __init__(health_points, attack_damage):


self.health_points = health_points
self.attack_damage = attack_damage
self.is_weapon_equipped = False
self.weapon: Weapon = None

def equipWeapon(self)
if self.weapon is not None and not self.is_weapon_equipped:
self.attack_damage += self.weapon.attack_increase
self.is_weapon_equipped = True

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC
Now we can enhance our main file
File: Main.py

def hero_battle(hero: Hero, enemy: Enemy) {

while hero.health_points > 0 and enemy.health_points > 0


enemy.special_attack()
enemy.attack()
hero.health_points -= enemy.attack_damage
hero.attack()
enemy.health_points -= hero.attack_damage

if hero.health_points > 0:
print(“Hero wins!”)
else:
print(“Enemy 2 wins!”)

zombie = Zombie(10, 1)
hero = Hero(10, 1)
weapon = Weapon(‘Sword’, 5)
hero.weapon = weapon
hero.equip_weapon()
hero_battle(hero, zombie)

battle(zombie, ogre)

LET’S CODE TOGETHER www.luv2code.com © luv2code


© CODINGWITHROBY LLC

You might also like