Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
100% found this document useful (1 vote)
33 views

Module 4 Python Integration Primer

This document provides an overview of GUI development, networking, and database connectivity in Python. It includes examples of creating GUI elements like windows, buttons, labels and canvases using Tkinter. Networking concepts like sockets, URLs and downloading web resources are demonstrated. Database integration is mentioned but not shown.

Uploaded by

Megha Trivedi
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
33 views

Module 4 Python Integration Primer

This document provides an overview of GUI development, networking, and database connectivity in Python. It includes examples of creating GUI elements like windows, buttons, labels and canvases using Tkinter. Networking concepts like sockets, URLs and downloading web resources are demonstrated. Database integration is mentioned but not shown.

Uploaded by

Megha Trivedi
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 28

Module 4 Python Integration Primer

Graphical User interface, Networking in Python, Python database connectivity, Introduction


to Django

GUI using Python


Creating root window with option Pg 571 Pb. 2
from tkinter import *

from tkinter import font

root=Tk()

root.title("My window")

root.geometry("400x300")

root.wm_iconbitmap('image.ico')

root.mainloop()

creating various shapes in canvas pg 578 pb 4

from tkinter import *

root=Tk()

c=Canvas(root, bg="blue", height=700, width=1200, cursor="pencil")

id=c.create_line(50,50,200,50,200,150,width=4, fill="white")

id=c.create_oval(100,100,400,400,width=5, fill="yellow", outline="red", activefill="lightblue")

id=c.create_rectangle(500,200,700,600,width=2, fill="gray", outline="black", activefill="yellow")

fnt=('Times', 40,'bold italic underline')

id=c.create_text(500,100, text="My canvas",font=fnt, fill="yellow", activefill="green")

# add canvas to the root window

c.pack()

root.mainloop()

create a frame in root window


from tkinter import *

root=Tk()
root.title("My frame")

f=Frame(root, height=400,width=500, bg="yellow", cursor="cross")

f.pack()

root.mainloop()

Widgets

Create a push button and bind it with an event handler Pg.588 Pb. 9
from tkinter import *

def buttonClick(self):

print('You have clicked me')

root=Tk()

f=Frame(root, height=200, width=300)

f.propagate(0)

f.pack()

b=Button(f, text='My Button', width=15, height=2, bg='yellow', fg='blue', activebackground='green',


activeforeground='red')

b.pack()

b.bind("<Button-1>", buttonClick)

root.mainloop()

Create a push button and bind it with an event handler using command option Pg.589 Pb.
10
from tkinter import *

class MyButton:

def __init__(self,root):

self.f=f=Frame(root, height=200, width=300)

self.f.propagate(0)

self.f.pack()

self.b=Button(self.f, text='My Button', width=15, height=2, bg='yellow',fg='blue',


activebackground='green', activeforeground='red', command=self.buttonClick)

self.b.pack()
def buttonClick(self):

print('You have clicked me')

root=Tk()

mb=MyButton(root)

root.mainloop()

create 3 push buttons and change the background of the frame according to the button
clicked by the user pg 591 Pb. 13
from tkinter import *

class MyButton:

def __init__(self,root):

self.f=Frame(root, height=200, width=300)

self.f.propagate(0)

self.f.pack()

self.b1=Button(self.f, text='Red', width=15, height=2, command=lambda: self.buttonClick(1))

self.b2=Button(self.f, text='Green', width=15, height=2, command=lambda: self.buttonClick(2))

self.b3=Button(self.f, text='Blue', width=15, height=2, command=lambda: self.buttonClick(3))

self.b1.pack()

self.b2.pack()

self.b3.pack()

def buttonClick(self,num):

if num==1:

self.f["bg"]='red'

if num==2:

self.f["bg"]='green'

if num==3:

self.f["bg"]='blue'

root=Tk()
mb=MyButton(root)

root.mainloop()

Example to explain pack, grid and place

from tkinter import *

class MyButton:

def __init__(self,root):

self.f=Frame(root, height=400, width=400)

self.f.propagate(0)

self.f.pack()

self.b1=Button(self.f, text='Red', width=15, height=2, command=lambda: self.buttonClick(1))

self.b2=Button(self.f, text='Green', width=15, height=2, command=lambda: self.buttonClick(2))

self.b3=Button(self.f, text='Blue', width=15, height=2, command=lambda: self.buttonClick(3))

self.b4=Button(self.f, text='White', width=15, height=2, command=lambda: self.buttonClick(4))

self.b1.pack(side=LEFT, padx=10,pady=15)

