Oracle SODA for Python

Simple Oracle Document Access (SODA) set of APIs that allow you to create collection of documents in Oracle Database, so that later you can retrieve/query those documents. Using SODA implementation you can perform CRUD (create,read,update,delete) on documents. Document can be of any MIME type, in this blog we will focus on JSON.

There are separate SODA implementations available for languages like Java, Python, PL/SQL & C etc. however SODA for REST can be accessed from all those languages which support REST framework. Refer Oracle documentation for other implementation : Oracle SODA.

In this blog we will explore SODA for Python implementation. We will see how we can store/retrieve/filter JSON document in Oracle Database using Python. Oracle Database supports storing and querying JSON data natively.

Refer this blog for understanding JSON: What is JSON?


Prerequisite: Oracle Client 18.3 or higher, Oracle Database 18.1 or higher required for SODA. After that assign SODA_APP role to the database user in which you are going to create SODA collections.

-- Check client version using below query
SELECT distinct client_version
FROM v$session_connect_info
WHERE sid = SYS_CONTEXT('USERENV', 'SID');

-- Check database version using below query
SELECT * FROM v$version;
--or
SELECT * FROM v$instance; 
-- SODA grant
GRANT SODA_APP TO <DB-USER>;

I’m using Oracle 19c Database, Python3 & cx_Oracle version 8. SODA is part of Oracle Python module cx_Oracle no need to install any other module.

Other Python Module used: configparser, json & requests.


SODA Collection

Soda collection is nothing but a database table. Collections contains document which can be represent as row of database table. createCollection method create a new collection in database & if collection already exists its just open without error.

SodaDatabase.createCollection(name, metadata=None, mapMode=False)

Lets create one simple collection providing only name argument.

print('Starting session...')
try:
    dsn = cx_Oracle.makedsn(hostname, port, service_name=servicename)
    conn = cx_Oracle.connect(username,password,dsn,encoding=encoding)
    print('Connected:' + conn.version)

    soda = conn.getSodaDatabase()
    collection = soda.createCollection("first_collection")
    conn.close()
    print('connection closed...')
except cx_Oracle.Error as e:
    print('Error:', e)

Collection FIRST_COLLECTION i.e. created using Python code: See below objects created by default in the database: Table, Index & Object

Collection Metadata: ‘FIRST_COLLECTION’

As metadata argument is not specified at the time of collection creation. Hence by default Oracle created a collection that support JSON document only & uses system generated keys. You can also provide metadata at the time of collection creation: Refer soda-collection-metadata-components-reference.

See below “JSON_DOCUMENT” constraint added automatically. You cannot store non json document in this collection, it will raise exception.

Insert Documents

Let’s insert some JSON document in this collection “FIRST_COLLECTION”. Here we have used GitHub free API to fetch some JSON data using request module.

We will use insertOne method to insert document. Input argument must be a SODA document or a dictionary or list. Refer below how to create a SODA document.

print('Starting session...')
try:
    dsn = cx_Oracle.makedsn(hostname, port, service_name=servicename)
    conn = cx_Oracle.connect(username,password,dsn,encoding=encoding)
    print('Connected:' + conn.version)

    soda = conn.getSodaDatabase()
    collection = soda.createCollection("first_collection")

    url = 'https://api.github.com/users/shobhit-singh/repos'
    req = requests.get(url)
    text = req.text

    parsed_dict = json.loads(text)
    collection.insertOne(parsed_dict)

    conn.close()
    print('connection closed...')
except cx_Oracle.Error as e:
    print('Error:', e)

A document is created in the table FIRST_COLLECTION: Refer JSON_DOCUMENT column for JSON data.

Code snippet for inserting json document using file:

try:
    dsn = cx_Oracle.makedsn(hostname, port, service_name=servicename)
    conn = cx_Oracle.connect(username,password,dsn,encoding=encoding)
    print('Connected:' + conn.version)

    soda = conn.getSodaDatabase()
    collection = soda.createCollection("first_collection")

    with open('jsonndata.json') as f:
        data = json.load(f)

    collection.insertOne(data)
    conn.commit()
    conn.close()
    #print('connection closed...')
