Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 31

SATHYABAMA

INSTITUTE OF SCIENCE AND TECHNOLOGY

B.E - ECE - IV SEM


SCSA1102 – FUNDAMENTALS OF PYTHON PROGRAMMING

UNIT – IV – DATABASE AND NETWORK


Mr. R. Immanuel Rajkumar
&
Dr.Annadevi
DEPARTMENT OF ECE
1
PYTHON (SCSA1102)
SYLLABUS

2
DATABASE AND NETWORK
Socket Programming in Python:-

3
https://realpython.com/python-sockets/
DATABASE AND NETWORK
Socket Programming in Python:-
 Sockets and the socket API are used to send messages across a
network.
 They provide a form of inter-process communication (IPC).
 The network can be a logical, local network to the computer, or one
that’s physically connected to an external network, with its own
connections to other networks.
 The obvious example is the Internet, which you connect to via your
ISP.

4
https://realpython.com/python-sockets/
DATABASE AND NETWORK
Socket Programming in Python:-

5
https://www.youtube.com/watch?v=T0rYSFPAR0A&t=925s
DATABASE AND NETWORK
Socket Programming in Python:-

6
https://www.youtube.com/watch?v=T0rYSFPAR0A&t=925s
DATABASE AND NETWORK
Socket Programming in Python:-

7
https://www.youtube.com/watch?v=T0rYSFPAR0A&t=925s
DATABASE AND NETWORK
Socket Programming in Python:-

8
https://www.youtube.com/watch?v=T0rYSFPAR0A&t=925s
DATABASE AND NETWORK
Socket API:-

 Python’s socket module provides an interface to the 


Berkeley
Thesockets
primaryAPI.
socket API functions and methods in this module are:

socket()
bind()
listen()
accept()
connect()
connect_ex()
send()
recv()
close()
9
https://realpython.com/python-sockets/
DATABASE AND NETWORK
Socket API:-

10
https://realpython.com/python-sockets/
DATABASE AND NETWORK
Socket API:-
In the diagram below, let’s look at the sequence
of socket API calls and data flow for TCP:
The left-hand column represents the server. On the right-hand side is the
client.
Starting in the top left-hand column, note the API calls the server makes to
setup a “listening” socket:
socket()
bind()
listen()
accept()
A listening socket does just what it sounds like. It listens for connections
from clients. When a client connects, the server calls accept() to accept, or
complete, the connection.

The client calls connect() to establish a connection to the server and


initiate the three-way handshake. The handshake step is important since it
ensures that each side of the connection is reachable in the network, in
other words that the client can reach the server and vice-versa. It may be
that only one host, client or server, can reach the other. 11
https://realpython.com/python-sockets/
DATABASE AND NETWORK
Socket API:-
In the diagram below, let’s look at the sequence
of socket API calls and data flow for TCP:
socket.socket() creates a socket object that supports the 
context manager type, so you can use it in a with statement. 
bind() is used to associate the socket with a specific network interface and
port number:
listen() enables a server to accept() connections. It makes it a “listening”
socket:
accept() blocks and waits for an incoming connection. When a client
connects, it returns a new socket object representing the connection and a
tuple holding the address of the client.
 connect() to establish a connection to the server 
close() also removes the socket from being monitored
close() will take care of the cleanup

12
https://realpython.com/python-sockets/
DATABASE AND NETWORK

Server.py:- Client.py:-
import socket import socket
s=socket.socket() c=socket.socket()
print('socket created') c.connect(('localhost',9999))
s.bind(('localhost',9999)) name=input("Enter Your Name : ")
s.listen(3) c.send(bytes(name,'utf-8'))
print('waiting for connections') print(c.recv(1024).decode())
while True:
c,addr=s.accept()
name=c.recv(1024).decode()
print("connected with : ",addr, name)
c.send(bytes('welcome to MyServer','utf-8'))
c.close()

