Skip to main content
Open navigation menu
Close suggestions
Search
Search
en
Change Language, English
Upload
Sign in
Sign in
0 ratings
0% found this document useful (0 votes)
29 views
14 pages
Python Module 5 Important Questions
Uploaded by
akshay s
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here
.
Available Formats
Download as PDF or read online on Scribd
Download
Save
Save Python Module 5 Important Questions For Later
Share
0%
0% found this document useful, Mark this document as useful
0%
0% found this document not useful, Mark this document as not useful
Print
Embed
Report
0 ratings
0% found this document useful (0 votes)
29 views
14 pages
Python Module 5 Important Questions
Uploaded by
akshay s
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here
.
Available Formats
Download as PDF or read online on Scribd
Go to previous items
Download
Save
Save Python Module 5 Important Questions For Later
Share
0%
0% found this document useful, Mark this document as useful
0%
0% found this document not useful, Mark this document as not useful
Print
Embed
Report
Go to next items
Download
1 Explain connect, cursor, execute and close command of a database with suitable example. A import sqites conn = [Link]([Link]’) /! The connect operation makes a “connection” to the database stored in the file music sqiite3 in the current directory. cur = [Link]() Calling cursor() is very similar conceptually to calling open() when dealing with text files. curexecute((DROP TABLE IF EXISTS Tracks’) it We can begin to execute commands on the contents of the database using the execute() method. curexecute(CREATE TABLE Tracks (tile TEXT, plays INTEGER)’ [Link]() close() is used to close the database. Design python program to retrieve node present in XML tree. Write a note on XML. A XML looks very similar to HTML, but XML is more structured than [Link] itis helpful to think of an XML document as a tree structure where there is a top tag person and other tags such as phone are drawn as children of their parent nodes. limport [Link] as ET input =" 001
Chuck
009 Brent stuff = [Link] (input) \st = stuff findall(users/user’) print(User count’, len('st)) for item in ist: print(’Name’, item find(name’) text) print(ld, item find¢ idl) text) print(Attribute’, item. get(’x")) Output: User count: 2 Name Chuck Scanned with CamScannerId 001 Attribute 2 Name Brent Id 009 Attribute 7 Write a python code to read the file from web using urib and retrieve the data of the file. Also compute the frequency of each word in the file A The equivalent code to read the sample. file from the web using urlib is as follows: impor uriib request, urlib parse, [Link] fhand = urlib. request urlopen([Link] pré[Link]/[Link]’) for line in than: print([Link]().strip()) We can write a program to retrieve the data for [Link] and compute the frequency of each word in the file as follows: import [Link], urllib parse, [Link] counts = dict() fhand = urlib. [Link](‘[Link] pré[Link]/[Link]’) for line in fhand: words = [Link]() split() for word in words: counts|word] [Link](word, 0) + 1 print(counts) Explain googie geocoding web service with program. ‘A: Google has an excellent web service that allows us to make use of their large database of geographic information. We can submit a geographical search string like "Ann Arbor, MI" to their geocoding AP! and have Google retum its best guess as to where on a map we might find our search string and tell us about the landmarks nearby. The geocoding service is free but rate limited so you cannot make unlimited use of the API in ‘a commercial application. But if you have some survey data where an end user has entered a location in a free-format input box, you can use this API to clean up your data quite nicely. The following is a simple application to prompt the user for a search string, call the Google geocoding API, and extract information from the returned JSON. import uni request, uriib. parse, [Link] import json serviceurl while True: address = input('Enter location: ') if len(address) < 1: break url= serviceuri + [Link]({'sensor: false’, ‘address': address}) print(Retrieving’, url) ttp:simaps. googleapis. com/maps/api/geocode/json” Scanned with CamScanneruh = urllib. request urlopen(url) data = [Link]().decode() print(Retrieved’, len(data), ‘characters') ty, js = json loads(data) except js = None if not js or ‘status’ not in js or js{status'] print('==== Failure To Retrieve print(data) cor le print([Link](js, indent=4)) lat = js['results"[0]["geometry"I[ "location" }["iat"] Ing = js["results"0][' geometry’ ocation"['ing’] print(‘at’, lat, ‘ing’, Ing) location = jsfresults'][0]['formatted_address'] print(location) Output: lat 42,2808256 Ing -83.7430378 Ann Arbor, MI, USA Describe creation of database table using database cursor architecture. A: The code to create a database file and a table named Tracks with two columns in the database is as follows: import sqiite3 conn = [Link](‘[Link]’) cur = [Link]() curexecute(DROP TABLE IF EXISTS Tracks’) [Link](CREATE TABLE Tracks (tite TEXT, plays INTEGER)) [Link]() The connect operation makes a “connection” to the database stored in the file music.sqlite3 in the current directory. Ifthe file does not exist, it will be created. The reason this is called a Connection" is that sometimes the database is stored on a separate “database server" from the server on which we are running our application. A cursor is like a file handle that we can use to perform operations on the data stored in the database. Calling cursor() is very similar conceptually to calling open() when dealing with text files, Scanned with CamScannerexecute fetchone fetchall Courses Figure 15.2 A Database Cursor Once we have the cursor, we can begin to execute commands on the contents of the database using the execute() method. Brief on Structures Query Language. with suitable python program explain function involved in creating, inserting, displaying, deleting and updating database table in python. A import sqiite3 conn = [Link](‘music. sqlite’) cur = [Link]() [Link](INSERT INTO Tracks (title, plays) VALUES (?, 2)’ (Thunderstruck, 20)) [Link](INSERT INTO Tracks (title, plays) VALUES (?, 2)’ (My Way’, 15)) [Link]() print("Tracks:’) [Link](‘SELECT title, plays FROM Tracks’) for row in cur: print(row) [Link](DELETE FROM Tracks WHERE plays < 100’) [Link]() When we create a table, we indicate the names and types of the columns CREATE TABLE Tracks (title TEXT, plays INTEGER) To insert a row into a table, we use the SQL INSERT command INSERT INTO Tracks (title, plays) VALUES (‘My Way’, 15) The INSERT statement specifies the table name, then a list of the fields/columns that you would like to set in the new row, and then the keyword VALUES and a list of corresponding values for each of the fields. The SQL SELECT command is used to retrieve rows and columns from a database. The SELECT statement lets you specify which columns you would like to retrieve as well as a WHERE clause to select which rows you would like to see. It also allows an optional ORDER BY clause to control the sorting of the returned rows. SELECT * FROM Tracks WHERE title = "My Way’ Using * indicates that you want the database to return all of the columns for each row that matches the WHERE clause You can request that the retumed rows be sorted by one of the fields as follows: Scanned with CamScannerSELECT title plays FROM Tracks ORDER BY title To remove a row, you need a WHERE clause on an SQL DELETE statement. The WHERE clause determines which rows are to be deleted DELETE FROM Tracks WHERE title = ‘My Way’ itis possible to UPDATE a column or columns within one or more rows in a table using the SQL UPDATE statement as follows: UPDATE Tracks SET plays = 16 WHERE title = 'My Way’ The UPDATE statement specifies a table and then a list of fields and values to change after the SET keyword and then an optional WHERE clause to select the rows that are to be updated. Explain any 2 socket function. Explain support for parsing HTML using regular expression with an example. A listen() - establishes a socket to listen for incoming connection. send() - sends data on a connected socket. sendto() - sends data on an unconnected socket. recv() - receives data from a connected socket. One simple way to parse HTML is to use regular expressions to repeatedly search for and extract substrings that match a particular pattern We can construct a well-formed regular expression to match and extract the link values as follows: href="http:// +2" We add parentheses to our regular expression to indicate which part of our matched string we would like to extract, and produce the following program: # Search for lines that start with From and have an at sign import [Link], urilib parse, [Link] import re url= input(Enter -") html = urliib request uriopen(url).read() links = [Link](b'href="(http:/."2)", him) for link in links: print([Link]()) Output Enter - http:/[Link]/[Link]. http:siwww [Link]/page2. htm Write a program to parse HTML using BeautifulSoup, A We will use urllib to read the page and then use BeautifulSoup to extract the href attributes from the anchor (a) tags. Program: import unlib request, [Link], [Link] Scanned with CamScannerfrom bs4 import BeautifulSoup input(Enter -*) him = urlib [Link](url).read() soup = BeautifulSoup(htmi, '[Link]’) # Retrieve all of the anchor tags tags = soup(') for tag in tags: print([Link](href, None)) Explain with a neat diagram of Service-Oriented Architecture. List the advantages of the same. ‘A: When we begin to build our programs where the functionality of our program includes access to services provided by other programs, we call the approach a Service-Oriented Architecture or SOA. A SOA approach is one where our overall application makes use of the services of other applications. A non-SOA approach is where the application is a single standalone application which contains al of the code necessary to implement the application. The data for hotel's is not stored on the airline computers. Instead, the airline computers contact the services on the hotel computers and retrieve the hotel data and present it to the user. When the user agrees to make a hotel reservation using the airline site, the airline site uses another web service on the hotel systems to actually make the reservation. And when it comes time to charge your credit card for the whole transaction, still other computers become involved in the process. Travel Application ve 132: Service Oriented Architecture A Service-Oriented Architecture has many advantages including (1) we always maintain only one copy of data (this is particularly important for things like hotel reservations where we do not want to over-commit) (2) the owners of the data can set the rules about the use of their data. With these advantages, an SOA system must be carefully designed to have good performance and meet the user's needs. Scanned with CamScanner410. What is JSON? Illustrate the concept of parsing JSON python code A: The JSON format was inspired by the object and array format used in the JavaScript language. But since Python was invented before JavaScript, Python's syntax for dictionaries, and lists influenced the syntax of JSON. So the format of JSON is nearly identical to a combination of Python lists and dictionaries. In the following program, we use the built-in json library to parse the JSON and read through the data. Compare this closely to the equivalent XML data and code above. The JSON has less detail, so we must know in advance that we are getting a list and that the list is of users and each user is a set of key-value pairs. The JSON is more succinct (an advantage) but also is less self-describing (a disadvantage). import json data = info = json loads(data) print((User count: len(info)) for item in into: print(Name’,item[name’)) print(Ic’, itemfia') print( Attribute’, item[x]) Output User count: 2 Name Chuck Id 001 Attribute 2 Name Brent Id 009 Attribute 7 Scanned with CamScannerRetrieving an image over HTTP *We can use a similar program to retrieve an image across using HTTP. * Instead of copying the data to the screen as the program runs, we accumulate the data in a string, trim off the headers, and then save the image data to a file as follows: Program MOST data pre ong thc senda GET hp ote oor pg MTH/LOMAANAND time seep(025) court = count + fen(daa) lenaata) count) snysoch. cose) Contd... # Look for the end of the header (2 CRLF) pos = [Link](b"\r\n\r\n") print('Header length’, pos) print(picture[:pos].decode()) # Skip past the header and save the picture data picture = picture[pos+4:] fhand = open("[Link]", "wb") [Link](picture) [Link]() Scanned with CamScanner— Security and API Usage Public APIs can be used by anyone without any problem. But, if the API is set up by some private vendor, then one must have API key to use that API. If API key is available, then it can be included as a part of POST method or as a parameter on the URL while calling API. Sometimes, vendor wants more security and expects the user to provide cryptographically signed messages using shared keys and secrets. The most common protocol used in the internet for signing requests is OAuth. As the Twitter API became increasingly valuable, Twitter went from an open and public API to an API that required the use of OAuth signatures on each API request. But, there are still a number of convenient and free OAuth libraries so you can avoid writing an OAuth implementation from scratch by reading the specification. These libraries are of varying complexity and have varying degrees of richness. ‘The OAuth web site has information about various OAuth libraries. Scanned with CamScannerEx4, Write a program to create a Student database with a table consisting of student name and age. Read n records from the user and insert them into database. Write queries to display all records and to display the students whose age is 20. import sqlite} conn=[Link]('[Link]') e=[Link]() [Link](‘CREATE TABLE thlStudent(name text, age Integer)’) n-int(input(“Enter number of records:”)) for i in range(n): nm=input("Enter Name:") ag=int(input("Enter age:")) [Link]("INSERT INTO tblStudent VALUES\ nm,ag)) [Link]() [Link]("select * from thlStudent ") print([Link]()) [Link]("select * from tblStudent where age=20") print([Link]()) [Link]() Scanned with CamScanner— Using JOIN to Retrieve Data © When we follow the rules of database normalization and have data separated into multiple tables, linked together using primary and foreign keys, we need to be able to build a SELECT that reassembles the data across the tables, + SQL uses the JOIN clause to reconnect these tables. In the JOIN clause you specify the fields that are used to reconnect the rows between the tables. Mamatha A, Asst Prof, Dept of CSE, SVIT. Page 25 Scanned with CamScannerHypertext Transfer Protocol — HTTP * The protocols that are used to transfer hypertext between two computers is known as Hypertext Transfer Protocol. * HTTP provides standard between a web browser and web server to establish communication * It is set of rules for transferring data from one computer to another. * Data such as text, images, and other multimedia files are shared on the World Wide Web. * The network protocol that powers the web is actually quite simple and there is built-in support in Python called socket which makes it very easy to make network connections and retrieve data over those sockets in a Python program. Contd... *A socket is much like a file, except that a single socket provides a two-way connection between two programs. * We can both read from and write to the same socket. * If we write something to a socket, it is sent to the application at the other end of the socket. * If we read from the socket, you are given the data which the other application has sent. * A protocol is a set of precise rules that determine who is to go first, what they are to do, and then what the responses are to that message, and who sends next, and so on. Scanned with CamScannerContd... * We can write a program to retrieve the data for [Link] and compute the frequency of each word in the file as follows: import [Link], [Link], [Link] fhand = [Link](‘[Link]') counts = dict() for line in fhand: words = [Link]().split() for word in words: counts[word] = [Link](word, 0) + 1 print(counts) Scanned with CamScannerSpidering Twitter using a database * bttos://[Link]/code3/twspiderpy ‘Simple database dumpers: import sqlite3 conn = [Link]{'spider-sqlite’) cur = [Link]() curexecute('SELECT * FROM Twitter’) count = 0 for row in cur: print(row) count = count +1 print(count, ‘rows.') [Link]() Scanned with CamScanner
You might also like
Database Basics and SQL Commands
PDF
No ratings yet
Database Basics and SQL Commands
18 pages
Python SQL Database Programming Guide
PDF
No ratings yet
Python SQL Database Programming Guide
8 pages
Python SQLite Programming Guide
PDF
0% (1)
Python SQLite Programming Guide
42 pages
Python Database Handling Guide
PDF
No ratings yet
Python Database Handling Guide
28 pages
Python Database Programming Guide
PDF
No ratings yet
Python Database Programming Guide
27 pages
Data Preprocessing with Pandas in Python
PDF
No ratings yet
Data Preprocessing with Pandas in Python
45 pages
DAP Module3
PDF
No ratings yet
DAP Module3
41 pages
Python Database Management with SQLite
PDF
No ratings yet
Python Database Management with SQLite
20 pages
Python Sqlite Tutorial
PDF
100% (4)
Python Sqlite Tutorial
42 pages
SQLite with Python: A Beginner's Guide
PDF
No ratings yet
SQLite with Python: A Beginner's Guide
7 pages
SQLite and Python Database Tutorial
PDF
No ratings yet
SQLite and Python Database Tutorial
8 pages
Python Unit 4
PDF
No ratings yet
Python Unit 4
8 pages
Python Unit 4
PDF
No ratings yet
Python Unit 4
8 pages
Introduction To SQLite in Python
PDF
No ratings yet
Introduction To SQLite in Python
126 pages
Python MySQL Connectivity Guide
PDF
No ratings yet
Python MySQL Connectivity Guide
2 pages
Understanding Service-Oriented Architecture
PDF
No ratings yet
Understanding Service-Oriented Architecture
9 pages
Python Database Connection Guide
PDF
No ratings yet
Python Database Connection Guide
32 pages
Connect Python to MySQL Database
PDF
No ratings yet
Connect Python to MySQL Database
8 pages
Bank Management System Project Report
PDF
No ratings yet
Bank Management System Project Report
21 pages
Python SQLite Integration Guide
PDF
No ratings yet
Python SQLite Integration Guide
6 pages
SQLite Database Programming Basics
PDF
No ratings yet
SQLite Database Programming Basics
19 pages
Python MySQL Interface Guide
PDF
100% (1)
Python MySQL Interface Guide
40 pages
Python Database Programming Guide
PDF
No ratings yet
Python Database Programming Guide
20 pages
Ex 5
PDF
No ratings yet
Ex 5
2 pages
Python Database Interaction Guide
PDF
No ratings yet
Python Database Interaction Guide
26 pages
SQLite Command Line Usage and Errors
PDF
No ratings yet
SQLite Command Line Usage and Errors
12 pages
Data Preprocessing with Python Pandas
PDF
No ratings yet
Data Preprocessing with Python Pandas
42 pages
A SQLite Tutorial With Python PDF
PDF
100% (2)
A SQLite Tutorial With Python PDF
14 pages
School Management System Project Report
PDF
No ratings yet
School Management System Project Report
32 pages
Connect Python to MySQL Database
PDF
No ratings yet
Connect Python to MySQL Database
28 pages
SQLite Manipulation From Python
PDF
No ratings yet
SQLite Manipulation From Python
14 pages
Python SQLite Database Management Guide
PDF
No ratings yet
Python SQLite Database Management Guide
14 pages
Python MySQL Connectivity Guide
PDF
No ratings yet
Python MySQL Connectivity Guide
10 pages
Python MySQL Connector Guide
PDF
No ratings yet
Python MySQL Connector Guide
28 pages
Python SQLite Tutorial for Beginners
PDF
No ratings yet
Python SQLite Tutorial for Beginners
12 pages
Connect Python to MySQL Database
PDF
No ratings yet
Connect Python to MySQL Database
40 pages
Database Programming Essentials
PDF
No ratings yet
Database Programming Essentials
16 pages
Connecting Python to MySQL Database
PDF
No ratings yet
Connecting Python to MySQL Database
4 pages
Connect Python to MySQL Database
PDF
No ratings yet
Connect Python to MySQL Database
28 pages
Database Operations with Python Tutorial
PDF
No ratings yet
Database Operations with Python Tutorial
7 pages
Python SQLite Basics and Operations
PDF
No ratings yet
Python SQLite Basics and Operations
11 pages
Connect Python to MySQL Database
PDF
No ratings yet
Connect Python to MySQL Database
27 pages
MySQLdb Python Connection Guide
PDF
No ratings yet
MySQLdb Python Connection Guide
24 pages
Python SQLite Database Operations Guide
PDF
No ratings yet
Python SQLite Database Operations Guide
40 pages
Python SQLite Tutorial
PDF
No ratings yet
Python SQLite Tutorial
31 pages
Final Project
PDF
No ratings yet
Final Project
37 pages
Python Database Programming Guide
PDF
No ratings yet
Python Database Programming Guide
5 pages
Installing Pymysql for MySQL Access
PDF
No ratings yet
Installing Pymysql for MySQL Access
30 pages
Python SQL Database Integration Guide
PDF
No ratings yet
Python SQL Database Integration Guide
4 pages
Python MySQL Database Connection Guide
PDF
No ratings yet
Python MySQL Database Connection Guide
188 pages
Python sqlite3 Database Tutorial
PDF
No ratings yet
Python sqlite3 Database Tutorial
18 pages
Python Database Transactions Guide
PDF
No ratings yet
Python Database Transactions Guide
52 pages
Library Management System Overview
PDF
No ratings yet
Library Management System Overview
23 pages
Connect Python to MySQL Database
PDF
No ratings yet
Connect Python to MySQL Database
10 pages
Slide Show
PDF
No ratings yet
Slide Show
28 pages
Tours and Travels Project in Python
PDF
No ratings yet
Tours and Travels Project in Python
29 pages
Connect Python to MySQL Database
PDF
No ratings yet
Connect Python to MySQL Database
28 pages