Week 7
Week 7
Week 7 Lecture 1
Class BSCCS2001
Materials
Module # 31
Type Lecture
Week # 7
Communication
Week 7 Lecture 1 1
Social Media → Facebook, Instagram, Twitter, YouTube
Knowledge Discovery
Sports
Software Engineering
Library
Education
Document Processing
Health
Domain, functionality, user base, response time, scale, daily hit, and many more
Most use an RDBMS like Oracle, DB2 MySQL, PostgreSQL, etc. for managing data
Applications are functionality split into the frontend layer, middle layer, backend layer
Implements the functionality of the application → Links the frontend & backend
Authentication, Search/Browse logic, Pricing, Cart management Payment handling (gateway), Order
management (mail, SMS, internal actions), Delivery management
Week 7 Lecture 1 2
Support functionality based on frontend interface
Logic tier
This layer coordinates the
application, processes commands,
makes logical decisions and GET LIST OF ALL ADD ALL SALES
evaluations, and performs SALES MADE TOGETHER
LAST YEAR
calculations. It also moves and
processes data between the two
surrounding layers.
SALE 1
QUERY SALE 2
SALE 3
Data tier SALE 4
Storage
Database
Source: https://en.wikipedia.org/wiki/Multitier_architecture
Controller → Receive events, execute actions, and return a view to the user
Business Layer/Tier
Provides mapping from object model of business layer to the relational model of the DB
Week 7 Lecture 1 3
Application Architecture: User Interface
Web browsers have become the de-facto standard user interface to the DBs
Avoid the need for downloading/installing specialized code, while providing a good Graphical User Interface
JavaScript, Flash (dead apparently) and other scripting language runs in the browser, but are downloaded
transparently
Examples → Banks, Airlines and Rental Car reservations, university course registration and grading and so on
These are similar in architecture and workflow with the web, but have significant differences with their smaller (but
wide range of) form factor, and extremely low resources
For example → student can enroll in a class only if she has completed all the prerequisites, and has paid her
tuition fee
Support workflows which define how a task involving multiple participants is to be carried out
Error handling
Schema designer has to provide a mapping between object data and relational schema
For example → Java class Student mapped to a relation student, with corresponding mapping of attributes
Week 7 Lecture 1 4
Objects can be created and saved to the DB using session.save(object)
Architecture Classification
DB architecture uses programming languages to design a particular type of software for business or organizations
DB architecture focuses on the design, development, implementation and maintenance of computer programs that
store and organize information for businesses, agencies and institutions
It can be
Centralized
Decentralized
Hierarchical
The architecture of a DBMS can be seen as either single tier or multi tier:
1-tier architecture
2-tier architecture
3-tier architecture
n-tier architecture
Architecture Evolution
Three distinct eras of application architecture
1-tier Architecture
One-tier architecture involves putting all of the required components for a software application or technology on a
single server or platform
Week 7 Lecture 1 5
Basically, a one-tier architecture keeps all of the elements of an application, including the interface, Middleware and
back-end data, in one place
Developers see these types of systems as the simplest and most direct way
Source: https://medium.com/oceanize-geeks/concepts-of-database-architecture-dfdc558a93e4
2-tier Architecture
The two-tier architecture is based on Client Server architecture
Source: https://medium.com/oceanize-geeks/concepts-of-database-architecture-dfdc558a93e4
3-tier Architecture
A 3-tier architecture separates it tiers - Presentation, Logic and Data Access from each other based on the
complexity of the users and how they use the data present in the DB
Week 7 Lecture 1 6
It is the most widely used architecture to design a DBMS
Source: https://medium.com/oceanize-geeks/concepts-of-database-architecture-dfdc558a93e4
n-tier Architecture
An n-tier architecture distributes different components of the 3-tiers between different servers and adds interface tiers
for interactions and workload balancing
Source: https://medium.com/oceanize-geeks/concepts-of-database-architecture-dfdc558a93e4
Week 7 Lecture 1 7
Presentation Logic Data Functionality
Application
• Login • Mail List View • Inbox • Sent • User Authentication • Connection to • Mail Users • • Send/Receive
Web Mail Items • Outbox • Trash • Mail Composer Mail Server (SMTP, POP, IMAP) • Address Book • Mails • Manage
• Filters Encryption/Decryption Mail items Address Book
• Courses • • Manage
• Login • Add/Delete Courses,
• User Authentication • Timetable Teachers • Rooms • timetable for
Teachers, Rooms, Slots • Assignments:
Timetable Assignment Logic • Slots • multiple courses
• Teachers → Course • Allocations •
Encryption/Decryption Assignments • taken by multiple
Course → Room, Slots • Views
Allocations teachers
Week 7 Lecture 1 8
📚
Week 7 Lecture 2
Class BSCCS2001
Materials
Module # 32
Type Lecture
Week # 7
Most web documents are HyperText documents formatted via the HyperText Markup Language (HTML)
HyperText links to other documents, which can be associated with regions of the text
Forms, enabling users to enter data which can then be sent back to the Web server
"http" indicates that the document is to be accessed using the HyperText Transfer Protocol
The second part gives the unique name of a machine on the Internet
The rest of the URL identifies the document within the machine
Week 7 Lecture 2 1
The path name of a file on the machine:
file:///C:/WINDOWS/media/Alarm01.wav
file:///localhost/c:/WINDOWS/media/Alarm01.wav
http://www.google.com/search?q=silberschatz
Relationships
URN defines an item's identity, while the URL provides a method for finding it
Week 7 Lecture 2 2
Select from a set of options
Enter values
Text boxes
Filled in input sent back to the server, to be acted upon by an executable at the server
HyperText Transfer Protocol (HTTP) used to communication with the Web Server
That is, once the server replies to a request, the server closes the connection with the client, and forgets all about
the request
In contrast, Unix logins, and JDBC/ODBC connections stay connected until the client disconnects
Operating Systems have tight limits on the number of open connections on a machine
For example, user authentication should be done only once per session
Sent by the browser to the server that created the cookie on further interactions
part of HTTP
Server saves the information about cookies it issued, and can use it when serving a request
Web Browser
A web browser is an application software for accessing the World Wide Web (WWW)
A web browser's job is to fetch content from the Web and display it on the user's device
This process begins when the user inputs the URL into the browser address bar, starting with either http:// or
https://
Once a web page has been retrieved, the rendering engine displays it on the user's device
A browser or the rendering engine is a core software component for a web browser
The primary job of a browser engine is to transform HTML documents and other resources of a web page into an
interactive visual representation on a user's device
Each link contains a URL, and when it is clicked or tapped, the browser navigates to the new resource
Web browsers are used on a range of devices, including desktops, laptops, tablets and smartphones
The most used browser is Google Chrome, with 64% global market share on all devices, followed by Safari with
19%
Web Servers
Week 7 Lecture 2 3
A web server is a software and underlying hardware that accepts requests via HTTP or its secure variant HTTPS
A web browser or crawler, requests for a specific resource using HTTP, and the server responds with the content of
that resource or an error message
The server can also accept and store resources sent from the user agent
The document name in a URL may identify an executable program, that when run, generated the HTML document
When an HTTP server receives a request for such a document, it executes the program and sends back the
HTML document that is generated
The Web client can pass extra arguments with the name of the document
To install a new service on the Web, one simply needs to create and install an executable that provides the said
service
Common Gateway Interface (CGI) → a standard interface between web and application server
Web Services
Allow data on Web to be accessed using remote procedure call mechanism
Representational State Transfer (REST) → allows the use of standard HTTP request to a URL to execute a
request and return data
uses XML representation for sending request data, as well as for returning results
Web Architecture
Week 7 Lecture 2 4
Source: https://www.intuz.com/guide-on-web-app-architecture
Scripts may be written for a variety of purposes such as for automating process on a local-computer or to generate
web pages
The programming languages in which scripts are written are called scripting language
Common scripting languages are VBScript, JavaScript, ASP, PHP, PERL, JSP, etc.
Scripting of 2 types:
Client Side → Client-side scripting is responsible for interaction within a web page
The client-side scripts are firstly downloaded at the client-end and then interpreted and executed by the browser
Server Side → Server-side scripting is responsible for the completion or carrying out a task at the server-end and
then sending the result to the client-end
Source: https://www.geeksforgeeks.org/web-scripting-and-its-types/
JavaScript
VRML
For example, ensure that values entered by the users satisfy some correctness checks
Executing programs at the client site speeds up interaction by avoiding may round trips to the server
Easy for limited capability scripting languages, harder for general purpose programming languages like Java
For example, Java's security system ensures that the Java applet code does not make any system calls directly
Notifies the user about potentially dangerous actions and allows the option to abort the program or to continue
execution
JavaScript
Week 7 Lecture 2 5
JavaScript very widely used
Forms basis of new generation of Web applications (called Web 2.0 applications) offering rich user interfaces
Modify the displayed web page, by altering the underlying Document Object Model (DOM) tree representation of
the displayed HTML text
Communicate with a web server to fetch data and modify the current page using fetched data, without needing to
reload/refresh the page
For example, on selecting a country in the drop-down menu, the list of states in the country is automatically
populated in a linked drop-down menu
JavaScript: Example
<html>
<head>
<script type="text/javascript">
function validate() {
var credits = document.getElementById("credits").value;
if (isNaN(credits) || credits <= 0 || credits >= 16) {
alert("Credits must be a number greater than 0 and less than 16");
return false;
}
}
</script>
</head>
<body>
<form action="createCourse" onsubmit="return validate()">
Title: <input type="text" id="title" size="20"><br />
Credits: <input type="text" id="credits" size="2"><br />
<Input type="submit" value="Submit">
</form>
</body>
</html>
Input values from HTML forms can be used directly in the embedded code/SQL queries
When the document is requested, the Web server executes the embedded code/SQL queries to generate the
actual HTML document
JSP, PHP
Servlets
Java Servlet specification defines an API for communication between the Web/application server and application
program running in the server
For example, methods to get parameter values from Web forms, and to send HTML text back to the client
Servlets: Example
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
Week 7 Lecture 2 6
public class PersonQueryServlet extends HttpServlet {
public void doGet(HttpServlet request, HttpServletResponse response)
throws ServletException IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<head><title>Query Result</title></head>");
out.println("<body>");
if (persontype.equals(”student”)) {
· · · code to find students with the specified name · · ·
· · · using JDBC to communicate with the database · · ·
out.println(”</table>”);
}
else {
· · · as above, but for instructors · · ·
}
out.println("</body>");
out.close();
}
}
Servlet: Sessions
Servlet API supports handling of sessions
Sets a cookie on first interaction with browser, and uses it to identify session on further interactions
if (request.getSession(false) == true)
authentication page
check login/password
session.getAttribute("userid", userid)
session.getAttribute("userid")
Servlet: Support
Servlets run inside application server such as
Java 2 Enterprise Edition (J2EE) platform supporting objects, parallel processing across multiple application
servers, etc
Week 7 Lecture 2 7
<html>
<head>
<title>Hello</title>
</head>
<body>
<% if (request.getParameter("name") == null)
{ out.println("Hello World"); }
else { out.println("Hello, " + request.getParameter("name")); }
%>
</body>
</html>
Such tags are likely library functions, can be used to build rich user interfaces such as paginated display of large
datasets
<html>
<head>
<title>Hello</title>
</head>
<body>
<? php if (!isset($_REQUEST['name']))
{ echo "Hello World"; }
else { echo "Hello, " + $_REQUEST['name']; }
?>
</body>
</html>
JSP is a servlet but it is more convenient to write and to modify regular HTML than to have a million println
The Web page design experts can build the HTML, leaving places for the servlet programmers to insert the
dynamic content
JSP vs JavaScript
"Client side" → JavaScript code is executed by the browser after the web server sends the HTTP response
With the exception of cookies, HTTP and form submission data is not available to JavaScript
Week 7 Lecture 2 8
"Server side" → Java Server Pages are executed by the web server before the web server sends the HTTP
response
Week 7 Lecture 2 9
📚
Week 7 Lecture 3
Class BSCCS2001
Materials
Module # 33
Type Lecture
Week # 7
Frameworks
Connectionist
Open DB Connectivity (ODBC) → works with C, C++, C#, Visual Basic and Python
OLEDB
ADO.NET
Embedding
Embedded SQL works with C, C++, C#, Java, COBOL, FORTRAN and Pascal
Week 7 Lecture 3 1
ODBC
Open DB Connectivity (ODBC) is a standard API for accessing DBMS
An application written using ODBC can be ported to other platforms, both on the client and the server side, with few
changes to the data access code
ODBC is
An API to
ODBC was originally developed by Microsoft and Simba Technologies during the early 1990s, and became the basis
for the Call Level Interface (CLI) standardized by SQL Access Group in the Unix and mainframe field
It creates a table, inserts data using literal and parameterized statements and fetches the data
import pyodbc
conn = pyodbc.connect('DSN=SQLS;UID=test01;PWD=test01')
cursor = conn.cursor()
while True:
row = cursor.fetchone()
if not row:
break
print(row)
while True:
row = cursor.fetchone()
if not row:
break
print(row)
Source: https://dzone.com/articles/tutorial-connecting-to-odbc-data-sources-with-pyth
JDBC
Week 7 Lecture 3 2
Java DB Connectivity (JDBC) is an API for the programming language Java, which defines how a client may access
a DB
JDBC supports a variety of features for querying and updating data, and for retrieving query results; metadata
retrieval, such as querying about relations present in the DB and the names and the types of relation attributes
Open a connection
Execute queries using the Statement object to send queries and fetch results
JDBC, original released by Sun Microsystems released as part of Java Development Kit (JDK) 1.1 on in 1997, is part
of Java Standard Edition platform, from Oracle corporation
JDBC: Example
We show a simple example here to connect to SQL server from Java using JDBC to execute DB commands
Then, using an SQL statement with the SQLServerStatement object, it runs the SQL statement and places the data that it
returns into a SQLServerResultSet object
Next, the sample code calls the custom displayRow method to iterate through the rows of data that are in the result
set, and uses the getString method to display some of the data
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
while (rs.next()) {
// Iterate on Table("ProductID", "Name")
System.out.println(rs.getString("ProductID") + " : " + rs.getString("Name"));
}
}
stmt.execute(sql);
sql = "INSERT Product_JDBC_Sample VALUES (’Adjustable Time’,’AR-5381’)"; // Add Product 1
stmt.execute(sql);
sql = "INSERT Product_JDBC_Sample VALUES (’ML Bottom Bracket’,’BB-8107’)"; // Add Product 2
Week 7 Lecture 3 3
stmt.execute(sql);
sql = "INSERT Product_JDBC_Sample VALUES (’Mountain-500 Black’,’BK-M18B-44’)"; // Add Product 3
stmt.execute(sql);
}
}
Programmers usually use such a bridge when they lack a source driver for some DB but have access to a target
driver
ODBC-to-JDBC (ODBC-JDBC) bridges → An ODBC-JDBC bridge consists of an ODBC driver which uses the
services of a JDBC driver to connect to a database
JDBC-to-ODBC (JDBC-ODBC) bridges → A JDBC-ODBC bridge consists of a JDBC driver which employs an
ODBC driver to connect to a target DB
OLE DB-to-ODBC bridges → An OLE DB-ODBC bridge consists of an OLE DB Provider which uses the services
of an ODBC function calls
ADO.NET-to-ODBC bridges → An ADO.NET-ODBC bridge consists of an ADO.NET Provider which uses the
services of an ODBC driver to connect to a target DB
Embedded SQL
The SQL standard defines embedding of SQL in a variety of programming languages such as C, C++, Java,
FORTRAN, and PL/1
A language to which SQL queries are embedded is referred to as a host language, and the SQL structures permitted
in the host language comprise embedded SQL
The basic form of these languages follow that of the System R embedding of SQL into PL/1
EXEC SQL (or similar alternate like #sql ) statement is used to identify embedded SQL request to the pre-processor
EXEC SQL <embedded SQL statement>;
Week 7 Lecture 3 4
In some languages, like COBOL, the semi-colon is replaced with END-EXEC
Before executing any SQL statements, the program must first connect to the DB
Variables of the host language can be used within embedded SQL statements
They are preceded by a colon (:) to distinguish from SQL variables (for example, :credit_amount)
Variables used as above must be declared within DECLARE section, as illustrated below
The syntax for declaring the variables, however, follows the usual host language syntax
int credit-amount;
Example
From within a host language, find the ID and name of the students who have completed more than the number of
credits stored in variable credit_amount in the host language
EXEC SQL
from student
END_EXEC
The variable c (used in the cursor definition) is used to identify the query
This statement causes the DB system to execute the query and to save the results within a temporary relation
The query uses the value of the host-language variable credit-amount at the time the open statement is executed
The fetch statement causes the values of one tuple in the query result to be placed on host language variables
A variable called SQLSTATE in the SQL communication area (SQLCA) gets set to '02000' to indicate no more data is
available
The close statement causes the DB system to delete the temporary relation that holds the result of the query
For example, the Java embedding defines Java iterators to step through result tuples
Can update tuples fetched by the cursor by declaring that the cursor is for update
EXEC SQL
Week 7 Lecture 3 5
select *
from instructor
for update
We then iterate through the tuples by performing fetch operations on the cursor (as illustrated earlier) and after
fetching each tuple we execute the following code
update instructor
where current of c
User one has granted select privileges to all on table sailor , so the bind step will be legal
The app takes one argument on the command line, a sailor's SID
It then finds the sailor SID's age out of the table ONE.SAILOR and reports it
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sqlenv.h>
#include <sqlcodes.h>
#include <sys/time.h>
#define EXIT 0
#define NOEXIT 1
EXEC SQL INCLUDE SQLCA; // Include DB2’s SQL error reporting facility.
EXEC SQL BEGIN DECLARE SECTION; // Declare the SQL interface variables.
// This macro prints the message in the SQLCA if the return code is 0 and the SQLCODE is not 0
#define PRINT_MESSAGE() { \
if (rc == 0) DUMP_SQLCA();
else printf("RC: %d\n",rc);
errcount += 1;
Week 7 Lecture 3 6
}
}
yuppy 22 1 20
lubber 31 1 25
guppy 44 2 31
rusty 58 3 47
Executed Successfully
Bye
int main() {
EXEC SQL INCLUDE SQLCA;
EXEC SQL BEGIN DECLARE SECTION;
int OrderID; /* Employee ID (from user) */
int CustID; /* Retrieved customer ID */
char SalesPerson[10] /* Retrieved salesperson name */
char Status[6] /* Retrieved order status */
EXEC SQL END DECLARE SECTION;
Week 7 Lecture 3 7
exit();
query_error:
printf ("SQL error: %ld\n", sqlca->sqlcode);
exit();
bad_number:
printf ("Invalid order number.\n");
exit();
}
Source: https://docs.microsoft.com/en-us/sql/odbc/reference/embedded-sql-example?view=sql-server-ver15
import java.sql.*;
import sqlj.runtime.*;
import sqlj.runtime.ref.*;
class App
{
/**********************
** Register Driver **
**********************/
static
{
try
{
Class.forName("com.ibm.db2.jdbc.app.DB2Driver").newInstance();
}
catch (Exception e)
{
e.printStackTrace();
}
}
/********************
** Main **
********************/
// URL is jdbc:db2:dbname
String url = "jdbc:db2:sample";
Week 7 Lecture 3 8
System.exit(1);
}
DefaultContext.setDefaultContext(ctx);
}
→ Declares column data types and names, and returns the values of the columns according to
App_Cursor1
App_Cursor2 → Declares column data types, and returns the values of the columns by column position (Positional
binding to columns)
Initialize the iterator → The iterator object cursor1 is initialized using the result of a query
Advance the iterator to the new row → The cursor1.next() method returns a Boolean false if there are no more
rows to retrieve
Move the data → The named accessor method empno() returns the value of the column named empno on the current
row
Week 7 Lecture 3 9
The named accessor method firstnme() returns the value of the column named firstnme on the current row
SELECT data into a host variable → The SELECT statement passes the number of rows in the table into the host
variable count1
Close the iterators → The close() method releases any resources held by the iterators
You should explicitly close iterators to ensure that system resources are released in a timely fashion
Initialize the iterator → The iterator object cursor2 is initialized using the result of a query
Retrieve the data → The FETCH statement returns the current value of the first column declared in the ByPos cursor
from the result table into the host variable str2
Check the success of a FETCH.INTO statement → The endFetch() method returns a Boolean true if the iterator is
not positioned on a row, that is, if the last attempt to fetch a row failed
The endFetch() method returns False if the last attempt to fetch a row was successful
Close the iterators → The close() method releases any resources held by the iterators
You should explicitly close iterators to ensure that system resources are released in a timely fashion
Week 7 Lecture 3 10
📚
Week 7 Lecture 4
Class BSCCS2001
Materials
Module # 34
Type Lecture
Week # 7
psycopg2
pg8000
py-postgresql
PyGreSQL
ocpgdb
bpgsql
SQLAlchemy
Source: https://pynative.com/python-postgresql-tutorial/
Package: psycopg2
Advantages of psycopg2
The following pip command installs psycopg2 on different OSs including Windows, Mac OS, Linux and Unix
pip install psycopg2
Create a cursor
Commit/rollback
Week 7 Lecture 4 1
Close the cursor
connection.close()
connection.cursor()
This routine creates a cursor which will be used throughout the program
cursor.close()
Python psycopg2 Module APIs: insert, delete, update & stored procedures
cursor.execute(sql [, optional parameters])
For example, cursor.execute("insert into people values (%s, %s)", (who, age))
cursor.executemany(sql, seq_of_parameters)
This routine executes an SQL command against all parameters sequences or mappings found in the sequence SQL
cursor.callproc(procname[, parameters])
This routine executes a stored database procedure with the given name
The sequence of parameters must contain one entry for each argument that the procedure expects
cursor.rowcount()
This is a read-only attribute which returns the total number of DB rows that have been modified, inserted or deleted by the last execute()
This method fetches the next row of a query result set, returning a single sequence, or None when no more data is available
cursor.fetchmany([size=cursor.arraysize])
This routine fetches the next set of rows of a query result, returning a list
An empty list is returned when no more rows are available
The method tries to fetch as many rows as indicted by the size parameter
cursor.fetchall()
This routine fetches all (remaining) rows of a query result, returning a list
connection.rollback()
This method rolls back any changes to the DB since the last call to commit()
Week 7 Lecture 4 2
Source: https://www.tutorialspoint.com/postgresql/postgresql_python.htm
import psycopg2
try:
# Connect to the PostgreSQL DB
conn = psycopg2.connect(database = dbname, user = usrname, password = pwd, host = address, port = portnum)
print("Database connected successfully")
except(Exception, psycopg2.DatabaseError) as error:
print(error)
finally:
# Close the connection
conn.close()
Output
Database connected successfully
psycopg2.DatabaseError → Exception raised for errors that are related to the PostgreSQL DB
Username → myuser
Password → mypass
Create a cursor object using the cursor() method of the connection object
The execute() methods run the SQL commands and return the result
Use commit() to make the changes in the DB persistent, or use rollback() to revert the DB changes
Use cursor.close() and connection.close() method to close the cursor and the PostgreSQL connection
import psycopg2
def createTable():
conn = None
try:
conn = psycopg2.connect(database = "mydb", user = "myuser", password = "mypass", host = "127.0.0.1", port = "5432")
createTable()
Output (if the table EMPLOYEE does not exist) → Table created successfully
Output (if the table EMPLOYEE already exists) → relation "employee" already exists
import psycopg2
try:
# Connect to the PostgreSQL DB
conn = psycopg2.connect(database = "mydb", user = "myuser", password = "mypass", host = "127.0.0.1", port = "5432")
cur = conn.cursor() # Create a new cursor
Week 7 Lecture 4 3
conn.commit() # Commit the changes to the DB
print ("Total number of rows inserted :", cur.rowcount);
cur.close() # close the cursor
except (Exception, psycopg2.DatabaseError) as error:
print(error)
finally:
if conn is not None:
conn.close()
Output (if a row already exists with the emp_num = 110) → duplicate key value violates unique constraint "employee_pkey" DETAIL: Key (emp_num)=(110)
already exists.
import psycopg2
def deleteRecord(num):
conn = None
try:
# Connect to the PostgreSQL DB
conn = psycopg2.connect(database = "mydb", user = "myuser", password = "mypass", host = "127.0.0.1", port = "5432")
cur = conn.cursor() # Create a new cursor
deleteRecord(110)
Output (If the row does not exist) → Total number of rows deleted: 0
import psycopg2
try:
# Connect to the PostgreSQL DB
conn = psycopg2.connect(database = "mydb", user = "myuser", password = "mypass", host = "127.0.0.1", port = "5432")
cur = conn.cursor() # Create a new cursor
updateRecord(110, "Finance")
Output (If the row does not exist) → Total number of rows updated: 0
import psycopg2
def selectAll():
conn = None
try:
# Connect to the PostgreSQL DB
conn = psycopg2.connect(database = "mydb", user = "myuser", password = "mypass", host = "127.0.0.1", port = "5432")
cur = conn.cursor() # Create a new cursor
selectAll()
Output →
Week 7 Lecture 4 4
Employee ID = 110, NAME = Bhaskar, DEPARTMENT = HR
JSON
E-mail processing
Beautiful Soup → an HTML parser that can handle all sorts of HTML
Source: https://www.python.org/about/apps/
It is desired to make getting started quick and easy, with the ability to scale up to complex applications
It began as a simple wrapper around Werkzeug (Werkzeug WSGI toolkit) and Jinja (Jinja templating engine) and has since then become one of
the most popular Python web application frameworks
Flask offers suggestions, but does not enforce any dependencies or project layouts
It is up to the developer to choose the tools and libraries they want to use
There are many extensions provided by the community that make adding new functionality easy
Source: https://pypi.org/project/Flask/
A simple example
@app.route('/')
def hello_world():
return "Hello, World!"
if __name__ == '__main__':
app.run()
Flask constructor takes the name of the current module (__name__) as argument
The route() function of the Flask class is a decorator, which tells the application which URL should call the associated function
app.route(rule, options)
Hence, when the home page of web server is opened in the browser, the output of this function will be rendered
Finally, the run() method of Flask class runs the application on the local development server
Source: https://www.tutorialspoint.com/flask/flask_application.htm
Week 7 Lecture 4 5
host → Hostname to listen on
python hello.py
Output
Python: Flask
Consider the table Candidate (in PostgreSQL) as shown below:
if __name__ == '__main__':
app.run(host='127.0.0.1', debug=True, port=5000)
<!DOCTYPE html>
<html>
<head>
<title>Candidate Email DB</title>
</head>
<body>
<h2>Candidate Email DB</h2>
<a href="/add">Add Email</a><br><br>
<a href="/viewall">View Email</a>
</body>
</html>
@app.route("/")
def index():
return render_template("index.html")
@app.route("/add")
def add():
return render_template("add.html")
Week 7 Lecture 4 6
Source code for add.html
<!DOCTYPE html>
<html>
<head>
<title>Add Email</title>
</head>
<body>
<h2>Email Information</h2>
<form action = "/savedetails" method="post">
<table>
<tr><td>CNO</td><td><input type="text" name="cno" required></td></tr>
<tr><td>Name</td><td><input type="text" name="name" required></td></tr>
<tr><td>Email</td><td><input type="text" name="email" required></td></tr>
<tr><td><input type="submit" value="Submit"></td></tr>
</table>
</form>
</body>
</html>
@app.route("/savedetails",methods = ["POST"])
def saveDetails():
cno = request.form["cno"]
name = request.form["name"]
email = request.form["email"]
conn = None
try:
conn = psycopg2.connect(database = "mydb", user = "myuser", password = "mypass", host = "127.0.0.1", port = "5432") # connect to the PostgreSQL database
cur = conn.cursor() # Create a new cursor
cur.execute("INSERT INTO Candidate (cno, name, email) VALUES (%s, %s, %s)", (cno, name, email)) # Execute the INSERT statement
conn.commit() # Commit the changes to the DB
cur.close() # Close the cursor
except (Exception, psycopg2.DatabaseError) as error:
render_template("fail.html")
finally:
if conn is not None:
conn.close() # Close the connection
return render_template("success.html")
@app.route("/viewall")
def viewAll():
conn = None
try:
# Connect to the PostgreSQL DB
Week 7 Lecture 4 7
conn = psycopg2.connect(database = "mydb", user = "myuser", password = "mypass", host = "127.0.0.1", port = "5432")
cur = conn.cursor() # Create a new cursor
<!DOCTYPE html>
<html>
<head>
<title>Email List</title>
</head>
<body>
<h3>Email List</h3>
<table border=5>
<tr>
<th>CNO</td><th>Name</td><th>Email</td>
</tr>
{% for row in rows %}
<tr>
<td>{{row[0]}}</td> <td>{{row[1]}}</td> <td>{{row[2]}}</td>
</tr>
{% endfor %}
</table>
<br><br>
<a href="/">Go Home</a>
</body>
</html>
Week 7 Lecture 4 8
📚
Week 7 Lecture 5
Class BSCCS2001
Materials
Module # 35
Type Lecture
Week # 7
Automatically generate code for the user interface from a declarative specification
Used as part of Rapid Application Development (RAD) tools even before Web
RAD software is an agile model that focuses on fast prototyping and quick feedback in app development to ensure
speedier delivery and an efficient result
App development has 4 phases → business modeling, data modeling, process modeling and testing & turnover
Defining the requirements, Prototyping, Receiving feedback and Finalizing the software
With RAD, the time between prototypes and iterations is short, and integration occurs since inception
A set of APIs for representing UI components and managing the state, handling the events and input
validation, defining page navigation and supporting internationalization and accessibility
Week 7 Lecture 5 1
JSP custom tag library for expressing a JSF interface within a JSP page
Ruby on Rails
Allows easy creation of simple CRUD (Create, Read, Update, Delete) interfaces by code generation from DB
schema or object model
G Suite
Microsoft Azure
For example, menus and list boxes can be associated with DataSet object
User actions such as selecting a value from a menu can be associated with actions at server
DataGrid provides convenient way of displaying SQL query results in a tabular format
May be accessed by millions of users every day, thousands of requests per second at peak time
Caching techniques used to reduce cost of serving pages by exploiting commonalities between requests
"select * from instructor where name = '" + "X' or 'Y' = 'Y" + "'"
Which is ...
Week 7 Lecture 5 2
X'; update instructor set salary = salary + 10000; - -
Normally, web server will execute, but not provide source of scripts files such as file.jsp or file.php , but
source of editor backup files such as file.jsp~ , or .file.jsp.swp may be server
Restrict access to DB server from IPs of machine running the application servers
Two-factor authentication
Device generates a new pseudo-random number every minute and displays to users
Application server generates same sequence of pseudo-random number to check that the number is correct
Problem 2 → SQL authorization is at the level of tables, or columns of tables, but not to specific rows of a table
SELECT *
FROM takes
Oracle Virtual Private DB (VPD) allows predicates to be added transparently to all the SQL queries, to enforce
find-grained authorization
For example, add ID = sys_context.user_id() to all queries on student relation if user is a student
Week 7 Lecture 5 3
Application Security: Audit Trails
Applications must log actions to an audit trail, to detect who carried out an update, or accessed some sensitive data
DB level, and at
Application level
Scalability
Performance
Security
Designed with consideration for the demands and constraints of the devices and also to take advantage of any
specialized capabilities
Cons
Limited memory
Limited power
Limited bandwidth
Pros
Can also access mobile-specific features such as click-to-call (to dial a number) or location-based mapping
Mobile apps
Users download apps from device-specific portals such as App Store, Google Play Store
Pull content and data from the internet, in a similar fashion to a website or
Week 7 Lecture 5 4
Architecture of Mobile App
Typically 3 tier
Presentation
Business
Data
Local data
Remote data
Android
iOS
Windows
iOS → Objective-C
Powered via Web programming languages → Ruby on Rails, JavaScript, PHP or Python
Attempts to use redundant, common code that can be used across platforms
Design Issues
Week 7 Lecture 5 5
Determine Device
Consider bandwidth
Select Technology
Select Navigation
Maintain Flow
Week 7 Lecture 5 6