13
https://realpython.com/python-sockets/
DATABASE AND NETWORK
Server.py:- Client.py:-
import socket
import os import socket
from _thread import *
ServerSocket = socket.socket() ClientSocket = socket.socket()
ThreadCount = 0
try:
host = 'localhost'
ServerSocket.bind(('localhost',9999)) port = 9999
except socket.error as e:
print(str(e))
print('Waiting for connection')
print('Waitiing for a Connection..') try:
ServerSocket.listen(5)
def threaded_client(connection):
ClientSocket.connect((host, port))
connection.send(str.encode('Welcome to the Servern')) except socket.error as e:
while True:
data = connection.recv(2048)
print(str(e))
reply = 'Server Says: ' + data.decode('utf-8')
print("Server Replied to client as :"+reply)
if not data:
Response = ClientSocket.recv(1024)
break while True:
connection.sendall(str.encode(reply)) Input = input('Say Something: ')
connection.close()
while True: ClientSocket.send(str.encode(Input))
Client, address = ServerSocket.accept() Response = ClientSocket.recv(1024)
print('Connected to: ' + address[0] + ':' + str(address[1]))
start_new_thread(threaded_client, (Client, )) print(Response.decode('utf-8'))
ThreadCount += 1 ClientSocket.close()
print('Thread Number: ' + str(ThreadCount))
ServerSocket.close()
14
https://realpython.com/python-sockets/
DATABASE AND NETWORK
Server.py:- Broadcasting means sending a message to all connected
clients. We can send the message to all the connected clients,
import socket
to clients on a namespace and clients in a particular room
from time import sleep

def main():
interfaces = socket.getaddrinfo(host='localhost', port=9999, family=socket.AF_INET)
allips = [ip[-1][0] for ip in interfaces]

msg = b'hello world' Client.py:-


while True:
import socket
for ip in allips: sock = socket.socket(socket.AF_INET,
print(f'sending on {ip}')
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.SOCK_DGRAM)
socket.IPPROTO_UDP) # UDP sock.setsockopt(socket.SOL_SOCKET,
sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) socket.SO_BROADCAST, 1)
sock.bind((ip,0))
sock.bind(("0.0.0.0", 5005))
sock.sendto(msg, ("255.255.255.255", 5005))
sock.close() while True:
# sock.sendto(bytes("hello", "utf-8"), ip_co)
sleep(2) data, addr = sock.recvfrom(1024)
print(data)
main()
15
https://realpython.com/python-sockets/
DATABASE AND NETWORK
What is NoSQL?:-
 NoSQL databases (aka "not only SQL") are non tabular, and store data
differently than relational tables.
 NoSQL databases come in a variety of types based on their data model. The
main types are document, key-value, wide-column, and graph.
 They provide flexible schemas and scale easily with large amounts of data
and high user loads.

16
https://www.mongodb.com/nosql-explained
DATABASE AND NETWORK
What is NoSQL?:-
 When people use the term “NoSQL database”, they typically use it to refer
to any non-relational database. Some say the term “NoSQL” stands for “non
SQL” while others say it stands for “not only SQL.” Either way, most agree
that NoSQL databases are databases that store data in a format other than
relational tables.
 A common misconception is that NoSQL databases or non-relational
databases don’t store relationship data well. NoSQL databases can store
relationship data—they just store it differently than relational databases do.
In fact, when compared with SQL databases, many find modeling
relationship data in NoSQL databases to be easier than in SQL databases,
because related data doesn’t have to be split between tables.
17
https://www.mongodb.com/nosql-explained
DATABASE AND NETWORK
What is NoSQL?:-

 NoSQL data models allow related data to be nested within a single data
structure.

 NoSQL databases emerged in the late 2000s as the cost of storage


dramatically decreased. Gone were the days of needing to create a complex,
difficult-to-manage data model simply for the purposes of reducing data
duplication. Developers (rather than storage) were becoming the primary
cost of software development, so NoSQL databases optimized for developer
productivity.
18
https://www.mongodb.com/nosql-explained
DATABASE AND NETWORK
What is SQL?:-
 Relational databases accessed by SQL (Structured Query Language). You can use SQL
when interacting with relational databases where data is stored in tables that have fixed
columns and rows.
 SQL databases rose in popularity in the early 1970s. At the time, storage was extremely
expensive, so software engineers normalized their databases in order to reduce data
duplication.
 Software engineers in the 1970s also commonly followed the waterfall software