except cx_Oracle.Error as e:
    print('Error:', e)

There are other ways also by which you can insert document in collection. Like insertOneAndGet, insertMany etc. Refer api_manual/soda

Get Collection Names

To get all collection names present in database. Use getCollectionNames method:

print('Starting session...')
try:
    dsn = cx_Oracle.makedsn(hostname, port, service_name=servicename)
    conn = cx_Oracle.connect(username,password,dsn,encoding=encoding)
    print('Connected:' + conn.version)

    soda = conn.getSodaDatabase()
    name = soda.getCollectionNames(limit=5)
    print(name)

    conn.close()
    print('connection closed...')
except cx_Oracle.Error as e:
    print('Error:', e)
        

There are various method available for collections like drop collection, find, truncate etc. Refer this link for details : soda-collection-object

Printing metadata of collection
print('Starting session...')
try:
    dsn = cx_Oracle.makedsn(hostname, port, service_name=servicename)
    conn = cx_Oracle.connect(username,password,dsn,encoding=encoding)
    print('Connected:' + conn.version)

    soda = conn.getSodaDatabase()
    coll = soda.openCollection("git_repos")
    print(coll.metadata)

    conn.close()
    print('connection closed...')
except cx_Oracle.Error as e:
    print('Error:', e)
Get all documents inside a collection
print('Starting session...')
try:
    dsn = cx_Oracle.makedsn(hostname, port, service_name=servicename)
    conn = cx_Oracle.connect(username,password,dsn,encoding=encoding)
    print('Connected:' + conn.version)

    soda = conn.getSodaDatabase()
    coll = soda.openCollection("first_collection")
    doc = coll.find()
    print(doc.getDocuments())

    conn.close()
    print('connection closed...')
except cx_Oracle.Error as e:
    print('Error:', e)

Retrieving Data

Retrieve JSON data from the document. Let’s just print all GitHub repo names present in that JSON.

print('Starting session...')
try:
    dsn = cx_Oracle.makedsn(hostname, port, service_name=servicename)
    conn = cx_Oracle.connect(username,password,dsn,encoding=encoding)
    print('Connected:' + conn.version)

    soda = conn.getSodaDatabase()
    coll = soda.openCollection("first_collection")
    doc = coll.find()
    docs = doc.getDocuments()
    res = docs[0].getContent()

    for i in res:
        print (i["name"])

    # dumping complete data as json file
    json.dump(res, open ('data.json', 'w'), indent=4)

    conn.close()
    print('connection closed...')
except cx_Oracle.Error as e:
    print('Error:', e)
Filtering JSON documents data

Filter documents records in collection on the basis of some input dictionary or JSON string. Filter specification is also called a query-by-example (QBE).

Refer this guide for filter specification details. overview-soda-filter-specifications-qbes

try:
    dsn = cx_Oracle.makedsn(hostname, port, service_name=servicename)
    conn = cx_Oracle.connect(username,password,dsn,encoding=encoding)
    print('Connected:' + conn.version)

    soda = conn.getSodaDatabase()
    coll = soda.openCollection("first_collection")
    doc = coll.find()    
    docs = doc.filter({"Numbers": {"0": "Zero", "1": "One"}})
    #docs = doc.filter({"name": "BigDataEnthusiast"})

    print( 'Count' ,docs.count())
    print( 'Doc Key:' , docs.getDocuments())

    conn.close()
    print('connection closed...')
except cx_Oracle.Error as e:
    print('Error:', e)

There are so many method available for collections/documents. You can refer below mentioned cx_orale documentation for more learning.

Refer GitHub link all code used in blog: github.com/shobhit-singh/Python-Programs/tree/master/cx_oracle_soda

References:


Thanks!
Happy Learning! Your feedback would be appreciated!

