Professional Documents
Culture Documents
Ece Unit 4 - Fundamentals of Python Programming
Ece Unit 4 - Fundamentals of Python Programming
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:-
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.
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]
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.
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.
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
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