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

Python Module-5 VTU QP Solution

Uploaded by

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

Python Module-5 VTU QP Solution

Uploaded by

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

PYTHON APPLICATION PROGRAMMING

Module 5

Network Programming & SQL with Python


Very Important Questions
Questions based on Socket
What is socket? Explain how socket connection can be established to the internet using Python code over the
TCP/IP connection and the http protocol to get the web document July 18

Define socket? Write a python program that makes a connection to a webserver and follows the rules of
HTTP protocol to request a plain test document and display what server sends back Jan 20
Define socket? Write a python program that makes a connection to a webserver and follows the rules of
HTTP protocol to request a plain test document and display what server sends back July 20
What is socket? Write and explain a program in python, that connects to web server requests a document,
and display what the server sends back. Jan 22
Define Socket. Explain how socket connection can be established to the internet using Python code over
TCP/IP connection and http protocol to get the web document July 22
Solution:
Sockets are endpoints in bidirectional communication channel.
o The sockets (endpoints) can communicate within a process, between processes in the same
machine, or between the processes on the different machines.
o Single socket provides a two-way connection, ie we can both read from and write to the same
socket.
o The Python provides built-in library called socket to make network connections and to
access data over other sockets

Creating the socket:


o To create socket, we have to use the python socket method from socket library(module).
Syntax of Socket
socket.socket(socket_family, socket_type)
Family Address family provides different types of addresses during inter-
process communication. Mainly 2 families: AF_INET & PF_INET
AF_INET = Address Format, Internet
AF_INET refers to IP addresses from the internet (IP V4 or IP V6)

Type Type of transport layer protocol TCP or UDP.


SOCK_STREAM for TCP (connection-oriented protocols)
SOCK_DGRAM for UDP (connectionless protocols)

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON APPLICATION PROGRAMMING

Example : The Simple Web Browser


Program: To retrieve web pages using the Hypertext Transfer Protocol (HTTP).
import socket #import the socket library

#To create the socket


s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# Now to connect to the website (http port 80)


s.connect(('data.pr4e.org', 80))

#Creating request to web page by using GET method of HTTP protocol


cmd='GET http://data.pr4e.org/romeo.txt HTTP/1.0\r\n\r\n'

#Data sent should be in bytes format, so convert from string to byte


cmd= cmd.encode()

#Now to send request to the server (website)


s.send(cmd)

#Creating variable of type bytes to store the received data


new_data=b''
#Now to receive the data from server
while True:
data = s.recv(512) #receiving the data of 512 bytes chuncks
if (len(data) < 1): #if the data is less than 1 byte
break #comeout of the loop
new_data=new_data+data
s.close()

a=new_data.decode() #convert back to string


print(a)

Explanation:
To create socket and send the request
1. First to import the socket library
2. Create the socket using socket.socket () method
3. Now to connect to the website using connect () method
4. To send request to webpage:
i. First create request for the web page using GET method of the HTTP and store it in
cmd variable.
ii. Data sent should be in bytes format, so convert string into byte using encode () method
and again store back in cmd variable.
iii. Now send request (stored in cmd variable) to the server using send () method.

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON APPLICATION PROGRAMMING

Note ; HTTP/1.0: This specifies the version of the HTTP protocol i.e HTTP version 1.0.
Here \r\n means next line and \r\n\r\n represents the end of HTTP header.
5. To receive the data from webpage
i. Create the one variable new_data of type byte to store the received data
ii. We have to receive the in 512-character chunks at time, so to extract entire data we
have to use loop (to repeat the process)
6. Close the connection using close method

The various functions used:


1. socket.socket () :
The socket method from the socket library(module) is used to create the socket
2. connect () :By using this method client establishes a connection with server.
3. send() : The send () method of Python's socket module is used to send data from one socket
to another socket.
4. encode() : The data sent should be in bytes format. String data can be converted to bytes by using the
encode() method
5. recv() : This function is used to receive the contents of the web page
6. close() : This function is used to close the socket connection