What is JSON?

What is JSON?

While working with the Web Applications, REST APIs or document databases (eg. Oracle Autonomous JSON Database) we always deals with JSON. What is JSON & why its ideal data interchange format. Lets explore!

JSON – Java Script Object Notation

  • Derived from JavaScript.
  • Language independent text format for structuring data.
  • Light weight, easy to read/parse information.
  • Almost all language support this format eg. Python, R, Java, PL/SQL etc.
  • File extension: .json
  • Internet MIME Type: application/json

JSON is built using: Key Value Pair & Array – Ordered elements

  • Key:Value Pair ( Like Hash Map, Dict in Python, Associative array in PL/SQL)
  • Ordered list of values. (Array, List) example [1,2,3]

Sampe JSON:

{
  "firstName": "Calos",
  "lastName": "Smith",
  "isAlive": true,
  "age": 33,
  "address": {
    "streetAddress": "XYZ Street",
    "city": "New York",
    "state": "NY",
    "postalCode": "10021-3100"
  },
  "phoneNumbers": [
    {
      "type": "home",
      "number": "111 111-1234"
    },
    {
      "type": "office",
      "number": "111 555-4567"
    }
  ],
  "children": ["alex","marry"],
  "spouse": null
}

Some JSON Fundamentals

  • Key: Always string (double quotes only)
  • Value: String (double quotes only), Number, Bool (true/False), Object or List & Null.
  • Object: Unordered set of key value pairs. Object begins with { & ends with }. Inside object – Key:Value (key followed by a colon followed by the value always) separated by comma ex. { key1:par1, key2:pair2 }
  • Array: Ordered collection of values. Start with [ & ends with ]. Values separated by comma. [1,2,3,4] or [“A”, “B”,”C”,”D”].

See below example :

  • address is object – As it contains key values pairs. Example of nested object also as address is inside one big object.
  • children is example of array – you can access elements with index like children[0]
  • phoneNumbers . Objects inside Array.
{
	"age": 33,
	"address": {
		"streetAddress": "XYZ Street",
		"city": "New York",
		"state": "NY",
		"postalCode": "10021-3100"
	},
	"phoneNumbers": [{
			"type": "home",
			"number": "111 111-1234"
		},
		{
			"type": "office",
			"number": "111 555-4567"
		}
	],
	"children": ["alex", "marry"]
}

Python In-Built Module JSON

De-serialization – Decoding JSON data into python native datatype dict.

a) Reading JSON Data from API & converting it to Python Dictionary

import json
import requests

url = 'https://api.publicapis.org/entries'
req = requests.get(url)
text = req.text
print (type(text)) 

# json.loads - It will create a Python Dictionary
parsed_dict = json.loads(text)
print (type(parsed_dict))
print ((parsed_dict['entries'][2]))

Other example: Normal JSON String. Converting back to Python Dict

import json

normal_json_str = '{"id":101,"parent_id":null, "name":"XYZ", "is_owner":true}'
print(normal_json_str)
print(type(normal_json_str))

# json.loads - It will create a Python Dictionary
parsed_dict = json.loads(normal_json_str)

print(parsed_dict)
print(type(parsed_dict))

b) Reading JSON Data from file & converting it to Python Dictionary

import json

with open('sampledata.json') as f:
    data = json.load(f)
    print (type(data))
    print ((data['entries'][2]))

Serialization – Encoding data into native JSON.

a) Converting Python List to JSON Data & printing it. Output is string

import json

my_dict = { 'Aphabets' : { 'A':{'Fruit':'Apple','Object':'Aeroplane'},'B':{'Fruit':'Banana','Object':'Ball'}} , 
             'Numbers'  : {  0:'Zero', 1:'One'} 
           } 
print(type(my_dict))

print(json.dumps(my_dict, indent=4))

b) Converting Python List to JSON Data & saving it as file.

import json

