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

MVC & Python - Part1

The document discusses the MVC design pattern and Python programming language. It introduces MVC and its components including the model, view, and controller. It then covers Python syntax, variables, data types, and other basic concepts.

Uploaded by

ski superhuman
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
39 views

MVC & Python - Part1

The document discusses the MVC design pattern and Python programming language. It introduces MVC and its components including the model, view, and controller. It then covers Python syntax, variables, data types, and other basic concepts.

Uploaded by

ski superhuman
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 59

IS231: Web Technology

MVC & Python Intro

BY: LAILA ESHEIBA


References
- MVC: https://www.youtube.com/watch?v=pCvZtjoRq1I
- W3Schools – Python
- Previous lectures of Dr.Neamat.

Laila Esheiba WEB TECHNOLOGY 2


MVC Design Pattern
Model View Controller

Software Architectural Design Pattern

One of the most frequently used patterns

General Goal: Separate application functionality

Promotes organized programming

Laila Esheiba WEB TECHNOLOGY 3


MVC Design Pattern
The Model View Controller (MVC) design pattern specifies that
an application consist of a data model, presentation information,
and control information. The pattern requires that each of these be
separated into different objects.

Laila Esheiba WEB TECHNOLOGY 4


Some Web Frameworks (using
MVC Concepts)
Ruby on Rails (Ruby)
Sinatra (Ruby)
Django (Python)
Flask (Python)
Zend (PHP)
Laravel (PHP)
Angular (JS)
Backbone (JS)
Express (JS)
Codeigniter(PHP)

Laila Esheiba WEB TECHNOLOGY 5


Model
Data related logic (Brain of the application)

Interactions with database (SELECT, INSERT, UPDATE, and DELETE), can


even be a simple file!

Communicates with controller

Can sometimes update the view (Depends on framework)

Laila Esheiba WEB TECHNOLOGY 6


View
What the end user sees (UI)

Usually consists of HTML/CSS

Communicates with the controller

Can be passed dynamic values from the controller

Templates Engines (allows dynamic data)


◦ Dust
◦ HAML
◦ Jinja (FLASK)
◦ Django Template Language

Laila Esheiba WEB TECHNOLOGY 7


Controller (Middleman)
Receives input (from view, url)

Processes requests (GET, POST, PUT, DELETE)

Gets data from the model

Passes data to the view

Laila Esheiba WEB TECHNOLOGY 8


Cycle

Laila Esheiba WEB TECHNOLOGY 9


MVC Cycle
•A request is made — say, when a user enters a URL associated
with your application.

•A route associated with that URL maps the URL to a controller


action.

•That controller action leverages the necessary model(s) to


retrieve information from the database, and then passes that data
off to a view.

•And that view renders the final page.

Laila Esheiba WEB TECHNOLOGY 10


MVC Advantages
•Multiple developers can work simultaneously on the model,
controller and views.

•MVC enables logical grouping of related actions on a controller


together. The views for a specific model are also grouped
together.

•Reusing of code and parallel development

•Models can have multiple views.

Laila Esheiba WEB TECHNOLOGY 11


MVC Disadvantages
•The framework navigation can be complex because it introduces
new layers of abstraction and requires users to adapt to the
decomposition criteria of MVC.

•Knowledge on multiple technologies becomes the norm.


Developers using MVC need to be skilled in multiple technologies.

Laila Esheiba WEB TECHNOLOGY 12


Example

Laila Esheiba WEB TECHNOLOGY 13


Python
Python is a popular programming language. It was
created by Guido van Rossum, and released in 1991.
It is used for:
• web development (server-side),
• software development,
• mathematics,
• system scripting.

Laila Esheiba WEB TECHNOLOGY 15


What can Python do?
•Python can be used on a server to create web
applications.

•Python can connect to database systems. It can also read


and modify files.

•Python can be used to handle big data and perform


complex mathematics.

•Python can be used for rapid prototyping, or for


production-ready software development.

Laila Esheiba WEB TECHNOLOGY 16


Why Python?
•Python works on different platforms (Windows, Mac, Linux,
Raspberry Pi, etc).

•Python has a simple syntax similar to the English language.

•Python has syntax that allows developers to write programs


with fewer lines than some other programming languages.

•Python runs on an interpreter system, meaning that code


can be executed as soon as it is written. This means that
prototyping can be very quick.

Laila Esheiba WEB TECHNOLOGY 17


Python Syntax compared to
other programming languages
•Python was designed for readability and has some
similarities to the English language with influence from
mathematics.

•Python uses new lines to complete a command, as


opposed to other programming languages which often
use semicolons or parentheses.

•Python relies on indentation, using whitespace, to define


scope; such as the scope of loops, functions and classes.
Other programming languages often use curly-brackets
for this purpose.

Laila Esheiba WEB TECHNOLOGY 18


Python Files
•Python is an interpreted programming language; this means that as a
developer you write Python (.py) files in a text editor and then put
those files into the python interpreter to be executed.

Try helloworld.py
print(“Hello,World!”)

•You can also write in the python command line directly to test some
functionality

Laila Esheiba WEB TECHNOLOGY 19


Python Indentation
•Indentation refers to the spaces at the beginning of a code
line.

•Where in other programming languages the indentation in


code is for readability only, the indentation in Python is very
important.

•Python uses indentation to indicate a block of code.

Try the following example with and without indentation:


if 5 > 2:
print("Five is greater than two!")

Laila Esheiba WEB TECHNOLOGY 20


Indentation
•The number of spaces is up to you as a programmer, but
it has to be at least one.

if 5 > 2:
print("Five is greater than two!")
if 5 > 2:
print("Five is greater than two!")

Laila Esheiba WEB TECHNOLOGY 21


Indentation
•You have to use the same number of spaces in the same
block of code, otherwise Python will give you an error:

if 5 > 2:
print("Five is greater than two!")
print("Five is greater than two!")

Laila Esheiba WEB TECHNOLOGY 22


Python Variables
•In Python, variables are created when you assign a value
to it:

Example
x = 5
y = "Hello, World!“

•Python has no command for declaring a variable.

Laila Esheiba WEB TECHNOLOGY 23


Comments
•Python has commenting capability for the purpose of in-
code documentation.

•Comments start with a #, and Python will render the rest


of the line as a comment:

#This is a comment.
print("Hello, World!")

Laila Esheiba WEB TECHNOLOGY 24


Multi Line Comments
•Python does not really have a syntax for multi line comments.

•To add a multiline comment, you could insert a # for each line:

#This is a comment
#written in
#more than just one line
print("Hello, World!")

Laila Esheiba WEB TECHNOLOGY 25


Multi Line Comments
•Since Python will ignore string literals that are not assigned
to a variable, you can add a multiline string (triple quotes) in
your code, and place your comment inside it:

"""
This is a comment
written in
more than just one line
"""
print("Hello, World!")

•As long as the string is not assigned to a variable, Python


will read the code, but then ignore it, and you have made a
multiline comment.

Laila Esheiba WEB TECHNOLOGY 26


Casting
•If you want to specify the data type of a variable, this can
be done with casting.

x = str(3) # x will be '3'


y = int(3) # y will be 3
z = float(3) # z will be 3.0

Laila Esheiba WEB TECHNOLOGY 27


Get the Type
•You can get the data type of a variable with the type() function.

x = 5
y = "John"
print(type(x))
print(type(y))

Laila Esheiba WEB TECHNOLOGY 28


Single or Double Quotes?
•String variables can be declared either by using single or
double quotes:

x = "John"
# is the same as
x = 'John'

Laila Esheiba WEB TECHNOLOGY 29


Case-Sensitive
•Variable names are case-sensitive.

This will create two variables:


a = 4
A = "Sally"
#A will not overwrite a

Laila Esheiba WEB TECHNOLOGY 30


Variable Names
•A variable name must start with a letter or the
underscore character

•A variable name cannot start with a number

•A variable name can only contain alpha-numeric


characters and underscores (A-z, 0-9, and _ )

•Variable names are case-sensitive (age, Age and AGE are


three different variables)