development model. Projects were planned in detail before development began.
Software engineers painstakingly created complex entity-relationship (E-R) diagrams to
ensure they had carefully thought through all the data they would need to store. Due to
this upfront planning model, software engineers struggled to adapt if requirements
changed during the development cycle. As a result, projects frequently went over
budget, exceeded deadlines and failed to deliver against user needs. 19
https://www.mongodb.com/nosql-explained
DATABASE AND NETWORK
What are the Types of NoSQL Databases?:-
 Over time, four major types of NoSQL databases emerged: document databases, key-
value databases, wide-column stores, and graph databases.
Document Databases :-
 Document databases store data in documents similar to JSON (JavaScript Object
Notation) objects. Each document contains pairs of fields and values. The values can
typically be a variety of types including things like strings, numbers, booleans, arrays, or
objects, and their structures typically align with objects developers are working with in
code. Because of their variety of field value types and powerful query languages,
document databases are great for a wide variety of use cases and can be used as a
general purpose database. They can horizontally scale-out to accomodate large data
volumes. MongoDB is consistently ranked as the world’s most popular NoSQL database
according to DB-engines and is an example of a document database.
20
https://www.mongodb.com/nosql-explained
DATABASE AND NETWORK
What are the Types of NoSQL Databases?:-
KEY-VALUE Databases :-
 Key-value databases are a simpler type of database where each item contains keys and
values.
 A value can typically only be retrieved by referencing its key, so learning how to query for
a specific key-value pair is typically simple.
 Key-value databases are great for use cases where you need to store large amounts of
data but you don’t need to perform complex queries to retrieve it.
 Common use cases include storing user preferences or caching. Redis and DynamoDB
are popular key-value databases.

21
https://www.mongodb.com/nosql-explained
DATABASE AND NETWORK
What are the Types of NoSQL Databases?:-
Wide-column Databases :-
 Wide-column stores store data in tables, rows, and dynamic columns. Wide-column
stores provide a lot of flexibility over relational databases because each row is not
required to have the same columns.
 Many consider wide-column stores to be two-dimensional key-value databases. Wide-
column stores are great for when you need to store large amounts of data and you can
predict what your query patterns will be.
 Wide-column stores are commonly used for storing Internet of Things data and user
profile data. Cassandra and HBase are two of the most popular wide-column stores.

22
https://www.mongodb.com/nosql-explained
DATABASE AND NETWORK
What are the Types of NoSQL Databases?:-
Graph Databases :-
 Graph databases store data in nodes and edges. Nodes typically store information about
people, places, and things while edges store information about the relationships
between the nodes.
 Graph databases excel in use cases where you need to traverse relationships to look for
patterns such as social networks, fraud detection, and recommendation engines. Neo4j
and JanusGraph are examples of graph databases.

23
https://www.mongodb.com/nosql-explained
DATABASE AND NETWORK
How NoSQL Databases Work?:-

24
https://www.mongodb.com/nosql-explained
DATABASE AND NETWORK
Python - NoSQL Databases?:-
 As more and more data become available as unstructured or semi-structured, the need
of managing them through NoSql database increases.
 Python can also interact with NoSQL databases in a similar way as is interacts with
Relational databases.
 In order to connect to MongoDB, python uses a library known as pymongo. You can add
this library to your python environment, using the below command from the Anaconda
environment.

 pip install pymongo

25
https://www.mongodb.com/nosql-explained
DATABASE AND NETWORK
Inserting Data:-
 To insert data into MongoDB we use the insert() method which is available in the