self.b2.pack(side=LEFT, padx=10,pady=15)

self.b3.pack(side=RIGHT, padx=10,pady=15)

self.b4.pack(side=RIGHT, padx=10,pady=15)

def buttonClick(self,num):

if num==1:

self.f["bg"]='red'

if num==2:

self.f["bg"]='green'

if num==3:

self.f["bg"]='blue'

if num==4:

self.f["bg"]='white'

root=Tk()

mb=MyButton(root)

root.mainloop()
Label in Python
from tkinter import *

root = Tk()

root.geometry('250x150')

# This will create a LabelFrame

label_frame = LabelFrame(root, text='This is Label Frame')

label_frame.pack(expand='yes', fill='both')

label1 = Label(label_frame, text='1. This is a Label.')

label1.place(x=0, y=5)

label2 = Label(label_frame, text='2. This is another Label.')

label2.place(x=0, y=35)

label3 = Label(label_frame, text='3. We can add multiple\n widgets in it.')

label3.place(x=0, y=65)

root.mainloop()

Textbox in Python
from tkinter import *

ws = Tk()

ws.title('Welcome')

ws.geometry('400x300')

ws.config(bg='blue')

message ='Welcome to VCET'


text_box = Text(ws,height=12,width=40)

text_box.pack(expand=True)

text_box.insert('end', message)

text_box.config(state='disabled')

ws.mainloop()

Radio button in Python


# Importing Tkinter module

from tkinter import *

# from tkinter.ttk import *

# Creating master Tkinter window

master = Tk()

master.geometry("175x175")

# Tkinter string variable

# able to store any string value

v = StringVar(master, "1")

# Dictionary to create multiple buttons

values = {"RadioButton 1" : "1",

"RadioButton 2" : "2",

"RadioButton 3" : "3",

"RadioButton 4" : "4",

"RadioButton 5" : "5"}

# Loop is used to create multiple Radiobuttons

# rather than creating each button separately

for (text, value) in values.items():


Radiobutton(master, text = text, variable = v,

value = value, indicator = 0,

background = "light blue").pack(fill = X, ipady = 5)

# Infinite loop can be terminated by

# keyboard or mouse interrupt

# or by any predefined function (destroy())

mainloop()

Checkbutton
from tkinter import *

root = Tk()

root.geometry("300x200")

w = Label(root, text ='Select the programming language', font = "50")

w.pack()

Checkbutton1 = IntVar()

Checkbutton2 = IntVar()

Checkbutton3 = IntVar()

Button1 = Checkbutton(root, text = "C++",

variable = Checkbutton1,

onvalue = 1,

offvalue = 0,

height = 2,

width = 10)

Button2 = Checkbutton(root, text = "Java",

variable = Checkbutton2,
onvalue = 1,

offvalue = 0,

height = 2,

width = 10)

Button3 = Checkbutton(root, text = "Python",

variable = Checkbutton3,

onvalue = 1,

offvalue = 0,

height = 2,

width = 10)

Button1.pack()

Button2.pack()

Button3.pack()

mainloop()

Networking in Python
Interconnection of Computers is called as network
Sharing of resources
Server-client
Requirements: Hardware, Software, Protocol
TCP/IP: transmission Control Protocol/ Internet Protocol
Socket:
Logical connecting point between a server and client is called Socket.
Establishing connection between server and client through socket is called Socket
Programming

Host name and IP address of a computer on Network

import socket
hostname = socket.gethostname()

IPAddr = socket.gethostbyname(hostname)

print("Your Computer Name is:" + hostname)

print("Your Computer IP Address is:" + IPAddr)

Your Computer Name is:LAPTOP-SUD985C6

Your Computer IP Address is:127.0.0.1

URL: Uniform Resource Locator represents the address that is specified to access some information
or resource on Internet

URL has four parts:

1. The protocol (http:// - HyperText Transfer Protocol)


2. Server name or IP address
3. Port number -optional, 80
4. File to be reffered

Different parts of url

Sceheme=protocol

Netloc=location of the network

Path=path of the web page

Port=port number

import urllib.parse

url='https://vcet.edu.in/computer-engineering/'

tpl=urllib.parse.urlparse(url)

print(tpl)

print('Scheme = ', tpl.scheme)

print('Network Loacation= ',tpl.netloc)

print('Path= ', tpl.path)

print('Parameters= ', tpl.params)

print('Port number= ', tpl.port)

print('Total url= ',tpl.geturl())


Scheme = https

Network Loacation= vcet.edu.in

Path= /computer-engineering/

Parameters=

Port number= None

Total url= https://vcet.edu.in/computer-engineering/

Reading source code of a webpage

import urllib.request

file=urllib.request.urlopen("https://www.python.org/")

print(file.read())

Downloading Webpage from Internet

import urllib.request

try:

file=urllib.request.urlopen("https://python.org/")

content=file.read()

except urllib.error.HTTPError:

print('The Webpage does not exsist')

exit()

f=open('myfile.html','wb')

f.write(content)

f.close()

Download image from internet

import urllib.request

from PIL import Image


# Python Image Library

# Retrieving the resource located at the URL

# and storing it in the file name a.jpeg

url = "https://www.iitb.ac.in/sites/www.iitb.ac.in/files/styles/gallery_item/public/
GoldenOriole.jpeg"

urllib.request.urlretrieve(url, "myimage.jpeg")

# Opening the image and displaying it (to confirm its presence)

img = Image.open(r"myimage.jpeg")

img.show()

TCP/IP Server send message from server and receive by client

AF_INET: represents IP address version 4

SCOK_STREAM -indicated we are using TCP/IP protocol

Server1.py

import socket

# take the server name and port name

host = 'local host'

port = 5000

# create a socket at server side

# using TCP / IP protocol

s = socket.socket(socket.AF_INET,

socket.SOCK_STREAM)

# bind the socket with server

# and port number

s.bind(('', port))
# allow maximum 1 connection to

# the socket

s.listen(1)

# wait till a client accept

# connection

c, addr = s.accept()

# display client address

print("CONNECTION FROM:", str(addr))

# send message to the client after

# encoding into binary string

c.send(b"HELLO, How are you ? ")

msg = "Bye!"

c.send(msg.encode())

# disconnect the server

c.close()

Client1.py

import socket

# take the server name and port name

host = 'local host'

port = 5000

# create a socket at client side


# using TCP / IP protocol

s = socket.socket(socket.AF_INET,

socket.SOCK_STREAM)

# connect it to server and port

# number on local computer.

s.connect(('127.0.0.1', port))

# receive message string from

# server, at a time 1024 B

msg = s.recv(1024)

# repeat as long as message

# string are not empty

while msg:

print('Received:' + msg.decode())

msg = s.recv(1024)

# disconnect the client

s.close()

TCP/IP server reads a file name from the client and reads its content

Create a file whose contents are to be read

Message.bin

with open('message.bin','wb') as f:

mes=input('Enter Message: ')

mes=mes.encode()

f.write(mes)

server1.txt

import socket
# take the server name and port name

host = 'local host'

port = 5000

# create a socket at server side

# using TCP / IP protocol

s = socket.socket(socket.AF_INET,

socket.SOCK_STREAM)

# bind the socket with server

# and port number

s.bind(('', port))

# allow maximum 1 connection to

# the socket

s.listen(1)

# wait till a client accept

# connection

c, addr = s.accept()

# display client address

print("CONNECTION FROM:", str(addr))

# accept file name from client

fname=c.recv(1024)

#convert the file name into a normal string

fname=str(fname.decode())

print('File name received from the client'+fname)


try:

f=open(fname, 'rb')

content=f.read()

c.send(content)

print('File content sent to the client')

f.close()

except FileNotFoundError:

c.send('File does not exist')

c.close()

client1

import socket

# take the server name and port name

host = 'local host'

port = 5000

# create a socket at client side

# using TCP / IP protocol

s = socket.socket(socket.AF_INET,

socket.SOCK_STREAM)

# connect it to server and port

# number on local computer.

s.connect(('127.0.0.1', port))

filename=input('Enter a file name: ')


#send file name to the server

s.send(filename.encode())

#receive the contents from the server

content=s.recv(1024)

print(content.decode())

#disconnect the client

s.close()

# disconnect the client

s.close()

Send email

Smpt- simple mail transfer protocol

Step 1: First of all, “smtplib” library needs to be imported.


Step 2: After that create a session, we will be using its instance SMTP to
encapsulate an SMTP connection.
s = smtplib.SMTP('smtp.gmail.com', 587)
Step 3: In this, you need to pass the first parameter of the server location
and the second parameter of the port to use. For Gmail, we use port number
587.
Step 4: For security reasons, now put the SMTP connection in TLS
mode. TLS (Transport Layer Security) encrypts all the SMTP commands.
After that, for security and authentication, you need to pass your Gmail
account credentials in the login instance. The compiler will show an
authentication error if you enter an invalid email id or password.
Step 5: Store the message you need to send in a variable say, message.
Using the sendmail() instance, send your message. sendmail() uses three
parameters: sender_email_id, receiver_email_id and
message_to_be_sent. The parameters need to be in the same sequence.

import smtplib

# creates SMTP session

s = smtplib.SMTP('smtp.gmail.com', 587)
# start TLS for security

s.starttls()

# Authentication

s.login("sender_email_id", "sender_email_id_password")

# message to be sent

message = "Message_you_need_to_send"

# sending the mail

s.sendmail("sender_email_id", "receiver_email_id", message)

# terminating the session

s.quit()

Authentication Error

You would need to go to your account


settings https://www.google.com/settings/security and you would need to enable Access
for less secure apps which helps to use the google smtp for clients.

Database connectivity

DBMS:

Advantages:

1. Insertion deletion, modifying etc. with a single instruction


2. Handling large volume of dat

Open MYSQL command line prompt

Enter the password


MYSQL command to create a table, add elements, access the element, update, delete
elements
Enter password: *********

Welcome to the MySQL monitor. Commands end with ; or \g.

Your MySQL connection id is 13

Server version: 8.0.32 MySQL Community Server - GPL

Copyright (c) 2000, 2023, Oracle and/or its affiliates.

Oracle is a registered trademark of Oracle Corporation and/or its

affiliates. Other names may be trademarks of their respective

owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> show databases;

+--------------------+

| Database |

+--------------------+

| employee_db |

| information_schema |

| mysql |

| performance_schema |

| sakila |

| sys |

| world |

+--------------------+

7 rows in set (0.00 sec)

mysql> use world;

Database changed
mysql> show tables;

+-----------------+

| Tables_in_world |

+-----------------+

| city |

| country |

| countrylanguage |

+-----------------+

3 rows in set (0.00 sec)

mysql> create table emptab(eno int,ename char(20), sal float);

Query OK, 0 rows affected (0.21 sec)

mysql> desc emptab;

+-------+----------+------+-----+---------+-------+

| Field | Type | Null | Key | Default | Extra |

+-------+----------+------+-----+---------+-------+

| eno | int | YES | | NULL | |

| ename | char(20) | YES | | NULL | |

| sal | float | YES | | NULL | |

+-------+----------+------+-----+---------+-------+

3 rows in set (0.00 sec)

mysql> use employee_db;

Database changed

mysql> create table emptab(eno int, ename char(10), sal float);

Query OK, 0 rows affected (0.16 sec)

mysql> desc emptab;

+-------+----------+------+-----+---------+-------+

| Field | Type | Null | Key | Default | Extra |

+-------+----------+------+-----+---------+-------+
| eno | int | YES | | NULL | |

| ename | char(10) | YES | | NULL | |

| sal | float | YES | | NULL | |

+-------+----------+------+-----+---------+-------+

3 rows in set (0.00 sec)

mysql> insert into emptab values(1, "ABC", 1000);

Query OK, 1 row affected (0.10 sec)

mysql> insert into emptab values(2, "XYA",2000);

Query OK, 1 row affected (0.05 sec)

mysql> select * from emptab;

+------+-------+------+

| eno | ename | sal |

+------+-------+------+

| 1 | ABC | 1000 |

| 2 | XYA | 2000 |

+------+-------+------+

2 rows in set (0.00 sec)

mysql> insert into emptab values(3, "PQR", 3000);

Query OK, 1 row affected (0.04 sec)

mysql> update emptab set sal =sal+1000 where eno=2;

Query OK, 1 row affected (0.06 sec)

Rows matched: 1 Changed: 1 Warnings: 0

mysql> select * from emptab;

+------+-------+------+

| eno | ename | sal |


+------+-------+------+

| 1 | ABC | 1000 |

| 2 | XYA | 3000 |

| 3 | PQR | 3000 |

+------+-------+------+

3 rows in set (0.00 sec)

mysql> delete from emptab where ename="ABC";

Query OK, 1 row affected (0.08 sec)

mysql> select * from emptab;

+------+-------+------+

| eno | ename | sal |

+------+-------+------+

| 2 | XYA | 4000 |

| 3 | PQR | 3000 |

+------+-------+------+

2 rows in set (0.00 sec)

Create as table pg 675 Pb 8

import mysql.connector

#establishing the connection

conn = mysql.connector.connect(

user='root', password='vcetCOMPS', host='127.0.0.1', database='employee_db')

#Creating a cursor object using the cursor() method

cursor = conn.cursor()

cursor.execute("drop table if exists emptab") # execute SQL query


str="create table emptab(eno int, ename char(20), salary float)"

cursor.execute(str)

#Closing the connection

cursor.close()

conn.close()

Execute desc emptab; in MYSQL to see that the table is created

Inserting rows into table pb 4 pg 669

import mysql.connector

#establishing the connection

conn = mysql.connector.connect(

user='root', password='vcetCOMPS', host='127.0.0.1', database='employee_db')

#Creating a cursor object using the cursor() method

cursor = conn.cursor()

str1="insert into emptab(eno, ename, salary) values(1, 'ABC', 1000)"

str2="insert into emptab(eno, ename, salary) values(2, 'PQR', 2000)"

str3="insert into emptab(eno, ename, salary) values(3, 'XYZ', 3000)"

try:

cursor.execute(str1) # execute SQL query

cursor.execute(str2)

cursor.execute(str3)

conn.commit() # save the changes made

except:

conn.rollback() # rollback if there is any error


# execute a SQL query using execute() method

cursor.execute("select * from emptab")

#get only one row

rows=cursor.fetchall()

#display total number of rows

print('Total number of rows =', cursor.rowcount)

# display all rows

for row in rows:

print(row)

#Closing the connection

cursor.close()

conn.close()

Python program to retrieve and display all rows from employee table pb 1 pg 666

import mysql.connector

#establishing the connection

conn = mysql.connector.connect(

user='root', password='vcetCOMPS', host='127.0.0.1', database='employee_db')

#Creating a cursor object using the cursor() method

cursor = conn.cursor()

# execute a SQL query using execute() method

cursor.execute("select * from emptab")


#get only one row

row=cursor.fetchone()

#if the row exists

while row is not None:

print(row)

row=cursor.fetchone()

#Closing the connection

cursor.close()

conn.close()

print all rows Pb 2. Pg 667

import mysql.connector

#establishing the connection

conn = mysql.connector.connect(

user='root', password='vcetCOMPS', host='127.0.0.1', database='employee_db')

#Creating a cursor object using the cursor() method

cursor = conn.cursor()

# execute a SQL query using execute() method

cursor.execute("select * from emptab")

#get only one row

rows=cursor.fetchall()

#display total number of rows

print('Total number of rows =', cursor.rowcount)


# display all rows

for row in rows:

print(row)

#Closing the connection

cursor.close()

conn.close()

update rows in the table pg 673 Pb 7

import mysql.connector

def update_rows(eno):

#establishing the connection

conn = mysql.connector.connect(

user='root', password='vcetCOMPS', host='127.0.0.1', database='employee_db')

#Creating a cursor object using the cursor() method

cursor = conn.cursor()

str="update emptab set salary=salary+1000 where eno ='%d' "

args=(eno)

try:

cursor.execute(str % args) # execute SQL query

conn.commit() # save the changes made

except:

conn.rollback() # rollback if there is any error

finally:

# execute a SQL query using execute() method

cursor.execute("select * from emptab")


#get only one row

rows=cursor.fetchall()

#display total number of rows

print('Total number of rows =', cursor.rowcount)

# display all rows

for row in rows:

print(row)

#Closing the connection

cursor.close()

conn.close()

x=int(input('Enter eno: '))

update_rows(x)

Deleting rows from a table pg.672 Pb. 6

import mysql.connector

def delete_rows(eno):

#establishing the connection

conn = mysql.connector.connect(

user='root', password='vcetCOMPS', host='127.0.0.1', database='employee_db')

#Creating a cursor object using the cursor() method

cursor = conn.cursor()

str="delete from emptab where eno ='%d' "

args=(eno)
try:

cursor.execute(str % args) # execute SQL query

conn.commit() # save the changes made

except:

conn.rollback() # rollback if there is any error

finally:

# execute a SQL query using execute() method

cursor.execute("select * from emptab")

#get only one row

rows=cursor.fetchall()

#display total number of rows

print('Total number of rows =', cursor.rowcount)

# display all rows

for row in rows:

print(row)

#Closing the connection

cursor.close()

conn.close()

x=int(input('Enter eno: '))

delete_rows(x)

Introduction to DJANGO
Install Django
pip install django

Creating a Project
Lets’ check how to create a basic project using Django after you have
installed it in your pc.
 To initiate a project of Django on Your PC, open Terminal
and Enter the following command
django-admin startproject projectName
 A New Folder with name projectName will be created. To
enter in the project using terminal enter command
cd projectName
Python manage.py runserver
Now visit http://localhost:8000/ ,

To create a basic app in your Django project you need to go to directory


containing manage.py and from there enter the command :
python manage.py startapp projectApp

You might also like