Laila Esheiba WEB TECHNOLOGY 31


Variable Names Examples
myvar = "John"
my_var = "John"
_my_var = "John"
myVar = "John"
MYVAR = "John"
myvar2 = "John"

Laila Esheiba WEB TECHNOLOGY 32


Illegal Variable Names
Examples

2myvar = "John"
my-var = "John"
my var = "John"

Laila Esheiba WEB TECHNOLOGY 33


Multi Words Variable
Names
•Variable names with more than one word can be difficult
to read.
There are several techniques you can use to make them
more readable:
◦ Camel Case
◦ Each word, except the first, starts with a capital letter:
◦ myVariableName = "John“
◦ Pascal Case
◦ Each word starts with a capital letter:
◦ MyVariableName = "John“
◦ Snake Case
◦ Each word is separated by an underscore character:
◦ my_variable_name = "John"

Laila Esheiba WEB TECHNOLOGY 34


Python Variables - Assign
Multiple Values
•Many Values to Multiple Variables
Python allows you to assign values to multiple variables in
one line:

Example
x, y, z = "Orange", "Banana", "Cherry"
print(x)
print(y)
print(z)

Laila Esheiba WEB TECHNOLOGY 35


One Value to Multiple
Variables
•And you can assign the same value to multiple variables
in one line:

Example
x = y = z = "Orange"
print(x)
print(y)
print(z)

Laila Esheiba WEB TECHNOLOGY 36


Unpack a Collection
•If you have a collection of values in a list, tuple etc.
Python allows you extract the values into variables. This
is called unpacking.

Unpack a list:

fruits = ["apple", "banana", "cherry"]


x, y, z = fruits
print(x)
print(y)
print(z)

Laila Esheiba WEB TECHNOLOGY 37


Output Variables
•The Python print statement is often used to output variables.

•To combine both text and a variable, Python uses the + character:
x = "awesome"
print("Python is " + x)

x = "Python is "
y = "awesome"
z = x + y
print(z)

Laila Esheiba WEB TECHNOLOGY 38


+ Operator
•For numbers, the + character works as a mathematical operator:

x = 5
y = 10
print(x + y)

If you try to combine a string and a number, Python will give


you an error:

x = 5
y = "John"
print(x + y)

Laila Esheiba WEB TECHNOLOGY 39


Global Variables
•Variables that are created outside of a function are known
as global variables.
•Global variables can be used by everyone, both inside of
functions and outside.

x = "awesome"

def myfunc():
print("Python is " + x)

myfunc()

Laila Esheiba WEB TECHNOLOGY 40


The global Keyword
• Normally, when you create a variable inside a function, that variable is local, and can only
be used inside that function.

• To create a global variable inside a function, you can use the global keyword.

If you use the global keyword, the variable belongs to the global
scope:

def myfunc():
global x
x = "fantastic"
myfunc()
print("Python is " + x)

Laila Esheiba WEB TECHNOLOGY 41


The global Keyword
• Also, use the global keyword if you want to change a global variable inside a
function.

• To change the value of a global variable inside a function, refer to the


variable by using the global keyword:

x = "awesome"
def myfunc():
global x
x = "fantastic"
myfunc()
print("Python is " + x)

Laila Esheiba WEB TECHNOLOGY 42


Python Data Types
Built-in
Text Type:Data
str Types
Numeric int, float, complex
Types:
Sequence list, tuple, range
Types:
Mapping dict
Type:
Set Types: set, frozenset
Boolean bool
Type:
Binary bytes, bytearray, memoryview
Types:

Laila Esheiba WEB TECHNOLOGY 43


Python Strings
• Like many other popular programming languages, strings in Python are
arrays of bytes representing unicode characters.

• However, Python does not have a character data type, a single character
is simply a string with a length of 1.

• Square brackets can be used to access elements of the string.

Get the character at position 1 (remember that the first


character has the position 0):
a = "Hello, World!"
print(a[1])

Laila Esheiba WEB TECHNOLOGY 44


Looping Through a String
•Since strings are arrays, we can loop through the characters in a string,
with a for loop.