my_dict = { 'Aphabets' : { 'A':{'Fruit':'Apple','Object':'Aeroplane'},'B':{'Fruit':'Banana','Object':'Ball'}} , 
             'Numbers'  : {  0:'Zero', 1:'One'} 
           } 
print(type(my_dict))

json.dump(my_dict, open ('jsonndata.json', 'w'), indent=4)

I have used jsonlint.com for validating JSON.

References:


Thanks!
Happy Learning! Your feedback would be appreciated!

Jupyter Notebook Setup | Python & R

Jupyter Notebook Setup | Python & R

In this blog we will explore what is Jupyter Notebook & how we can setup in Windows 10 for Python & R.


Jupyter Notebook – open source web application that you can use to create and share documents that contain code, code output, visualizations, and text. You can include markdown in the jupyter notebooks.

Best way to write, execute code & share the output as document. See below sample notebook for R. Refer below screenshot contains markdown text, code & its output for R & Python.

Jupyter supports many programming languages, including Python, R and Scala.

Installation for Python & R:

For R: Just need to run below commands:

install.packages('IRkernel')
IRkernel::installspec()	
IRkernel::installspec(user = FALSE)

Installation is completed, now you can start creating & sharing notebooks.

Starting Jupyter Notebook

Go to the command prompt, change directory where you want to start the jupyter notebook, it will store all files in this directory only. Execute command: jupyter notebook , it will start the notebook application : http://localhost:8888/tree

Creating Notebook

Go the jupyter notebook home page & click on the new. Refer below screenshot, it is asking for the language, I have setup jupyter for R as well as Python. You can create new as well as run existing notebook files also.

You can create normal text file & folder in the directory where you have started the jupyter notebook.

Running Notebook using R

See below reference example of running the notebook for R language. It has markdown text, R code as well as code output.

Running Notebook using Python

See below reference example of running the notebook for Python language.

Exporting Notebook

You have option to download the notebook as html /ipynb/pfd… etc. Later you can share the notebook in GitHub, email or any blog.

Refer sample .ipynb notebooks I have pushed in GitHub: https://github.com/shobhit-singh/Python-Learning-Journey


Thanks!

Happy Learning! Your feedback would be appreciated!

Calling Oracle Database REST APIs using Python

Calling Oracle Database REST APIs using Python

In previous blog we have seen how we can enable REST Services in database schema using ORDS. Also we have created REST API using GET,POST & DELETE Method. Oracle Rest Data Services (ORDS) enable REST interface for the Oracle Database, so that you can create RESTfull APIs that uses HTTP/HTTPS requests to GET, PUT, POST & DELETE resource in the database table.

Refer below blogs for REST Service & APIs setup.

In this blog we will call Oracle Database REST APIs using Python.


REST API 1: For retrieving customer email based on text pattern (GET Method)

import requests
import json

url = "http://localhost:8080/ords/customerorders/search/adam"
req = requests.get(url)
print('Response code received: {code} '.format(code=req.status_code))
if req.status_code == 200:
    req_text_dict = json.loads(req.text)
    for i in req_text_dict['items']:
        print(i)
else:
    print("Some issue in API")

REST API 2: For retrieving orders based on customer email & status (GET Method)

import requests
import json

url = "http://localhost:8080/ords/customerorders/serachorder/orders/"
payload = (('CUSTOMER_ID', 272), ('ORDER_STATUS', "CANCELLED"))
req = requests.get(url, params=payload)

print('Response code received: {code} '.format(code=req.status_code))
if req.status_code == 200:
    req_text_dict = json.loads(req.text)
    for i in req_text_dict['items']:
        print(i)
else:
    print("Some issue in API")

REST API 3: For creating new customer entry (PUT Method)

import requests
import json

url = "http://localhost:8080/ords/customerorders/customer/addcust"
payload = (('EMAIL_ADDRESS', "devuser1@test.com"), ('FULL_NAME', "DevUser1"))
req = requests.post(url, params=payload)
print('Response code received: {code} '.format(code=req.status_code))
if req.status_code == 200:
    req_text_dict = json.loads(req.text)
    print(req_text_dict)