Write a python code to read the file from web using urllib and retrieve the data of the file. Also compute the
frequency of each word in the file. Jan 20
Write a python code for retrieving the romeo.txt file from the web and compute the frequency of each word
in the file. June 20
Write a program to retrieve data text file on web and compute frequency of each word in file. Jan 22

• Python has urllib library, which is used to handle the URLs.


• By using urllib, we can access or retrieve web page like any text file.

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON APPLICATION PROGRAMMING

• By using urllib library, we can, send GET requests, receive data, parse data, and modify the
headers, error handling etc. urllib handles all these tasks related to HTTP protocol
• The urllib.request is default module used for opening HTTP URLs.
• The urllib library has many modules to handle the URLs.
o urllib.request : for opening and reading. To open the file: urllib.request.urlopen().
o urllib.parse: The URL parsing is used to split a URL string into its components.
o urllib.error : It is used to handle the errors. It raises the exception when error occurs

Program : To retrieve web pages using urllib


import urllib.request

file1 = urllib.request.urlopen('http://data.pr4e.org/romeo.txt')

for line in file1:


line=line.decode() #To convert to string (from byte)
print(line)

Explanation
o Open the web page using urllib.urlopen.
o Then we can treat webpage like a file and read it using a for loop.
o When we run program, output will be only contents of the file. The headers are still
sent, but the urllib code consumes the headers and only returns the data to us.

Example: To write a program to retrieve the data and compute the frequency of each word
import urllib.request,
import urllib.parse,
import urllib.error

counts = dict()
file1 = urllib.request.urlopen('http://data.pr4e.org/romeo.txt')

for line in file1:


words = line.decode().split()
for word in words:
counts[word] = counts.get(word, 0) + 1
print(counts)

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON APPLICATION PROGRAMMING

Questions based on XML


Write a note on XML. Design python program to retrieve a node present in XML tree. Jan 2019
What is XML? How is it used in python? Explain parsing of XML with example. Jan 2020
Write a note on XML. June 2020
What is XML? Explain the process of parsing XML using a tree representation. Jan 2022
Note on XML:
• XML is the markup language similar to HTML. It is structured and tag-based language
• This is mainly used to exchange or transmit the data across the web. It is most suitable
for exchanging document style data.
• The XML is similar to HTML, but the difference is, HTML has predefined tags, but in
XML user or developer can create his own tags (user defined). That is why it is called
EXTENSIBLE
• XML is more structured than HTML.
• The most important part of XML are XML tags.
• Two important tags of XML are: start tag & end tag
• The content (data) or instructions have to be placed between these starts and stop tags.
• Start Tag: Every XML element or content begins with start-tag.
Example: <name>
• End Tag: Every element that has a start tag should end with an end-tag.
Note: end tag includes a ("/")
Example </name>
• Simple example for xml document

• We can think XML document as a tree structure. Here Player is top tag or root tag(node)
and other tags such as name, age are child elements.

Tree structure above XML code.

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON APPLICATION PROGRAMMING

Parsing XML (To retrieve the node present in the XML tree)
(Parsing means extracting the data from text)
• To parse XML document, first XML document has to be converted into Tree structure (Tree
of nodes) and then required node of the tree has to be extracted(parsed).
• To convert the XML into Tree structure, inbuilt functions of Element Tree library are used.
So, first we need to import Element Tree library (xml.etree.ElementTree)
• Mainly 3 functions of Element Tree library are used.
▪ fromstring(): It is used to convert XML code into a tree-structure (tree of XML
nodes.)
▪ find () function is used extract the node (value of the tag) from XML tree
▪ get () function is used to extract the attribute value.
Example:

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON APPLICATION PROGRAMMING

Output:
Name:Dhoni
Age: 40
Runs: 15000
Attribute: yes

Explanation :

ET.fromstring(data) => converts the XML data (stored in the data variable) into an Element Tree structure
(tree).

tree.find('name').text =>finds the <name> tag in the XML tree and returns its content ('Dhoni')

tree.find('age').text =>finds the <age> tag in the XML tree and returns its content ('40').

tree.find('runs').text => finds the <runs> tag in the XML tree and returns its text content ('15000').

tree.find('email').get('hide')=> finds the <email> tag in the XML tree and retrieves the value of the 'hide'
attribute ('yes' ).