database environment. First we connect to the db using python code shown below and
then we provide the document details in form of a series of key-value pairs.
# Import the python libraries
from pymongo import MongoClient
from pprint import pprint
# Choose the appropriate client
client = MongoClient()
# Connect to the test db
db=client.test
# Use the employee collection
employee = db.employee
employee_details = {'Name': 'Raj Kumar‘, 'Address': 'Sears Streer, NZ','Age': '42'}
# Use the insert method
#result = employee.insert_one(employee_details)
#result = employee.insert_one({ 'Name': 'Jeba','Address': 'Jeppiaar Nagar, Chennai','Age': '12'})
# Query for the inserted document.
#Queryresult = employee.find_one({'Age': '12'})
Queryresult = employee.find().forEach(printjson)
#db.employee.find().forEach(printjson)
pprint(Queryresult)
26
https://www.mongodb.com/nosql-explained
DATABASE AND NETWORK
Read Database:-
 To Read data into MongoDB we use the find() method which is available in the database
environment used to find db and print by query.

import pprint
from pymongo import MongoClient

with MongoClient() as client:


db = client.test
for doc in db.employee.find():
pprint.pprint(doc)

27
https://www.mongodb.com/nosql-explained
DATABASE AND NETWORK
Delete Database:-
 Deleting a record is also straight forward where we use the delete method. Here also we
mention the condition which is used to choose the record to be deleted.
# Import the python libraries
from pymongo import MongoClient
from pprint import pprint
# Choose the appropriate client
client = MongoClient()
# Connect to db
db=client.test
employee = db.employee
# Use the condition to choose the record
# and use the delete method
db.employee.delete_one({"Age":‘12'})
Queryresult = employee.find_one({'Age':‘12'})
pprint(Queryresult)
28
https://www.mongodb.com/nosql-explained
DATABASE AND NETWORK
MultiThreading:-  Multithreading is a model of program execution that
allows for multiple threads to be created within a process,
# Import Module executing independently but concurrently sharing process
from tkinter import *
import time resources. Depending on the hardware, threads can run
from threading import * fully parallel if they are distributed to their own CPU core.
# Create Object
from tkinter import *
root = Tk() import time
# Set geometry from threading import *
root.geometry("400x400") root = Tk()
def work(): root.geometry("400x400")
print("sleep time start") def threading():
for i in range(10): # Call work function
t1=Thread(target=work)
print(i)
t1.start()
time.sleep(1) def work():
print("sleep time stop") print("sleep time start")
# Create Button for i in range(10):
Button(root, text="Click Me", command=work).pack() print(i)
# Execute Tkinter time.sleep(1)
root.mainloop() print("sleep time stop")
Button(root,text="Click Me",command = threading).pack()
root.mainloop()
29
https://www.mongodb.com/nosql-explained
DATABASE AND NETWORK
Show GIF Images:-
def stop_animation():
import tkinter as tk root.after_cancel(anim)
from PIL import Image
root = tk.Tk() gif_label = tk.Label(root,image="")
gif_label.pack()
file="speaker4.gif"
start =
info = Image.open(file) tk.Button(root,text="start",command=lambda :animation(count))
frames = info.n_frames # gives total number of frames that gif contains start.pack()
# creating list of PhotoImage objects for each frames stop = tk.Button(root,text="stop",command=stop_animation)
im = [tk.PhotoImage(file=file,format=f"gif -index {i}") for i in range(frames)] stop.pack()
count = 0
anim = None root.mainloop()
def animation(count):
global anim
im2 = im[count]
gif_label.configure(image=im2)
count += 1
if count == frames:
count = 0
anim = root.after(50,lambda :animation(count))

30
https://www.mongodb.com/nosql-explained
DATABASE AND NETWORK
Show GIF Images with Multithreading:-
import tkinter as tk def animation(count):
from PIL import Image global anim
from threading import * im2 = im[count]
gif_label.configure(image=im2)
root = tk.Tk()
count += 1
file="speaker4.gif" if count == frames:
info = Image.open(file) count = 0
frames = info.n_frames # gives total number of frames that gif contains anim = root.after(50,lambda :animation(count))
# creating list of PhotoImage objects for each frames
im = [tk.PhotoImage(file=file,format=f"gif -index {i}") for i in range(frames)] def stop_animation():
count = 0 root.after_cancel(anim)
anim = None
gif_label = tk.Label(root,image="")
def threading(): gif_label.pack()
# Call work function start = tk.Button(root,text="start",command=threading)
t1=Thread(target=animation(count)) start.pack()
t1.start() stop = tk.Button(root,text="stop",command=stop_animation)
def appenddata(): stop.pack()
filename=E1.get()+".txt" stopy = tk.Button(root,text="stop",command=appenddata)
stopy.pack()
print(filename)
root.after(50, appenddata) root.mainloop()
31
https://www.mongodb.com/nosql-explained

You might also like