Thursday, March 15, 2018

Python project - Contactbook

Contact Book: Sample application to perform CRUD operations using Python, MySQL.

             MySQL
             Python 3.x

Libraries used :
           pymsql , beatutifultable

Installation of Libraries using pip
           pip install pymsql
           pip install beautifultable

This application performs basic CRUD orations to demonstrate Python end-to-end application.

Note: Update and delete methods were not called from main, you can give a try...

contact.py


from collections import namedtuple

Contact = namedtuple("Contact", ["cid","name", "email", "mobile"])

config.py


mysql = {
    'host': 'localhost',
    'user': 'root',
    'passwd': 'password',
    'db': 'counselor_db'}

util.py

import pymysql
import config

class DbUtil:

    @staticmethod
    def get_connection():
        try:
            con = pymysql.connect(config.mysql['host'], config.mysql['user'],config.mysql['passwd'],config.mysql['db'])
        except pymysql.MySQLError as error:
            print('Exception number: {}, value {s}'.format(error.args[0], error))
            raise
        else:
            return con

    @staticmethod
    def close_connection(conn):
        try:
            conn.close()
        except pymysql.MySQLError as error:
            print("While closing connection ...")
            print('Exception number: {}, value {!r}'.format(error.args[0], error))
            raise

    @staticmethod
    def close_cursor(cursor):
        try:
            cursor.close()
        except pymysql.MySQLError as error:
            print("While closing the cursor ...")
            print('Exception number: {}, value {!r}'.format(error.args[0], error))
            raise

dboperations.py

import config
from util import DbUtil
import pymysql
from contact import Contact


class ContactDbOperations:

    def add_contact(self, new_contact):
        try:
            connection = DbUtil.get_connection()
            with connection.cursor() as cursor:
                cursor.execute("insert into contact(name,email,mobile) values(%s,%s,%s)", (new_contact.name
                                                                        , new_contact.email
                                                                                            , new_contact.mobile))
            connection.commit()

        except pymysql.MySQLError as error:
            print("While inserting Data ...")
            print('Exception number: {}, value {!r}'.format(error.args[0], error))
        finally:
            DbUtil.close_connection(connection)
            DbUtil.close_cursor(cursor)

    def get_contact(self, cid):
        try:

            conn = DbUtil.get_connection()
            cursor = conn.cursor()
            cursor.execute("select  cid, name, email, mobile from contact where cid = %s", cid)
            contact = Contact(*cursor.fetchone())
            return  contact
        except pymysql.DatabaseError as error:
            print("While getting data from DB using id... ")
            print('Exception number: {}, value {!r}'.format(error.args[0], error))
        finally:
            DbUtil.close_connection(conn)
            DbUtil.close_cursor(cursor)

    def update_contact(self, contact):
        try:
            conn = DbUtil.get_connection()
            cursor = conn.cursor()
            cursor.execute("update contact set name = %s ,email = %s, mobile = %s where cid = %s", contact)
            conn.commit()

        except pymysql.DatabaseError as error:
            print("While updating ... ")
            print('Exception number: {}, value {!r}'.format(error.args[0], error))
        finally:
            DbUtil.close_connection(conn)
            DbUtil.close_cursor(cursor)

    def get_all_contacts(self):
        try:
            connection = DbUtil.get_connection()
            with connection.cursor() as cursor:
                cursor.execute("select cid, name, email, mobile from contact")
                rows = cursor.fetchall()
                contacts = self.get_list_data(rows)
                return contacts
        except Exception as error:
            print("While retrieving data ... ")
            print('Exception number: {}, value {!r}'.format(error.args[0], error))
        finally:
            if connection:
                DbUtil.close_connection(connection)
                DbUtil.close_cursor(cursor)

    def search_contact(self, search_str):
        try:
            connection = DbUtil.get_connection()
            with connection.cursor() as cursor:
                cursor.execute("select cid, name, email, mobile from contact where name like %s ", ('%' + search_str + '%'))
                rows = cursor.fetchall()
                contacts = self.get_list_data(rows)
                return contacts
        except Exception as error:
            print("While searching Data ...")
            print('Exception number: {}, value {!r}'.format(error.args[0], error))
        finally:
            DbUtil.close_connection(connection)
            DbUtil.close_cursor(cursor)

    @staticmethod
    def delete_contact(cid):
        try:
            connection = DbUtil.get_connection()
            cursor = connection.cursor()
            cursor.execute("delete from contact where cid = %s ", cid)
            connection.commit()

        except pymysql.DatabaseError as error:
            print("While deleting data ...")
            print('Exception number: {}, value {!r}'.format(error.args[0], error))
        finally:
            DbUtil.close_connection(connection)
            DbUtil.close_cursor(cursor)

    @staticmethod
    def get_list_data(rows):
        return [Contact(*row) for row in rows]