Explain the significance of XML over the web development. Illustrate with an example. July 2018
Importance of XML in Web Applications:
XML has several important web applications; such as
• Web Publishing: XML allows user to create interactive pages that can display information.
• Searching: In XML data is placed between tags, so it makes searching easy.
For example: Consider XML page containing information of different cricket players such as
player name, age, runs scored etc. Now if we search the pages with player name, then it will
directly search into name tags and retrieve related data
• Independent Data Interchange: Almost all other programming languages can parse (extract
data from) XML. So, XML is highly used for interchanging data between web application
using APIs.
• Granular Updates: Updating Entire document makes process slow, as the entire document
needs to be refreshed from the server. So, in updating/uploading an XML document, only the
part (granular) of the document is updated/uploaded.
• Metadata Applications:
▪ Assists in Data Assessments and Aggregation
▪ Custom Tags

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON APPLICATION PROGRAMMING

Questions based on SQL


Brief on structured Query language, with suitable python program explain functions involved in creation of
database table in python. Jan 19
With appropriate code segment in python using SQLite, explain table creation, insertion, fetching and
deletion. Jan 2022
(SQL:Structured query language):
• SQL is used to interact with database
• A database is an organized collection of interrelated data.
• SQL is used to perform operations on data in databases. It is used for storing, manipulating
and retrieving the data in databases.
• The various data types in SQLite are
1. INTEGER 2. TEXT 3. BOOLEAN 4. FLOAT 5. VARCHAR 6. NUMERIC
• Basic SQL commands

Command Meaning
CREATE TABLE To Create a new table
DROP TABLE Deletes table
SELECT To Extract data from database
INSERT INTO To Insert new data into a database
UPDATE To Update data in database
DELETE To Delete data from database

Syntax of commands: (Creating the Table, inserting, extracting and deleting data)

1. Creating Table: CREATE TABLE command is used to create a new table.


CREATE TABLE Player (name VARCHAR, age INT, runs INT )

This command creates a table wit name Player with the attributes(columns) name, age and
runs. The name is of character data type and age, runs are of Integer type

2. Inserting data: Data is inserted using INSERT INTO command


INSERT INTO Player (name, age, runs) VALUES ('Dhoni', 35, 15000)

3. Extracting data: SELECT command is used to extract or fetch the data


SELECT * FROM Player #Retrieves all the data from the table Player
SELECT name, age FROM player #Retrieves only name and age

4. Updating value: UPDATE command is used to modify the existing data


UPDATE Player SET age = 45 WHERE name = 'Dhoni‘

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON APPLICATION PROGRAMMING

5. Deleting data: DELETE command is used to delete the particular record


DELETE FROM player WHERE name='Dhoni'
DELETE FROM player # delete all data

6. Deleting Table: DROP TABLE is used to delete the table.


DROP TABLE Player

SQLite with Python (Embedding SQL commands in Python)

Embedded SQL: Putting SQL queries into high-level languages (python or java) to get meaningful
& efficient output
• Python has inbuilt library sqlite3 to handle SQLite database.
• This library has methods connect (), execute (), cursor () and commit () to perform operations
on database
• To use Python to handle SQL database
i. First import the python library sqlite3
ii. To create the database: connect () method is used to Create the database, if already
existing, then it directly opens it.
(Note: connect means create and open)
iii. To create cursor object: cursor () method is sued to create cursor object (file handle)
iv. To Execute: SQL commands are executed using execute () method. By using this
method, we can execute the commands like CREATE TABLE, INSERT INTO etc
v. Confirmation: For the commands INSERT, UPDATE, DELETE, confirm the
execution by using commit method (). This
vi. Close the connection (database): close() method is used to close database

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON APPLICATION PROGRAMMING

Example1:Program to create the table

import sqlite3
conn=sqlite3.connect(‘cricket.db’) #create & open database by name cricket and store in variable conn
cur=conn.cursor() # creating the cursor object : cur
cur.execute (‘CREATE TABLE Player (name TEXT, age INT, runs INT)’) #create table
conn.close() # close the database or connection