else:
    print("Some issue in API")

REST API 4: For deleting customer entry based using email id (DELETE Method)

import requests
import json

url = "http://localhost:8080/ords/customerorders/customer/addcust"
payload = ('EMAIL_ADDRESS', "devuser1@test.com")
req = requests.delete(url, data=json.dumps(payload))
print('Response code received: {code} '.format(code=req.status_code))
if req.status_code == 200:
    req_text_dict = json.loads(req.text)
    print(req_text_dict)
else:
    print("Some issue in API")

Schema Used: Customer-Orders Sample Schema | Oracle 12c

Thanks!

Happy Learning! Your feedback would be appreciated!

Exploring Docker

Exploring Docker

Problem Statement: Let say we have to setup multiple application (App 1, App 2 & App 3) on machine. All these application require different version of software/libraries dependencies. How we can setup applications so that there is no conflict of libraries version between applications.

Earlier times approach where we can setup different physical machines for all the applications. Following are some disadvantages:

  • Huge cost involved for setup different machines.
  • Wastage of resources in individual machines.
  • Difficult to scale & manage the applications.

Old Approach: Setup VMs (Virtual Machines) on top of one host machine & run applications separately. See below diagram

In this kind of hypervisor based virtualization model each VM has its own OS i.e. separate resources allocated for VM (RAM, HDD and CPU). Following are some disadvantages:

  • Entire OS loads first then the app start. So Boot time is slow.
  • VMs are generally huge is size (GB’s).
  • Wastage of unused resources in VM.
  • Deployment is not easy.

Latest Approach: Containerization – Process of packaging of an application with its required files, libraries/dependencies to run in efficient way in isolated user space called container.

Its a form of OS virtualization, where containers shares the host OS kernel. Containers are light weight as it holds only required files & libs & consume resources whenever required.

Source: pexels.com (Free Licence)

What is Docker?

‘Container based technology’ which enable developer to create, run & deploy application as efficient light weight container. You can create the containers using the docker images i.e. read only template. You can get the images for OS, Programming Language, Databases, DevOps etc.

Visit Docker Hub for more details.

Containers shares the host OS kernel

Docker Installation:

Docker is easy to install application, available for variety of Linux, macOS & Windows. There are several methods to install the Docker on your machine, you can refer all the methods at docs.docker.com/

In this blog we will install docker using the shell script on Ubuntu box.

curl -fsSL https://get.docker.com -o get-docker.sh
sudo sh het-docker.sh

Checking the docker version after installation using docker -v or docker –version

Testing Docker Installation:

Docker is now installed on the system, lets run the first container to test the docker installation using docker official image “Hello-World”. You can refer the complete documentation of this image here.

Pulling the image of ‘hello-word‘ from docker hub. You can check all downloaded images in your local repository using docker images.

Now we have hello-world image present in local repository. We can use docker run command to launch the container using this image.

Listing all the container using docker ps -a command.

We are able to test the doker installation by running first container successfully. Let’s move to next step by creating the custom images by passing our own set of code.


Creating Custom Docker Image:

There are many options to create the custom docker image. Here we are going to use the Dockerfile to create multiple custom docker custom images.

Here I’m going to create two custom images using the base images of Python version 2.7 & 3.8 and will provide common python code for both the apps. Later going to create the containers for these images.

I have create one Dockerfile, first I’m using Python 2.7 version image as base.

Sample python script:

Creating custom image for python 2.7 using docker build command.

python2.7app custom image is created

After this I have edited the Dockerfile & changed the Python version to 3.8

Creating second custom docker image for python 3.8:

python3.8app custom image is created

Checking all the docker images: So we have our own custom images created. See below image python2.7app & python3.8app.

Launching Docker Containers:

Containers created for separate images & code is also executed.

Checking all the container using docker ps -a command

Check the details of containers like IP, Ports etc using inspect command.

Pushing custom images to Docker Hub:

First you have to sign up for docker hub: hub.docker. You will get you docker id i.e. username.

docker tag <image-id> username/<image-name>

docker login

# provide your docker hub credentials

To push the image :

docker push username/<image-id>

You can check your image in hub.docker

Removing the Docker Images/Containers:

# Remove all stopped containers 
docker rm $(docker ps -a -q)
# Remove single container 
docker rm <container-id>
# Remove single image
docker rmi <image-id>

Thanks!

Happy Learning! Your feedback would be appreciated!

ODI 12c – Setting CDC/Journalizing

ODI 12c – Setting CDC/Journalizing

In this blog we will see step by step how we can setup the change data capture (CDC)/journalizing in ODI 12c.

Change data capture as the name suggest the process to identify the change in source data whether the records inserted/updated or deleted from the source systems. After identifying the change data & applying the same in targets.  We will explore here the complete process & objects required to setup the CDC in ODI 12c.

ODI  Journalizing Modes:

Simple –  Capture changes for individual data-stores in a model, does not support referential integrity between the data-store.

Consistent Set – It also support the referential integrity between data-stores. Group of datastores journalized in this mode is called ‘Consistent Set’.


Step 1. Import JKM:

Import the Journalizing Knowledge Model – JKM Oracle Simple

JKM

Create the Model for your source data-store. Select the ‘Journalizing Mode‘ as simple & select the correct JKM from drop down. Refer below screenshot.

Model
Model

Reverse engineer your tables, make sure it has some key.

Step 2. Add Subscriber:

Subscriber: It is a application or process which consume the captured change data. When subscribers have consumed the captured changes, later on changes were discarded from the journals.

If you do not want to add any subscriber to your data-store, by default ‘SUNOPSIS‘ will be there.

Subcriber
Add Subscriber

Step 3. Add to CDC:

You are adding your data-store to CDC process.

addtocdc
Add to CDC

If you open your data-store,  go to Journalizing tab. You will see a message that table is included in CDC. Also the clock sign will come on  your data-store.

CDC addeed
Data-store

Step 4. Start Journal:

Start the journal, select the subscriber.  Select context & run. It will create all the objects using which change data can be captured in J$ tables.

startjournal

journal
Journal Steps

Below objects created in database. Two views are created: the JV$ view and the JV$D view.

  • TABLES: J$ACCOUNTS_STAGE & SNP_SUBSCRIBERS
  • TRIGGERT$ACCOUNTS_STAGE
  • VIEWS: JV$ACCOUNTS_STAGE & JV$DACCOUNTS_STAGE

Subscriber Table:

ACCOUNTS_STAGE Table registered as subscriber in SNP_SUBSCRIBERS.

subsciber

J$ Table:

I have inserted 4 records in my staging table ACCOUNTS_STAGE manually. After commit I have noticed that 4 records also inserted in my J$ Tabe i.e. J$ACCOUNTS_STAGE with consume flag as 0 i.e. records not yet consumed. J$ Table J$ACCOUNTS_STAGE has only 5 columns, last one is the key of table. 

  • JRN_SUBSCRIBER
  • JRN_CONSUMED
  • JRN_FLAG
  • JRN_DATE
  • ACCOUNT_ID

j$ table

Above records are inserted by the trigger T$ACCOUNTS_STAGE on ACCOUNTS_STAGE. 

Step 5. Journalizing Filter in Mapping :

You can set your subscriber here in filter.

journalizing filter

Step 6. Journalizing Data Only:

Tick the ‘Check box’ for ‘Journalizing Data Only‘.

journa_data_only

JV$ view:

JV$ACCOUNTS_STAGE is used in the mappings where you select the option Journalized data only. This view is used to insert the records in I$ flow table.

Records from the J$ table ( J$ACCOUNTS_STAGE) are filtered using condition JRN_CONSUMED=1. If you have multiple records for 1 key, then it will pick the latest entry of the that key using JRN_DATE.