contactservice.py

from dboperations import ContactDbOperations
from contact import Contact
from beautifultable import BeautifulTable

class ContactService:

    def __init__(self):
        self.cs = ContactDbOperations()

    def add_contact(self):
        name = input("Name : ")
        email = input("Email : ")
        mobile = input("Mobile : ")
        contact = Contact(0, name, email, mobile)
        self.cs.add_contact(contact)
        self.show_all_contacts()

    def show_all_contacts(self):
        contacts = self.cs.get_all_contacts()
        ContactService.paint_data_list(contacts)

    def search_contact(self):
        name = input("Enter search name :")
        contacts = self.cs.search_contact(name)
        if contacts:
            ContactService.paint_data_list(contacts)
        else:
            print("No data found with search name :{}".format(name))

    @staticmethod
    def paint_data(data):
        table = BeautifulTable()
        table.column_headers = ["CID", "NAME", "EMAIL", "MOBILE"]
        table.append_row([data.cid, data.name, data.email, data.mobile])
        print(table)

    @staticmethod
    def paint_data_list(data):
        table = BeautifulTable()
        table.column_headers = ["CID", "NAME", "EMAIL", "MOBILE"]
        for li in data:
            table.append_row([li.cid, li.name, li.email, li.mobile])
        print(table)


main.py


if __name__ == '__main__':
    cs = ContactService()
    while True:
        print("*"*40)
        print("1. Add Contact 2. View All 3.Search 4. Exit")
        print("*"*40)
        choice = int(input("Enter your choice :"))
        if choice == 1:
            cs.add_contact()
        elif choice == 2:
            cs.show_all_contacts()
        elif choice == 3:
            cs.search_contact()
        elif choice == 4:
            exit()
        else:
            print("Enter only 1 to 4 ......")

Saturday, March 10, 2018

MongoDB CRUD operations exercise


Installation of MongoDB

The executable file needs to be downloaded from:

https://www.mongodb.com/download-center?jmp=nav#community

Note: During installation of MongoDB, one of the wizards has a compass installation check box, please uncheck the same, and continue the installation process by clicking on “Next”.

·         Once installation is completed, create the directory “data/db” in the "C" drive.

·         Copy the MongoDB installation directory path (which looks like C:\Program Files\MongoDB\Server\3.6\bin) and add it to the environment variable of the system. 
  •      To Run mongo client open command prompt and type mongo 


·         To verify the installation:
                 - Open the command prompt
                            Type the command mongod. If a message "Waiting for connections on port 27017" is                  displayed on the last line, it indicates the successful installation of MongoDB.

Installation of RoboMongo

·         Download the executable from the following link:
        https://robomongo.org/download    
·         Just follow the instructions of the installation wizard to complete installation of RoboMongo.

Working with MongoDB
The example given below covers all the basic (CRUD) operations in MongoDB.
  1. Connect to MongoDB (by using mongo shell)
  2. Create database with name (ems)   - use ems;
  3.  Insert the following data into "faculty" collection (Use insertMany())