Example 2: Program to delete the table

import sqlite3
conn=sqlite3.connect(‘cricket.db’) #create & open database by name cricket and store in variable conn
cur=conn.cursor() # creating the cursor object : cur
cur.execute (‘DROP TABLE Player’) # Delete table
conn.commit() #It is for confirmation
conn.close() # close the database or connection

Example 3: Program to create the table and to insert the values

import sqlite3
conn=sqlite3.connect(‘cricket.db’) #create & open database by name cricket and store in variable conn
cur=conn.cursor() # creating the cursor object : cur
cur.execute (‘CREATE TABLE Player (name TEXT, age INT, runs INT)’) #create table
cur.execute (‘INSERT INTO Player (name, age, runs) VALUES ('Dhoni', 35, 15000)’)
conn.close() # close the database or connection

Example 4: Program to update or modify the values

import sqlite3
conn=sqlite3.connect(‘cricket.db’) #create & open database by name cricket and store in variable conn
cur=conn.cursor() # creating the cursor object : cur
cur.execute (‘UPDATE Player SET runs 20,000 WHERE ‘name’ = virat)
conn.commit() #It is for confirmation
conn.close() # close the database or connection

Example 5: Program to delete the data


import sqlite3
conn=sqlite3.connect(‘cricket.db’) #create & open database by name cricket and store in variable conn
cur=conn.cursor() # creating the cursor object : cur
cur.execute (‘DELETE FROM Player WHERE= ‘Dhoni’)

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON APPLICATION PROGRAMMING

conn.commit() #It is for confirmation


conn.close() # close the database or connection

Example 6: Extracting and displaying the data


import sqlite3
conn=sqlite3.connect(‘cricket.db’) #create & open database by name cricket and store in variable conn
cur=conn.cursor() # creating the cursor object : cur
cur.execute (‘SELECT name, age FROM Player’)
for row in cur
print(row[0])
print(row[1])
conn.close() # close the database or connection

Define cursor? Explain connect, execute and close command of databases with suitable example
• A cursor is a database object that allows us to work with the result of a SQL command.
• When a SQL statement is executed, the result is temporarily stored in memory within the
cursor.
• Cursors is used to navigate through the rows of the result, typically one row at a time.
• They act as pointers, allow us to fetch individual rows, move to the next row, and process
each row in a loop.
• Cursors are used to interact with the data returned by a SQL, thus enable us to perform
various operations on the data.

cursor () method: It is used to create cursor object (file handle). It acts as a file handle or
intermediator

connect () method: Use connect () method to Create the database (or database object) and open
(connect) it, if already existing, then directly open it.

execute () method : We can Execute the SQL commands using execute () method. By using this
method, we can execute the commands like CREATE TABLE, INSERT INTO etc

commit method (): Confirm the execution by using commit method (), specially while deleting or
updating

close() method : Use close() method to close the connection or database

#Program
#To create the table & Insert the values

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON APPLICATION PROGRAMMING

import sqlite3
conn=sqlite3.connect(‘cricket.db’) #create & open database by name cricket and store in variable conn
cur=conn.cursor() # creating the cursor object : cur
cur.execute (‘CREATE TABLE Player (name TEXT, age INT, runs INT)’) #create table
cur.execute (‘INSERT INTO Player (name, age, runs) VALUES ('Dhoni', 35, 15000)’)
cur.execute (‘INSERT INTO Player (name, age, runs) VALUES ('Rohit', 30, 12000)’)
cur.execute (‘INSERT INTO Player (name, age, runs) VALUES ('Virat', 30, 14000)’)
conn.close() # close the database or connection

# To update or modify the values (age of rohit)

import sqlite3
conn=sqlite3.connect(‘cricket.db’) #create & open database by name cricket and store in variable conn
cur=conn.cursor() # creating the cursor object : cur
cur.execute (‘UPDATE Player SET age 32 WHERE ‘name’ = Rohit)
conn.commit() #It is for confirmation
conn.close() # close the database or connection

#To delete the data