select	L.JRN_SUBSCRIBER AS  JRN_SUBSCRIBER,
L.ACCOUNT_ID AS  ACCOUNT_ID,
max(L.JRN_DATE) AS JRN_DATE
from DEV_SCHEMA.J$ACCOUNTS_STAGE L
where L.JRN_CONSUMED = '1'
group by L.JRN_SUBSCRIBER,L.ACCOUNT_ID

Locking of records in J$ table using below SQL update statements. When you start execution of mappings this is the first step.

update	DEV_SCHEMA.J$ACCOUNTS_STAGE
set	JRN_CONSUMED = '1'
where	(1=1)
AND JRN_SUBSCRIBER = 'SUNOPSIS'

JV$D View:

Data view is used to show the change data available for all subscribe in the J$ table without any consume filter, when you select the menu Journal Data from data-store.

I have inserted  new 1 record & 1 updated in my staging table ACCOUNTS_STAGE manually. If you notice the JRN_FLAG is coming as I for update case also, code was present in trigger like that.

updated

journal data jdview

List of changed data if available: It is coming from JV$D view (JV$DACCOUNTS_STAGE)

journal data jdview2

At the end of mapping steps there is one step which cleans journalized table.

delete from J$ACCOUNTS_STAGE
where 	JRN_CONSUMED = '1'
AND JRN_SUBSCRIBER = 'SUNOPSIS' ;

Thanks!

Happy Learning! Your feedback would be appreciated!

Python [Post 01] | Overview & Basics

What is Python? 

python-logo.png

Python is a general purpose object-oriented programming language with high-level programming capabilities. Developed by Guido van Rossum in the late eighties and early nineties at the National Research Institute for Mathematics and Computer Science in the Netherlands.

  • Open Source general-purpose programming language.
  • High-level programming language (i.e. independent of the computer’s hardware).
  • Interpreted (i.e. not need to compile your program before executing it, Python is processed at run-time by the interpreter)
  • Multiple Programming Paradigms ( i.e. Python supports object oriented programming, imperative and functional programming or procedural styles)
  • Code Readability – Python is easy to read, write & maintain.
  • Interactive –   IDLE is Python’s built-in Integrated Development Environment. It has a Python shell window, which gives you access to the Python interactive mode.

Python is fully-functional programming language that can do almost anything.

You can install latest Python from this website – https://www.python.org/

Please see below YouTube video for Python Installation on you Windows Machine in 2 minutes.

After installation you can check the Python Version using Command Prompt.

1.PNG

Hello, World! in Python programming.

print("Hello World!")

2.PNG


Thanks!

Happy Learning! Your feedback would be appreciated!

 

 

How to send email using Python.

How to send email using Python.

Folks,

In this blog we will explore how send email to single/multiple email id using python Script.


Python Script: See detailed comments in the Python Script.


# import the smtplib module.
import smtplib

# from user details
from_user_email_id =  [provide_your_email_id_here]
from_user_email_pwd = [provide_your_email_id_password]

# Email Subject
email_subject = [provide_your_email_subject]

# To user email ids
to_user_email_id = [provide_list_of_to_email_ids_comma_seperated]

# set up the SMTP server
s = smtplib.SMTP(host=[provide_smtp_host_address_here], port=[provide_smtp_port_here]])
s.ehlo()
s.starttls()
s.ehlo

# login the SMTP server using from email id and password.
s.login(from_user_email_id, from_user_email_pwd)

# Preparing email message header and body.
email_header = 'To:' + ", ".join(to_user_email_id)  + '\n' + 'From: ' + from_user_email_id + '\n' + 'Subject: ' +  email_subject + '  \n'
email_body = email_header + [provide_here_email_text]

# sending email
s.sendmail(from_user_email_id, to_user_email_id, email_body)

s.close()

 

After providing all the required information & save your file  in .py extension. Refer below example.

email

Execute Script:

execute

Result:

email4


Thanks!

Happy Learning! Your feedback would be appreciated!