db.faculty.insrtMany([
            { "name":"Krish", "age":35,"gender":"M","exp":10,subjects:["DS","C","OS"],"type":"Full Time","qualification":"M.Tech" },
            { "name":"Manoj", "age":38,"gender":"M","exp":12,subjects:["JAVA","DBMS"],"type":"Full Time", "qualification":"Ph.D"},
            { "name":"Anush", "age":32,"gender":"F","exp":8,subjects:["C","CPP"],"type":"Part Time","qualification":"M.Tech" },
            { "name":"Suresh", "age":40,"gender":"M","exp":9,subjects:["JAVA","DBMS","NETWORKING"],"type":"Full Time", "qualification":"Ph.D"},
            { "name":"Rajesh", "age":35,"gender":"M","exp":7,subjects:["DS","C","OS"],"type":"Full Time","qualification":"M.Tech" },
            { "name":"Mani", "age":38,"gender":"F","exp":10,subjects:["JAVA","DBMS","OS"],"type":"Part Time", "qualification":"Ph.D"},
            { "name":"Sivani", "age":32,"gender":"F","exp":8,subjects:["C","CPP","MATHS"],"type":"Part Time","qualification":"M.Tech" },
            { "name":"Nagesh", "age":39,"gender":"M","exp":11,subjects:["JAVA","DBMS","NETWORKING"],"type":"Full Time", "qualification":"Ph.D"},
            { "name":"Nagesh", "age":35,"gender":"M","exp":9,subjects:["JAVA",".Net","NETWORKING"],"type":"Full Time", "qualification":"Ph.D"},
            { "name":"Latha", "age":40,"gender":"F","exp":13,subjects:["MATHS"],"type":"Full Time", "qualification":"Ph.D"}
]);
Write the following queries:
1. Get the details of all the faculty.
2. Get the count of all faculty members. 
3. Get all the faculty members whose qualification is “Ph.D”.
4. Get all the faculty members whose experience is between 8 to 12 years.
5. Get all the faculty members who teach “MATHS” or “NETWORKING”.
6. Get all the faculty members who teach “MATHS” and whose age is more than 30 years and qualification must be “Ph.D”.
7. Get all the faculty members who are working part-time or who teach “JAVA”.
8. Add the following new faculty members:
      { "name":"Suresh Babu", "age":55,"gender":"M","exp":25,subjects:["MATHS","DE"],"type":"Full Time", "qualification":"Ph.D"}

db.faculty.insert(
      { "name":"Suresh Babu", "age":55,"gender":"M","exp":25,subjects:["MATHS","DE"],"type":"Full Time", "qualification":"Ph.D"}
       );
9. Update the data of all faculty members by incrementing their age and exp by one year.
10. Update the faculty “Sivani” with the following data: update qualification to “Ph.D” and type to “Full Time”.
11. Update all faculty members who are teaching “MATHS” such that they should now also teach “PSK”.
12. Delete all faculty members whose age is more than 55 years.
13. Get only the name and qualification of all faculty members. 
14. Get the name, qualification and exp of all faculty members and display the same in ascending order of exp.
15. Sort the faculty details by their age (descending order) and get the details of the first five faculty members only. 

Solutions: 
1. db.faculty.find().pretty()
2. db.faculty.count()
3. db.faculty.find({qualification:'Ph.D'}).pretty()
4. db.faculty.find({$and:[{exp:{$gt:7}},{exp:{$lt:13}}]}).pretty()
5. db.faculty.find({subjects:{$in:["MATHS","NETWORKING"]}}).pretty()
6. db.faculty.find({$and:[{subjects:'MATHS'},{age:{$gt:29}},{qualification:'Ph.D'}]}).pretty()
7. db.faculty.find({$or:[{type:"Part Time"},{subjects:"JAVA"}]}).pretty()
8. db.faculty.insert( {"name" : "Suresh Babu", age":55, "gender":"M", "exp":25, subjects:["MATHS","DE"],"type":"Full Time", "qualification":"Ph.D"})
9. db.faculty.updateMany({},{$inc:{age:1,exp:1}})
10. db.faculty.updateMany({name:"Sivani"},{$set:{qualification:"Ph.D",type:"Full Time"}})
11. db.faculty.updateMany({subjects:"MATHS"},{$push:{subjects:"PSK"}})
12. db.faculty.deleteMany({age:{$gt:54}})
13. db.faculty.find({},{name:1,_id:0,qualification:1});
14. db.faculty.find({},{name:1,_id:0,qualification:1,exp:1}).sort({exp:-1}).pretty()
15. db.faculty.find({}).sort({age:-1}).limit(5).pretty()






Monday, March 5, 2018

Python copy content of file to another file

Python:

Copy the content of inputfile.txt to outputfile.txt:

with open("outputfile.txt","w") as fw,open("inputfile.txt") as f:
    for line in f:
        fw.write(line)

Spring Boot 3 : JWT with SecurityFilterChain, AuthorizeHttpRequests, RequestMatchers

pom.xml <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0"...