Python Advanced Programming Guide
Python Advanced Programming Guide
Chapter-1 (Multithreading)
1. Implementing Multithreading in Python
2. Different ways of Creating user-defined Threads in Python
3. Program: Creating a Thread without extending any class – target function not taking any
arguments
4. Program: Creating a Thread without extending any class – target function taking some arguments
5. Program: Demo on creating our own Thread by extending Thread class
6. Program: Demo on creating multiple Threads
7. Synchronization
8. Program: Without Synchronization
9. Program: With Synchronization – using Locks
10. Program: Producer Consumer Threads – Problem (Buggy Program)
11. Program: Producer Consumer Threads – Problem – Solution – using Condition class
12. Program: Producer Consumer Threads – Problem – Solution – using Queue class
DATAPRO COMPUTERS 1
Chapter-6 (Python Database Programming – accessing MySQL Database)
1. Program: Establishing a connection with the MySQL Database and fetching all records in a table
2. Program: Get a particular Record(s) in a table
3. Program: Add/Insert Record
4. Program: Update a Record
5. Program: Delete a Record
6. Program: Establishing a connection with a public MySQL Database Engine Server and fetching all
records in a table
DATAPRO COMPUTERS 2
Chapter-1: Multithreading in Python
• Multiple threads within a process share the same data space with the main thread and can
therefore share information or communicate with each other more easily than if they were
separate processes.
• Threads sometimes called light-weight processes and they do not require much memory
overhead; they are cheaper than processes.
Examples of Multithreading:
• Copy Paste Application
• Media Player Application
• Flight shooting with Machine gun - Game Application (Eg: Sky Battle Game)
• Google Chrome Desktop Web Browser Application
• Web Server implementation – for each user – one thread caters his/her request. (there would be
a readymade pool of threads to cater the requests.)
• Search facility in Google Suggest Box (actual search is done in different Google Servers all over
the world)
• Search facility in the Operating System (to search for files and folders in all the drives – Eg: each
thread searches for the search keyword(s) in a particular Drive of the OS)
• In a Mobile App, where the user uploads a photo to the Server (via one thread), uploads a
document (via another thread) and simultaneously he/she can access the UI.
Note: Multithreaded application would be more affective on a multi-core processor where each core
can process a thread simultaneously.
DATAPRO COMPUTERS 3
Python provides “Thread” class of “threading” module that is useful to create threads. There are
different ways of creating our own thread:
Program: Creating a Thread without extending any class – target function not taking any arguments
Note: We can create a thread by creating an object of Thread class and pass the target function to be
executed parallelly.
Output:
Program: Creating a Thread without extending any class – target function taking some arguments
DATAPRO COMPUTERS 4
Note: Observe the comma (, ) after the argument mentioned in the tuple. Recollect that when a single
element is specified in a tuple, a comma is needed after that element.
Output:
Note:
• Define a new subclass of the Thread class.
• Then, override the run(self [,args]) method to implement what the thread should do when
started.
Once you have created the new Thread subclass, you can create an instance of it and then start a new
thread by invoking the start(), which in turn calls run() method.
DATAPRO COMPUTERS 5
Step2. Run the program
Output:
Sample Execution:
DATAPRO COMPUTERS 6
Program: Demo on creating Multiple Threads
Output:
DATAPRO COMPUTERS 7
Synchronization
At times when more than one thread try to access a shared resource, we need to ensure that resource
will be used by only one thread at a time. The process by which this is achieved is called synchronization.
A race condition occurs when two or more threads can access shared data and they try to change it at
the same time. As a result, the values of variables may be unpredictable/data corruption.
Locks
Locks are typically used to synchronize access to a shared resource. A Lock has only two states —
locked and unlocked. It is created in the unlocked state and has two principal methods — acquire() and
release().
The acquire() method locks the Lock and blocks execution until the release() method in some other
function sets it to unlocked. Then it locks the Lock again and returns True. The release() method should
only be called in the locked state, it sets the state to unlocked and returns immediately. If release() is
called in the unlocked state, a RunTimeError is raised.
lock = Lock()
DATAPRO COMPUTERS 8
Assume that in Reservation counter1, the clerk has sent a request to the server to allot that berth to
his/her passenger. In Reservation counter2, the second clerk has also sent a request to the server to
allot that berth to his passenger. It means two passengers are competing for the same berth (race
condition).
Output:
DATAPRO COMPUTERS 9
Output:
Note: The producer's job is to generate a piece of data, put it into the buffer and start again.
At the same time, the consumer is consuming the data (i.e., removing it from the buffer) one piece at a
time
So, producer and consumer need to run concurrently. Hence we need separate threads for Producer
and Consumer.
We keep one variable which will be global and will be modified by both Producer and Consumer
threads. Producer produces data and adds it to the queue. Consumer consumes data from the queue
i.e. removes it from the queue.
DATAPRO COMPUTERS 10
Output:
Execution 1:
Execution 2:
DATAPRO COMPUTERS 11
Note:
• Producer keeps on adding to the queue and consumer keeps on removing from the queue.
• Since queue is a shared variable, we keep it inside lock to avoid race condition.
• At some point, consumer has consumed everything and producer is still sleeping. Consumer
tries to consume more but since queue is empty, an IndexError is raised.
• But on every execution, before IndexError is raised you will see the print statement telling
“Nothing in queue, but consumer will try to consume”, which explains why you are getting the
error.
When there was nothing in the queue, consumer should have stopped running and waited instead of
trying to consume from the queue. And once producer adds something to the queue, there should be a
way for it to notify the consumer telling that it has added something to queue. So, consumer can again
consume from the queue. And thus IndexError will never be raised.
• Condition in threads.
• wait() method available on Condition instances.
• notify() method available on Condition instances.
Note: Condition object allows one or more threads to wait until notified by another thread.
Condition provides acquire() and release() which calls lock’s acquire() and release() internally, and so we
can replace lock instances with condition instances and our lock behavior will keep working properly.
DATAPRO COMPUTERS 12
Output:
Execution 1:
DATAPRO COMPUTERS 13
Execution 2:
Output:
DATAPRO COMPUTERS 14
Note:
• In place of list, we are using a Queue instance.
• queue has a Condition and that condition has its lock. You don’t need to bother about Condition
and Lock if you use Queue.
• Producer uses put available on queue to insert data in the queue.
• put() has the logic to acquire the lock before inserting data in queue.
• Also put() checks whether the queue is full. If yes, then it calls wait() internally and so producer
starts waiting.
• Consumer uses get.
• get() acquires the lock before removing data from queue.
• get() checks if the queue is empty. If yes, it puts consumer in waiting state.
• get() and put() has proper logic for notify() too.
DATAPRO COMPUTERS 15
Chapter-2: Network/Socket Programming in Python
Note: Before digging into the programming part of networking, 1st let’s understand some of the basic
concepts of Computer Networks.
The main advantage of a network is sharing of resources – data, files and hardware.
The data (of employees/customers) and files (documents/images) in a computer can be shared with
other computers in the network.
It is also possible to share the hardware in the network, Eg: there is no need of having individual printer
for each computer in an office, all the computers can share the single printer – any user can give a print
command sitting at his computer.
DATAPRO COMPUTERS 16
• LAN
• CAN
• MAN
• WAN
Server Machine: The computer which serves the requests of the other computer(s) is known as Server
Machine. Ex.s: File Server, Web Server, Email Server
Client Machine: The computer which sends the requests to the server machine is known as Client
Machine. Ex.s: File Client, Web Client, Email Client
Client and Server software: Both the client and server machines need software to send/receive the
request/response. It means we need a program at client side and another program at server side.
Server program should be up and running first, so that it can handle any client’s request.
Client should first make a connection request, if accepted by the server, only then communication can
take place.
Host ID/IP Address: A unique ID (4 byte number: around 429 crores) for each computer in the network.
Port ID: A unique ID (2 byte number: 0 to 65535) for each server program running on any computer.
Ex1: MySQL server: 3306
Ex2: Oracle server: 1521
Ex3: Apache Tomcat Web Server: 8080
Socket: It is the communication end point for any computer in the network.
We can say, Socket = Host ID + Port ID
Sockets
It is a logical connection point between a Server and client machine so that communication can be done
through that point. Establishing communication between them using sockets is called as “socket
programming”.
We should use a new Port ID for each new socket. The port numbers/IDs from 0 to 1023 are already
allotted for various services and hence we should avoid using these port numbers in our
networking/socket programs
Eg:
DATAPRO COMPUTERS 17
Socket Programming in Python
Sockets are the end-point of a two-way communication link. An endpoint is a combination of IP address
and the port number.
DATAPRO COMPUTERS 18
Python Socket Programming Work Flow
DATAPRO COMPUTERS 19
Note: [Link]() is equivalent to:
[Link](socket.AF_INET, socket.SOCK_STREAM);
AF_INET: represents IP Address version 4 and SOCK_STREAM: indicates that we are using TCP/IP
protocol for communication.
Output:
Note: Encoding and Decoding is not required in Python 2 but required in Python 3
DATAPRO COMPUTERS 20
Note: Instead of “[Link]” we could have even said: “localhost”
Note: The client socket’s port id may way from execution to execution.
DATAPRO COMPUTERS 21
Step2. Write the following Client program
DATAPRO COMPUTERS 22
Step4. Then run the Client program
Client Side:
Server Side:
DATAPRO COMPUTERS 23
Chapter-3: GUI Programming in Python
PyCharm is an IDE used specifically for the Python language. It is developed by the Czech company
JetBrains.
d
Note: First make sure that python is already installed on the desktop
Recollect the location: C:\Users\HP\AppData\Local\Programs\Python\Python35-32
Step2.
Step3.
DATAPRO COMPUTERS 24
Note:
DATAPRO COMPUTERS 25
DATAPRO COMPUTERS 26
Leave the defaults and click “OK”
Step5.
Click “Create”
DATAPRO COMPUTERS 27
Step7. Now edit [Link] as follows:
Note: To increase font size, press Ctrl + Shift + A and type increase font size, click on the option
multiple times.
DATAPRO COMPUTERS 28
Program: GUI Programming in Python – demo
(Tkinter Programming)
Note: Tkinter (Tk-inter) is the standard GUI library for Python. Python when combined with Tkinter
provides a fast and easy way to create GUI applications. Tkinter provides a powerful object-oriented
interface to the Tk GUI toolkit.
Output:
Note: We could have done this program on PyCham IDE as well. So that we can take advantage of
Intellisense of the PyCharm IDE
Some explanation:
Button and Label are the other two classes/widgets/components. Each of them has a parent
widget, which we pass in as the first parameter to the constructor – we have put the label and
button inside the main window, so they are the main window’s children in the tree. We use the
pack() on each widget to position it inside its parent
[Link]() is a method on the main window which we execute when we want to run our
application. This method will loop forever, waiting for events from the user, until the user exits the
program – either by closing the window, or by terminating the program with a keyboard interrupt in the
console.
Note: PyQt is a GUI widgets toolkit. It is a Python interface for Qt, one of the most powerful, and
popular cross-platform GUI library. PyQt is a blend of Python programming language and the Qt library.
PyQt API is a set of modules containing a large number of classes and functions. While QtCore module
contains non-GUI functionality for working with file and directory etc., QtGui module contains all the
graphical controls.
Note: In PyCharm IDE if we get reference warnings at the imports even though we have installed the
modules in the correct locations, then File → Invalidate Caches/Restart
DATAPRO COMPUTERS 30
Note: If we get PyQt5 module not found error then check where it got installed:
Copy the PyQt5 folders and paste them into the appropriate path for the Python IDLE
DATAPRO COMPUTERS 31
Note:
Every PyQt5 application must create an application object. The [Link] parameter is a list of arguments
from a command line. Python scripts can be run from the shell. It is a way how we can control the
startup of our scripts.
Note:
The mainloop receives events from the window system and dispatches them to the application widgets.
The mainloop ends if we call the exit() method or the main widget is destroyed.
Output:
DATAPRO COMPUTERS 32
Note: Using its simple drag and drop interface, a GUI interface can be quickly built without having to
write the code. It is however, not an IDE such as Visual Studio. Hence, Qt Designer does not have the
facility to debug and build the application.
Click Windows Start Button → In the Search box just type “Designer”
(OR)
(a)
DATAPRO COMPUTERS 33
(b) Change the Window Dimensions
DATAPRO COMPUTERS 34
(e) Change it’s label:
DATAPRO COMPUTERS 35
Note: Signals and Slots:
Unlike a console mode application, which is executed in a sequential manner, a GUI based application is
event driven. Functions or methods are executed in response to user’s actions like clicking on a button,
selecting an item from a collection or a mouse click etc., called events.
Widgets used to build the GUI interface act as the source of such events. Each PyQt widget, which is
derived from QObject class, is designed to emit ‘signal’ in response to one or more events. The signal on
its own does not perform any action. Instead, it is ‘connected’ to a ‘slot’. The slot can be any callable
Python function.
Note: This .ui file contains XML representation of widgets and their properties in the design.
Note: So, it uses Android App Development style for designing the UI
Step4. Create a python file which uses the above Python GUI file
DATAPRO COMPUTERS 37
Step5. Run the Application
Output:
Note: In this example, we shall be using the widgets: QMainWindow, QPushButton, QLineEdit,
QComboBox, QLabel, QStatusBar and QMessageBox
DATAPRO COMPUTERS 38
Here we have used the following Widgets:
Line Edit (under “Input Widgets” Category)
Combo Box (under “Input Widgets” Category)
Label (under “Display Widgets” Category)
Push Button (under “Buttons” Category)
Step2. Drag and Drop the required Widgets on to the Designer window
To Increase Font size for the label (=) → Select it → in its Property Editor window → Go to Font
Property and increase the font size
Step3. To Remove the MenuBar, go to ObjectInspector Window → select MenuBar , Right Click →
Remove
Step4. For the 1st TextBox(Line Edit Widget) → Set the ToolTip property value to: Enter First Number
This tooltip message would be displayed when the user hovers the mouse pointer over it.
Note: For the 3rd TextBox (Line Edit Widget) → Set the ReadOnly property to True
Step5. To add items to the ComboBox, just double click on it and add the items
DATAPRO COMPUTERS 39
Then change its “text” property to “Clear”
Similarly, for the “Calculate” button, change the object name to: calculateButton and its text
(a) Select the “Clear” Button and go to its “Signal/Slot” Editor Window:
Initially it shows:
DATAPRO COMPUTERS 40
(b) Double on each of the “Sender”, “Signal”, “Receiver” and “Slot” and select appropriate items
Step8. To Check:
DATAPRO COMPUTERS 41
Enter two numbers and click “Clear” button, we can notice that the two “Line Edit” widgets gets cleared.
Solution:
DATAPRO COMPUTERS 42
Note: Just make a Copy Paste don’t do Cut and Paste
Step10. We can convert this C++ Code into Python Code using the following tool:
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
[Link]("MainWindow")
[Link](400, 200)
[Link] = [Link](MainWindow)
[Link]("centralwidget")
self.lineEdit1 = [Link]([Link])
[Link]([Link](10, 40, 61, 31))
[Link]("lineEdit1")
[Link] = [Link]([Link])
[Link]([Link](90, 40, 51, 31))
font = [Link]()
[Link](14)
[Link](True)
[Link](75)
[Link](font)
[Link]("comboBox")
[Link]("")
[Link]("")
[Link]("")
[Link]("")
self.lineEdit2 = [Link]([Link])
[Link]([Link](160, 40, 61, 31))
[Link]("lineEdit2")
[Link] = [Link]([Link])
[Link]([Link](240, 50, 21, 21))
font = [Link]()
[Link](14)
[Link](True)
[Link](75)
[Link](font)
[Link]("label")
self.lineEdit3 = [Link]([Link])
[Link]([Link](290, 40, 81, 31))
[Link](True)
[Link]("lineEdit3")
[Link] = [Link]([Link])
[Link]([Link](90, 90, 81, 31))
[Link]("clearButton")
[Link] = [Link]([Link])
[Link]([Link](220, 90, 81, 31))
[Link]("calculateButton")
self.label_2 = [Link]([Link])
self.label_2.setGeometry([Link](106, 10, 171, 20))
DATAPRO COMPUTERS 44
font = [Link]()
[Link](14)
[Link](True)
[Link](75)
self.label_2.setFont(font)
self.label_2.setObjectName("label_2")
[Link]([Link])
[Link] = [Link](MainWindow)
[Link]("statusbar")
[Link]([Link])
[Link](MainWindow)
[Link]([Link])
[Link]([Link])
[Link]([Link])
[Link](MainWindow)
if __name__ == "__main__":
import sys
app = [Link]([Link])
MainWindow = [Link]()
ui = Ui_MainWindow()
[Link](MainWindow)
[Link]()
[Link](app.exec_())
Step12. Create a new python file – [Link] which contains the implementation of “Calculate” Button
click functionality
DATAPRO COMPUTERS 45
Step13. Run the Program
Output:
Note: If we give invalid input like a non-numerical value or dividing integer with zero:
Note: The advantage is we need not open the Python IDLE to run the program. And this file can be run
on any Windows Computer by just double clicking on it.
Step1.
DATAPRO COMPUTERS 46
Step2. Now go to the folder where python code file is located
DATAPRO COMPUTERS 47
…
…
…
Note: Notice that the following files and directories get generated:
Note: this flag prevents a console window from being displayed when the application is run.
DATAPRO COMPUTERS 48
Step4. Open [Link] (Application)
DATAPRO COMPUTERS 49
…
…
…
Note: The flag “F” indicates only one file should be generated (package everything into a single
executable)
DATAPRO COMPUTERS 50
Place an icon file in the current working directory:
…
…
…
DATAPRO COMPUTERS 51
Note: It may not show the updated icon. Just place it in some other location, we can see the change.
Place the file on the desktop, double click and run the application
DATAPRO COMPUTERS 52
Chapter-4: Sending Email
Note: The smtplib modules is useful for communicating with mail servers to send mail.
sendmail() arguments: sender’s email id, receiver’s email id and body
Program: Sending Email from Python code – Ex2 (Sending to Multiple Receivers)
Program: Sending Email from Python code – Ex3 (Sending message with a subject)
DATAPRO COMPUTERS 53
Output (check the receiver’s email account):
Program: Sending Email from Python code – Ex4 (Sending message with File Attachment)
Note: Try attaching different types of files as well like jpg, pdf
Note: If any of the email ids doesn’t exist then that would just ignored.
Note: If any of the files doesn’t exist then the program won’t work.
DATAPRO COMPUTERS 54
Output:
DATAPRO COMPUTERS 55
Chapter-5: Python - XML and JSON Processing
Note: We shall use the [Link] module which implements a simple and efficient API for
parsing XML data.
…
…
…
Output:
DATAPRO COMPUTERS 56
Program: XML Data processing Demo2 – findall()
Output:
DATAPRO COMPUTERS 57
Program: XML Data Processing Demo3 – iter()
Output:
DATAPRO COMPUTERS 58
Step1. Write the following program
Output:
Note: Notice that “address” is an object (notice braces) and “phoneNumber” is an array (notice
squarebrackets)
Program: Python JSON data processing Demo2 – traversing the details of all Employees
DATAPRO COMPUTERS 59
Output:
Program: Python JSON Data processing Demo3 – getting a particular key’s value
DATAPRO COMPUTERS 60
Step1. Write the following program
Output:
Program: Python JSON Data Processing Demo4 – getting nth key’s value in an array
Output:
DATAPRO COMPUTERS 61
Step2. Run the program
Output:
DATAPRO COMPUTERS 62
Chapter-6: Python Database Programming - Accessing MySQL Database
Note: Let’s begin with creating a new Database in MySQL Database Engine, Create a user, Create a table
and put some records into it. Then we shall write a program to get those records
Part-1
(Download, install and configure XAMPP Server)
Step1.
XAMPP: Cross Platorm (X), Apache Web Server, MySQL Database, PHP and Perl
Step2.
DATAPRO COMPUTERS 63
[Link] gets downloaded
DATAPRO COMPUTERS 64
DATAPRO COMPUTERS 65
Click “Finish”, control panel gets started.
DATAPRO COMPUTERS 66
Step5. Click on “NetStat” button, to check which port numbers are busy
DATAPRO COMPUTERS 67
So, at Port 80, some process is already running. So we have change the port id of Apache HTTP Server
whose default port id is 80.
Open the [Link] file and modify the http listening port id:
Before Modification:
After modification:
Save it
DATAPRO COMPUTERS 68
Now Apache server is up and running
• web server
• installation of MySQL Database
Step9. Open any web browser and in the address bar, type: localhost:8080
DATAPRO COMPUTERS 69
Part-2
(In MySQL, Create a Database, a table with some data and a user to access it)
Name it as “for_python_db1”
DATAPRO COMPUTERS 70
DATAPRO COMPUTERS 71
Step5. Creating a table in our database
DATAPRO COMPUTERS 72
Click “Save”
DATAPRO COMPUTERS 73
Step6. Now add data/records
DATAPRO COMPUTERS 74
Part-3
(Connecting to the above MySQL database via a Python Program)
Note: PyMySQL is an interface for connecting to a MySQL database server from a Python Program. It
implements the Python Database API v2.0 and contains a pure-Python MySQL client library.
DATAPRO COMPUTERS 75
Note: Make sure that XAMPP Server is up and running
Output:
Output:
DATAPRO COMPUTERS 76
Step2. Run the program
Output:
DATAPRO COMPUTERS 77
Output:
Output:
DATAPRO COMPUTERS 78
Program: Establishing a connection with a public MySQL Database Engine Server and fetching all
records in a table
Part-1
(Creating a Live Public MySQL Database table)
DATAPRO COMPUTERS 79
Step2. Create a new Database:
DATAPRO COMPUTERS 80
Note: We can know these credentials from our Email
DATAPRO COMPUTERS 81
Step7. Add Records
DATAPRO COMPUTERS 82
Part-2
Step1. Write the following Python program
Output:
DATAPRO COMPUTERS 83
Chapter-7: Python Database Programming – accessing Oracle Database
Establishing a connection with the Oracle Database and fetching all records in a table
Part-1
(Download, install Oracle Database Engine/Server)
Note: Make sure that the Oracle Database software is a 64-bit version.
[Link]
After download:
(OR)
Go to: [Link]
DATAPRO COMPUTERS 84
Step2. Extract it to a folder
Step4.
DATAPRO COMPUTERS 85
During installation enter the DBA’s password and remember it, we need it for later use.
Username: “system”
Password: say “datapro”
Step1.
SQL>connect hr/hr
DATAPRO COMPUTERS 86
Note: select * from tab;
Part-2
(Connecting to the above Oracle database via a Python Program)
Step3.
DATAPRO COMPUTERS 87
Step4. Run the program
Note: The problem is we are using Python 32-bit but our Oracle driver is 64-bit and Oracle Database
server is 64-bit too
(a) Download it
DATAPRO COMPUTERS 88
(b) Uninstall the 32-bit Python
Step7. Re-Verify
Output:
Output:
Verify:
DATAPRO COMPUTERS 90
Program: Invoking a stored procedure in Oracle DB
A stored procedure is a set of Structured Query Language (SQL) statements with an assigned name,
which are stored in a relational database management system as a group, so it can be reused and
shared by multiple programs.
Note: A function is a subprogram that computes and returns a value whereas a procedure doesn’t
return any value.
Once compiled, it is a schema object known as a stored procedure or stored function, which can be
referenced or called any number of times by multiple applications connected to Oracle Database XE.
Both stored procedures and functions can accept parameters when they are executed (called).
Note: Remember to put the “commit” statement, for python, explicit commit is required unlike JDBC in
Java.
Test it:
sql> exec updateraju1(201, 60000);
DATAPRO COMPUTERS 91
Output:
Before:
Test it:
DATAPRO COMPUTERS 92
Step2. Invoke the above procedure
Output:
Test it:
sql>select getavgraju1(100) from dual;
DATAPRO COMPUTERS 93
Output:
DATAPRO COMPUTERS 94
Chapter-8: Python Database Programming – accessing MongoDB Database
Program1: Establishing a connection with the MongoDB Database and fetching all documents in a
collection
Part-1
Installing MongoDB
Note: The installers for MongoDB are available in both the 32-bit and 64-bit format. The 32-bit installers
are good for development and test environments. But for production environments you should use the
64-bit installers. Otherwise, you can be limited to the amount of data that can be stored within
MongoDB.
Step1.
DATAPRO COMPUTERS 96
Step3. To Verify:
StepA:
Note: The “[Link]” – a command line application: is the actual MongoDB Database, whereas to
write the commands for adding /removing data, we have to use “[Link]”
StepB: Inside the “bin” folder window, Shift + Right Click on an empty area →
Notice that automatically, command prompt gets opened with path to “bin” directory:
DATAPRO COMPUTERS 97
Note: The problem is it looks for “data\db” directory in the C:
DATAPRO COMPUTERS 98
Note: Every time we want to start the MongoDB Database server to have to go to the “bin” directory,
instead we can set path to this directory:
DATAPRO COMPUTERS 99
To type the commands to add and delete data, we have to open “[Link]”
StepF:
Part-2
Part-3
Output:
Output:
Output:
Output:
Output:
Output:
Step1.
Take a note of the connection string, which we shall use in the client program
mongodb+srv://bvraju2020:<password>@[Link]/test
[Link]
1st Login:
Step1.
Step3. Solution:
Output:
What is Firebase
Firebase is essentially a real time database. The Firebase Realtime Database is a cloud-hosted NoSQL database
that lets you store and sync data between your users in Realtime.
In normal database when data at back end get updated, to get the newest data, we need to refresh our browser
or android app screen in order to get updated data.
On other hand in Realtime databases like firebase we don't even need to do any refresh. Changes done from any
other client browser/Android App will be reflected to all connected clients without making any server-side call.
Step1. [Link]
Step2.
Step1.
(OR)
Choose:
Firebase Vs Firestore
Cloud Firestore is Firebase’s newest flagship database for mobile apps. It is a successor to the Realtime Database
with a new and more intuitive data model. Cloud Firestore is richer, faster, and more scalable than the Realtime
Database.
Realtime Database stores data as one large JSON tree which makes it easier to store simple data but harder to
organize complex, hierarchical data at scale.
Cloud Firestore stores data in documents arranged in collections. Simple data is stored in documents, which is
easy and similar to the way data is stored in JSON. Complex, hierarchical data is conveniently organized at scale
using subcollections within documents
Step2.
Program: To add a new Record/Object in Firebase database (Connecting to Firebase using Python)
Step1. python-firebase highly makes use of the requests library so before you begin, you need to have that
package installed.
Note: FirebaseApplication() takes two parameters; one is URL of database and second is authentication details for
database. But we don’t have any rules so we are passing None.
async is a keyword in Python 3.7 and it is used as module name in firebase package.
Now it is working
Expand them:
Step1.
Step3.
…
…
then:
Output:
Note: The user token will need to be passed as a parameter to the get(), push(), set(), update() and remove()
functions in order to authorize the actions.
Step3. Run the program with different course details and then Verify in the Firebase database
Step3. Add few more records and Verify in the Firebase database
Note: If we mention an existing course id: say “datapro1” again, then course gets updated. So these ids are
unique.
Output: