Saturday, 25 April 2020

Sample code for Authorization in Python

Achieving Authorization using JWT in Python


Here we are going to access an get API using python authorization by checking the username, password and generating JWT token.

kindly install below packages to proceed with the code.
install flask_jwt 
install flask_restful 
install flask 

once the above steps has been completed, we will be created three files 
app.py - main application file
security.py - security file
user.py - user

Code: app.py


Code: security.py


Code: user.py



If you need further explanation, kindly mention in the comments so that i can give a brief on code flow.
   



Wednesday, 15 April 2020

Windows BCD error code 0x0000098


Windows BCD error and it works and your files will be safe

File:\BCD
Error code: 0x0000098


Note:
If you are using windows genuine version kindly insert the installation media and follow the below steps:
-Start up your computer with the USB or DVD Windows 10 recovery media.
-Select your language time format and keyboard and click next.
-Click (repair now) then (troubleshoot), windows will automatically try to repair your system.

If you are using non-licensed version:


Start your computer and enter F11 and select the trouble shoot option



select Command prompt and enter the below commands:

C:\diskpart 
and press enter.

DISKPART> list disk 
and press enter to know which drive to target.

DISKPART> sel disk 0 
assuming your drive with windows is disk 0 and press enter.

DISKPART> list vol 
to view all the partitions and press enter.

Select the EFI partition volume which is using FAT32 next to the NTFS volume

DISKPART> sel vol 2
to select the fat32 EFI volume and press enter.

DISKPART> assign letter=m 
to assign an arbitrary drive letter to it and press enter.

DISKPART> Exit 
to exit the diskpart tool and press enter.


> cd /d m:\EFI\Microsoft\Boot\  
press enter

> bootrec /fixboot 
press enter

> ren BCD BCD.old 
and enter to backup the existing Boot Configuration Data
(BCD) store.

> bcdboot c:\Windows /l en-us /s m: /f ALL 
press enter to recreate the BCD store.

Close the command prompt windows then turn off pc and restart the computer.



Sunday, 12 April 2020

parameters are of unsupported type sqlite python

Details:

This is one of the common error a beginner will be facing when he is working on Python and SQLite bridging. Below is a scenario provided for better understanding with example.

Error:

insert_data = "INSERT INTO users VALUES (?, ?, ?)"
    user = [
        {1"Ram""abc@123"},
        {2"Rahim""wel@123"},
        {3"Raju""pass@123"}
    ]
    cursor.executemany(insert_data, user)

When you run the above code you will get the error:
(venv) D:\python\Course_sample\source_database>python dataBase.py
parameters are of unsupported type

This is because when ever we try to insert into database from python, they data has to be a tuple.
In the above code you can see list of set which we try to insert.

Fixed:

#insert data query
    insert_data = "INSERT INTO users VALUES (?, ?, ?)"
    user = [
        (1"Ram""abc@123"),
        (2"Rahim""wel@123"),
        (3"Raju""pass@123")
    ]
    cursor.executemany(insert_data, user)

The above code will get executed and the data will get inserted into the database properly.

Sunday, 5 April 2020

Lambda in python with example

Lambda:

In the below example you can see two methods have been created and clearly explained to show how Lambda works

friends =  [
    {"name""Ram""age":26}, 
    {"name""Raju""age":30}
]

#method with for loop 
def findAge(name):
    for friend in friends:
        if(friend["name"== name):
            return friend
    
    return f"{name} not found"

#method with Lambda expression 
def findAgeLambda(name):
    friend = next(filter(lambda x: x["name"== name, friends))
    return friend

print(findAge("Ram"))
print(findAgeLambda("Raju"))  

Output:

{'name': 'Ram', 'age': 26}
{'name': 'Raju', 'age': 30}

Difference between Set, List and Tuple in python


Set:
  • (regressive)unordered list of data
  • Mutable unordered(regressive) set of values
  • initialized using emptySet = set()
  • Every element is unique
  • A set is created by placing all items inside {}
  • Eg: my_set = {1, 2, 3}
List:
  • Ordered list of data
  • Mutable ordered set of values
  • Initialized using list = []
  • can contain duplicate
  • A list is created by placing all items inside []
  • Eg: my_list = [1,2,3]
Tuple:
  • Ordered list of data
  • Immutable set of values
  • Initialized using tuple = ()
  • can contain duplicate
  • A tuple is created by placing all items inside ()
  • Eg: my_tuple = (1,2,3)



class composition in python with example

Composition is a concept that models a has a relationship. It enables creating complex types by combining objects of other types. This means that a class Composite can contain an object of another class Component. This relationship means that a Composite has a Component.

Example:

class Garage:
    def __init__(self*cars):
        self.cars = cars

    def __str__(self):
        return (f"Total {len(self.cars)} cars in the Garage")

class Cars:
    def __init__(selfnameyear):
        self.name = name
        self.year = year

    def __str__(self):
        return ("{} is moving to Garage in {}".format(self.name, self.year))


car = Cars("Ferrari""2019")
car2 = Cars("Rolls""2020")
car3 = Cars("Benz""2021")
garage = Garage(car, car2, car3)

print(car)
print(car2)
print(car3)
print(garage)

Output:
Ferrari is moving to Garage in 2019
Rolls is moving to Garage in 2020
Benz is moving to Garage in 2021

Total 3 cars in the Garage

Try Except in python with example

Error handling in Python using Try.. Except..

Consider the below example for your reference, you can see the TRY block followed by the EXCEPT and below that there are two additional blocks ELSE and FINALLY.

Try:
The try block will get executed first and will perform the operations given under it. If there is any exception  during the operation then the try block will be stopped else the try block will completed its execution and by pass the EXCEPT block. Compulsory block 

Except:
This block will get executed only if there is any exception in the try block. This Except block will handle the exception and provide a useful message to user regarding the error that has been occurred. Compulsory block 

Else:
This block will be performed if there are no exception and over successful completion of the try block. This is an optional block.

Finally:
This is a final block and this block will definitely get executed even though if there is any exception and optional block in try except.

Example:

students =[
    {"name":"Ram""marks":[50,40,80]},
    {"name":"Raju""marks":[]},
    {"name":"Babu""marks":[90,80,70]}
]

try:
    for student in students:
        name = student["name"]
        marks = student["marks"]
        total = sum(marks)
        average = sum(marks)/len(marks)

        print(f"{name} has scored: Total={total} & Average={average}")
except Exception as e:
    print("There is error in student")
    print(e)
else:
    print("Student list completed")
finally:
    print("done")

Output:
Ram has scored: Total=170 & Average=56.666666666666664
There is error in student
division by zero
done

Dunder or Magic methods in python with example

Magic methods are usually represented by two underscores at front and two at the back of method names. The name Dunder is because of these underscores. Also mainly used for operator overloading.

In the below example you can see two methods "str" and "repr" with two underscore at the front and two at the back. These two methods are used to give user a output if there are no proper return methods in a class. These can also be used to give a message on the function that has been performed in a class.

Example:

class Cars:
    def __init__(selfnamemodel):
        self.name = name
        self.model = model

    def __str__(self):
        return (f"{self.name} is manufactured in the year {self.model}")

    def __repr__(self):
        return (f"<{self.name} is manufactured in the year {self.model}/>")


car = Cars("Ferrari""2019")
print(car)

Output:
Ferrari is manufactured in the year 2019

list indices must be integers or slices, not str error in python

Below is an example to elaborate the error and for an better understanding.

Eg:

shops = [{
    "name""Anand Motors",
    "cars": [
        {
            "name":"Ferrari",
            "Price"25000
        },
        {
            "name""Benz",
            "price"15000
        }
    ]}  
]

The above dictionary is referred as list, when to try to access the dictionary data using string.

name = "Anand Motors"
print(shops[name])

The above code gives error.

Solution or fix:

name = "Anand Motors"
print(next(shop for shop in shops if shop["name"== name))

The above code will fix this error.


Friday, 3 April 2020

Difference between Method and Function in python with example

Function:

A function is a set of code or block of code which process data and return or create a output for the given input.

Eg:
def addValues(xy):
    return x+y

x=int(input("Enter your x value:"))
y=int(input("Enter your y value:"))
print(addValues(x, y))

When you consider the above python code, addValues() is a function.

Method:

A method is similar to function where has a set of code or a block of code, which is represented by a name. When the name is called the entire block of code will be executed. 

Eg:
class mathis:
    def addValues(xy):
        return x+y

x=int(input("Enter your x value:"))
y=int(input("Enter your y value:"))
print(mathis.addValues(x, y))

In the above python code, the same addValues() is defined into a class which is referred as a method.

Here the difference between method and function is:

  • If a function is defined inside a class then it is called as method.
(note: Method and function has similar properties where both is used to perform an operation with block of code.)

Expense Handler Application with advance technologies

Budget Planner  One of the application developed with Ionic 4 and Python-Flask.  Ionic 4 code:  https://github.com/logeshbuiltin/Expense...