import sqlite3
conn=sqlite3.connect(‘cricket.db’) #create & open database by name cricket and store in variable conn
cur=conn.cursor() # creating the cursor object : cur
cur.execute (‘DELETE FROM Player WHERE= ‘Dhoni’)
conn.commit() #It is for confirmation
conn.close() # close the database or connection

# Extracting and displaying the data

import sqlite3
conn=sqlite3.connect(‘cricket.db’) #create & open database by name cricket and store in variable conn
cur=conn.cursor() # creating the cursor object : cur
cur.execute (‘SELECT name, runs, age FROM Player’)
for row in cur
print(row[0])
print(row[1])
print(row[2])
conn.close() # close the database or connection

#To delete the table

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON APPLICATION PROGRAMMING

import sqlite3
conn=sqlite3.connect(‘cricket.db’) #create & open database by name cricket and store in variable conn
cur=conn.cursor() # creating the cursor object : cur
cur.execute (‘DROP TABLE Player’) # Delete table
conn.commit() #It is for confirmation
conn.close() # close the database or connection

Write a python code for creating employee database, inserting records and selecting the employees
working in the company June 2020

import sqlite3
conn = sqlite3.connect('EmpDB') #create the
cur = conn.cursor()

#To create the table


cur.execute('CREATE TABLE Employee (EmpID, DeptName, GrossSalary)')

# Inserting data into the table