Loop through the letters in the word "banana":


for x in "banana":
print(x)

Laila Esheiba WEB TECHNOLOGY 45


String Length
•The len() function returns the length of a string:

a = "Hello, World!"
print(len(a))

Laila Esheiba WEB TECHNOLOGY 46


Check String
•To check if a certain phrase or character is present in a string, we can use
the keyword in.

Example
Check if "free" is present in the following text:
txt = "The best things in life are free!"
print("free" in txt)

Check if "expensive" is NOT present in the following text:

txt = "The best things in life are free!"


print("expensive" not in txt)

Laila Esheiba WEB TECHNOLOGY 47


Slicing Strings
•You can return a range of characters by using the slice
syntax.
•Specify the start index and the end index, separated by a
colon, to return a part of the string.

Example: Get the characters from position 2 to position 5


(not included):

b = "Hello, World!"
print(b[2:5])

Laila Esheiba WEB TECHNOLOGY 48


Slice From the Start
Get the characters from the start to position 5 (not
included):

b = "Hello, World!"
print(b[:5])

Laila Esheiba WEB TECHNOLOGY 49


Slice To the End
•By leaving out the end index, the range will go to the
end:

Get the characters from position 2, and all the way to the
end:
b = "Hello, World!"
print(b[2:])

Laila Esheiba WEB TECHNOLOGY 50


Negative Indexing
•Use negative indexes to start the slice from the end of
the string:

Get the characters:


From: "o" in "World!" (position -5)
To, but not included: “d" in "World!"
(position -2):

b = "Hello, World!"
print(b[-5:-2])

Laila Esheiba WEB TECHNOLOGY 51


Modify Strings
•Python has a set of built-in methods that you can use on
strings.
◦ Upper Case
◦ mystr.upper()
◦ Lower Case
◦ mystr.lower()
◦ Remove Whitespaces
◦ mystr.strip()
◦ Replace String
◦ mystr.replace(“H”,”J”)
◦ Split String
◦ mystr.split(“,”)

Laila Esheiba WEB TECHNOLOGY 52


String Format
age = 36
txt = "My name is John, I am " + age
print(txt)

The above script will generate an error!!

•we can combine strings and numbers by using


the format() method!
The format() method takes the passed
arguments, formats them, and places them in
the string in the placeholders {}.

Laila Esheiba WEB TECHNOLOGY 53


String Format
age = 36
txt = "My name is John, and I am {}"
print(txt.format(age))

• The format() method takes unlimited number of arguments, and are placed into
the respective placeholders:

quantity = 3
itemno = 567
price = 49.95
myorder = "I want {} pieces of item {} for {} dollars."
print(myorder.format(quantity, itemno, price)

Laila Esheiba WEB TECHNOLOGY 54


String Format
•You can use index numbers {0} to be sure the arguments are placed in
the correct placeholders:

quantity = 3
itemno = 567
price = 49.95
myorder = "I want to pay {2} dollars for {0} pieces of
item {1}."
print(myorder.format(quantity, itemno, price))

Laila Esheiba WEB TECHNOLOGY 55


Python - Escape Characters
•To insert characters that are illegal in a string, use an escape character.

•An escape character is a backslash \ followed by the character you want


to insert.

•An example of an illegal character is a double quote inside a string that


is surrounded by double quotes:

txt = “The name of the course is \“Web Technologies\""

Laila Esheiba WEB TECHNOLOGY 56


Boolean Values
•You can evaluate any expression in Python, and get one of two answers,
True or False.

•When you compare two values, the expression is evaluated and Python
returns the Boolean answer:

print(10 > 9)
print(10 == 9)
print(10 < 9)

Laila Esheiba WEB TECHNOLOGY 57


Boolean Values
Most values are true
Some Values are False:

In fact, there are not many values that


evaluate to False, except empty values,
such as (), [], {}, "", the number 0, and
the value None. And of course, the
value False evaluates to False.

Laila Esheiba WEB TECHNOLOGY 58


Next
Continue Python

Laila Esheiba WEB TECHNOLOGY 59

You might also like