cur.execute('INSERT INTO Employee (EmpID, DeptName, GrossSalary) VALUES (51, 'Quality
Control', 30,000))
cur.execute('INSERT INTO Employee (EmpID, DeptName, GrossSalary) VALUES (52, 'Quality
Control', 25,000))
cur.execute('INSERT INTO Employee (EmpID, DeptName, GrossSalary) VALUES (53, 'Quality
Control', 20,000))
cur.execute('INSERT INTO Employee (EmpID, DeptName, GrossSalary) VALUES (54, 'Testing',
25000))
cur.execute('INSERT INTO Employee (EmpID, DeptName, GrossSalary) VALUES (55, 'Testing',
20,000))
#To extract or retrieve the all data and print all the data
cur.execute('SELECT * FROM Employee') # * indicates extract all the data
print (cur.fetchall())

# Now only to extract gross salary of quality control


cur.execute('SELECT GrossSalary FROM Employee WHERE DeptName = \'Quality Control\'')
print (cur.fetchall())

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON APPLICATION PROGRAMMING

What is embedded SQL? Explain the importance of SQLite database. Write a Python code to
establish a database connection to ‘EmpDb’ and display the total gross salary paid to the employee
working in the ‘Quality Control’ department.
Assume the employee table has been already created and exit in the ‘EmpDb’. The fields of
Employable table are: (EmpID, DeptName, GrossSalary).

Embedded SQL: Putting SQL queries into high-level languages (python or java) to get meaningful
& efficient output
Importance of SQLite database is embedded (serverless), lightweight and fast database. It is open
source database

# Python code
import sqlite3
conn = sqlite3.connect('EmpDB')
cur = conn.cursor()

#To create the table


cur.execute('CREATE TABLE Employee (EmpID, DeptName, GrossSalary)')

# Inserting data into the table


cur.execute('INSERT INTO Employee (EmpID, DeptName, GrossSalary) VALUES (51, 'Quality
Control', 30,000))
cur.execute('INSERT INTO Employee (EmpID, DeptName, GrossSalary) VALUES (52, 'Quality
Control', 25,000))
cur.execute('INSERT INTO Employee (EmpID, DeptName, GrossSalary) VALUES (53, 'Quality
Control', 20,000))
cur.execute('INSERT INTO Employee (EmpID, DeptName, GrossSalary) VALUES (54, 'Testing',
25000))
cur.execute('INSERT INTO Employee (EmpID, DeptName, GrossSalary) VALUES (55, 'Testing',
20,000))

#To extract or retrieve the data and print all the data
cur.execute('SELECT * FROM Employee') # * indicates extract all the data
print (cur.fetchall())

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON APPLICATION PROGRAMMING

# Now only to extract gross salary of quality control


cur.execute('SELECT GrossSalary FROM Employee WHERE DeptName = \'Quality Control\'')
print (cur.fetchall())

#To add the gross salary of quality control department using sum command
cur.execute('SELECT SUM(GrossSalary) FROM Employee WHERE DeptName = \'Quality
Control\'')
print ('Total Gross Salary of Employees Working in Quality Control Dept. is', cur.fetchall()[0][0])

Explain with a neat diagram of Server Oriented Architecture


Server Oriented Architecture:

• When we are building programs, in our program if we include functionality, which can
access the services provided by other programs, then this approach is called Service-
Oriented Architecture or SOA.
• In SOA approach: our overall application makes use of the services of other applications.
• In non-SOA approach: The application is a single standalone application which contains all
of the code necessary to implement the application.
• When an application makes a set of services available over the web using API, we call these
web services
Example of SOA:
• We can go to a single web site and book the ticket for air-travel and also book hotel room.
• This is possible due to service-oriented Architecture.
• Similarly, the payment for the air-travel or hotel accommodation can be done using credit
card. Thus, there are various services available that are interconnected. These services are
responsible for handling air-booking-data, hotel-booking-data or credit card transaction

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON APPLICATION PROGRAMMING

Write a note on Google Geocoding web service. Using Python supported libraries. Demonstrate with a
Snippet code.
Google Maps and its Geocoding API are very popular web services provided by Google. These are used to
obtain Geographical information (find locations, get directions etc)
Geocoding is the process of converting human-readable addresses or place names (like "Hubli") into
geographic coordinates (latitude and longitude) that can be used to locate those places on the map.
Working principle:
Users submit a geographic search string (e.g., "Hubli") to the Geocoding API.
Geocoding API processes this string and tries to find a matching location from its database.
If a match is found, Google returns the geographic coordinates (latitude and longitude) of the location.
Also, Google Maps may display the location on the map with nearby landmarks, making it easier for users to
recognize the place.

Google Geocoding web service

import requests

def geocode(address):
base_url = "https://maps.googleapis.com/maps/api/geocode/json"
api_parameters = {"address": address, "key": "YOUR_GOOGLE_MAPS_API_KEY"}

response = requests.get(base_url, params=api_parameters)


data = response.json()

# Extracting latitude and longitude from the response


location = data['results'][0]['geometry']['location']
latitude = location['lat']
longitude = location['lng']
return latitude, longitude

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON APPLICATION PROGRAMMING

# To call the function


address = "M.G. road, Bengaluru"
latitude, longitude = geocode(address)
print(f"The coordinates of '{address}' are: Latitude {latitude}, Longitude
{longitude}")

Create simple spidering program that will go through Twitter accounts and build a database of them

import tweepy

# 1.Twitter Developer API keys


consumer_key = "YOUR_CONSUMER_KEY"
consumer_secret = "YOUR_CONSUMER_SECRET"
access_token = "YOUR_ACCESS_TOKEN"
access_token_secret = "YOUR_ACCESS_TOKEN_SECRET"

# Authenticate with Twitter API


auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)

# Create API object


api = tweepy.API(auth, wait_on_rate_limit=True)

def fetch_user_details(username):
user = api.get_user(screen_name=username)
return user._json

# Call the function


username = "twitter"
user_details = fetch_user_details(username)
print("User Details:")
for key, value in user_details.items():
print(f"{key}: {value}")

1. Import Required Libraries:


2. Twitter Developer API Keys and Access Tokens:
These keys and tokens are required for authentication to access the Twitter API.
3. Authenticate with Twitter API:
These keys and tokens are required for authentication to access the Twitter API.
4. Create API Object:
We create an OAuthHandler object, by passing the consumer key and secret. Then, we set the access
tokens to access the Twitter account.
5. Define the Function to Fetch User Details:

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON APPLICATION PROGRAMMING

We define a function fetch_user_details(username) that takes a username as input. The function uses
the api.get_user() method to get the details of the Twitter user with the given username.
6. Call the Function:
We call the fetch_user_details() function, passing the Twitter username as "twitter". The function
will retrieve the user details
7. Print the User Details:

Prof. Sujay Gejji ECE, SGBIT, Belagavi

You might also like