Posted by: Zeeshan Amjad | October 31, 2023

Values passing in HTTP call


In HTTP request, parameter can be passed in more than one way. For GET request, we can pass value by either query parameter, path parameter or header. For POST or PUT we can even pass it in the body. Let’s focus on the GET request and see how can we pass values in different ways.

We already saw the example of query passing here https://zamjad.wordpress.com/2023/09/01/writing-webservice-with-python/

Here we are going to write a simple program using Flask to show how to retrieve values passing using query, path and header.

from flask import Flask, request, jsonify
app = Flask(__name__)
 
@app.route("/")
def hello() -> str:
    return jsonify("Hello World from Python")

@app.route("/query")
def queryParam() -> str:
    value1 = request.args.get("key1")
    value2 = request.args.get("key2")
    return jsonify({
        "key1": value1,
        "key2": value2
    })
 
@app.route("/path/<parammeter>")
def pathParam(parammeter) -> str:
    value = request.view_args["parammeter"]
    return jsonify({"parameter": value})

@app.route("/header")
def headerParam() -> str:
    value = None
    if "parameter" in request.headers:
        value = request.headers["parameter"]
    return jsonify({"parameter": value})

if __name__ == "__main__":
    app.run()
    

The first one is very simple, we pass the values in the form of key value pair in the URL, here is one such example.

localhost:5000/query?key1=hello&key2=world

Its output would be something like this.

{

     "key1": "hello",

    "key2": "world"

}

To pass the value in the form of path we would call it something like this

localhost:5000/path/pathvalue

Here is the output of this

{

    "parameter": "pathvalue"

}

The third way is to pass value via header. The simplest way to pass this using Postman or similar tool. We can set the key value in the header and pass it. Here is the output of the program when set key is “parameter” and “value” as a value.

{

"parameter": "value"

}

If we call it from browser, then its value would be null.

Posted by: Zeeshan Amjad | October 12, 2023

Multiple Inheritance and Method Resolution Order in Python


Python is one of the few language who support multiple inheritance. Here is a simplest program to demonstrate multiple inheritance in Python.

class Parent1:
    pass

class Parent2:
    pass

class Child(Parent1, Parent2):
    pass

if __name__ == "__main__":
    child = Child()

But what would be the method resolution order if same method is inherited in the class more than one way. The simple way to demonstrate this is to create a based class, inherit two class from it and inherit new class inherited from both, also known as diamond problem. It can be demonstrated by this diagram.

Diamond Problem

Here is a simplest implementation of this.

class GrandParent:
    pass

class Parent1(GrandParent):
    pass

class Parent2(GrandParent):
    pass

class GrandChild(Parent1, Parent2):
    pass

Now if we have a method in GrandParent, it comes twice in the GrandChild class via both parent classes. Let’s create a simple program.

class GrandParent:
    def method(self):
        print("GrandParent.method")

class Parent1(GrandParent):
    def method(self):
        super().method()
        print("Parent1.method")

class Parent2(GrandParent):
    def method(self):
        super().method()
        print("Parent2.method")

class GrandChild(Parent1, Parent2):
    def method(self):
        super().method()
        print("GrandChild.method")

if __name__ == "__main__":
    gc = GrandChild()
    gc.method()

Here is the output of the program

GrandParent.method

Parent2.method

Parent1.method

GrandChild.method

The way Python looks for methods or attributes in the class hierarchy is called Method Resolution Order or simply MRO. Python internally uses C3 Linearization Algorithm to computer MRO in case of multiple inheritance. C3 Linearization algorithms remove any duplicate and uses left to right traversal. Here super().method() inside the GrandChild class first call the Parent1 method then Parent 2. If we changed the order of classes while doing the inheritance then it changes accordingly.

Python also define special method mro to display the current Method Resolution Order. It can be called at class level in two ways. Here is a simple code to demonstrate the MRO

class GrandParent:
    def method(self):
        print("GrandParent.method")

class Parent1(GrandParent):
    def method(self):
        super().method()
        print("Parent1.method")

class Parent2(GrandParent):
    def method(self):
        super().method()
        print("Parent2.method")

class GrandChild(Parent1, Parent2):
    def method(self):
        super().method()
        print("GrandChild.method")

if __name__ == "__main__":
    gc = GrandChild()
    print(GrandChild.mro())
    print(GrandChild.__mro__)

Here is the output of this program that shows MRO.

[<class ‘__main__.GrandChild’>, <class ‘__main__.Parent1’>, <class ‘__main__.Parent2’>, <class ‘__main__.GrandParent’>, <class ‘object’>]

(<class ‘__main__.GrandChild’>, <class ‘__main__.Parent1’>, <class ‘__main__.Parent2’>, <class ‘__main__.GrandParent’>, <class ‘object’>) 

Posted by: Zeeshan Amjad | September 24, 2023

Dice simulation using useReducer hook


We already crated dice simulation program in two different ways, one using flux pattern and another one using redux library. Although redux is very popular and powerful library with lots of support for tools and testing, but it is bit complex and its learning curve is bit steep. It is very useful when we are trying to create a global state management by creating one application level store and complex state management.

However, for local component level state management, we can do this with one of react hook useReducer without using redux library. It is suitable for simple, component level state management, without any external dependency.

Let’s try to create a same program this time using useReduce hook. For this, we don’t need to create store, so there is no need to use Provider in the application class, and it is similar to any react component. Here is a simple code of our Application class.

import './App.css';
import Dice from './Dice';

function App() {
  return (
    <div className="App">
      <Dice />
    </div>
  ) 
}

export default App;

We are trying to make our implementation as similar to as our other two implementations. The important thing here is the use of useReducer hook which returns the state and dispatch method. In this version of the application, there is no need to create a store and get the state information from the store and there is no need to create a dispatcher method ourself. Here is a complete code of our Dice component this time using hook.


import { useReducer } from 'react';

// define action types
const INCREMENT_DICE = 'INCREMENT_DICE';
const DECREMENT_DICE = 'DECREMENT_DICE';
const RESET_DICE = 'RESET_DICE';
const ROLL_DICE = 'ROLL_DICE';

// Create actions
const incrementDice = () => {
    return { type: INCREMENT_DICE };
}

const decrementDice = () => {
    return { type: DECREMENT_DICE };
}

const resetDice = () => {
    return { type: RESET_DICE };
}

const rollDice = () => {
    return { type: ROLL_DICE };
}

const initialState = {
    diceCount: 1,
    sum: 0,
};

const randomNumber = (min, max) => {
    return Math.floor(Math.random() * (max - min + 1) + min)
}

const reducer = (state = initialState, action) => {
    switch (action.type) {
        case INCREMENT_DICE:
            return {
                diceCount: state.diceCount + 1,
                sum: 0,
            };
        case DECREMENT_DICE:
            return {
                diceCount: state.diceCount - 1,
                sum: 0,
            };
        case RESET_DICE:
            return {
                diceCount: 1,
                sum: 0,
            }
        case ROLL_DICE:
            var sum = 0;
            for (var i = 0; i < state.diceCount; i++)
                sum += randomNumber(1, 6);
            return {
                diceCount: state.diceCount,
                sum: sum,
            }
        default:
            return state;
    }
};

const Dice = () => {

    const [state, dispatch] = useReducer(reducer, initialState);

    return (
        <div>
            <h2>Dice Simulation Using useReducer hook</h2>
            <p>Number of dices {state.diceCount}</p>
            <p>Sum of rolling Dice {state.sum}</p>
            <p><button onClick={() => dispatch(incrementDice())}>Increment</button>
                <button onClick={() => dispatch(decrementDice())}>Decrement</button>
                <button onClick={() => dispatch(resetDice())}>Reset</button></p>
            <p><button onClick={() => dispatch(rollDice())}>Roll Dice</button></p>
        </div>
    )
}

export default Dice;

Here is the output of the program

Dice Simulation Hook

Posted by: Zeeshan Amjad | September 22, 2023

Dice simulation using Redux


We created a dice simulation program using flux design pattern here https://zamjad.wordpress.com/2023/09/10/flux-design-pattern-using-typescript-in-react/

Now let’s try to create a same program, but this time using one of the very popular state management library Redux.

Let’s first install the redux using the following npm command on the terminal

npm install redux react-redux

The main concept is similar to what we did using the flux design pattern. For simplicity, I am going to write almost all the code in one file using JavaScript, instead of TypeScript. It is not a good practice to put everything in one file.

Let’s start with creating actions. We defined 4 action in our dice simulation application.

// define action types
const INCREMENT_DICE = 'INCREMENT_DICE';
const DECREMENT_DICE = 'DECREMENT_DICE';
const RESET_DICE = 'RESET_DICE';
const ROLL_DICE = 'ROLL_DICE';

// Create actions
const incrementDice = () => {
  return { type: INCREMENT_DICE };
}

const decrementDice = () => {
  return { type: DECREMENT_DICE };
}

const resetDice = () => {
  return { type: RESET_DICE };
}

const rollDice = () => {
  return { type: ROLL_DICE };
}

We are using two variable for our state, the number of dice and sum when we roll dice. Here is our initial state.

const initialState = {
  diceCount: 1,
  sum: 0,
};

Now we need to create a store. There should be only one redux store per application. It is a single source of truth for our application. We also need to define the function that describe what should we do with each actions. Here is a code to create function to do specific things based on action and create store.

const counterReducer = (state = initialState, action) => {
  switch (action.type) {
    case INCREMENT_DICE:
      return {
        diceCount: state.diceCount + 1,
        sum: 0,
      };
    case DECREMENT_DICE:
      return {
        diceCount: state.diceCount - 1,
        sum: 0,
      };
    case RESET_DICE:
      return {
        diceCount: 1,
        sum: 0,
      }
    case ROLL_DICE:
      var sum = 0;
      for (var i = 0; i < state.diceCount; i++)
        sum += randomNumber(1, 6);
      return {
        diceCount: state.diceCount,
        sum: sum,
      }
    default:
      return state;
  }
};

export const store = createStore(counterReducer);

Here randomNumber is our own utility function to give us random number from minimum number using Math.random() method.

When we were not using redux in our previous version, we had to write dispatch function ourselves. Here redux is taking care of this for us. Here is JSX code to dispatch the action on each button.

<p><button onClick={() => dispatch(incrementDice())}>Increment</button>
<button onClick={() => dispatch(decrementDice())}>Decrement</button>
<button onClick={() => dispatch(resetDice())}>Reset</button></p>
<p><button onClick={() => dispatch(rollDice())}>Roll Dice</button></p>

We need to make one change in the App class. To use redux, we need to call our Dice component inside the Provider and specify what is our store. Here is complete code of our App file.

import React from 'react';
import './App.css';
import { Provider } from 'react-redux';
import Dice, {store} from './Dice';


function App() {
  return (
    <Provider store={store}>
      <div className="App">
        <Dice />
      </div>
    </Provider>
  );
}

export default App;

And here is our complete code of Dice.js file

import { useSelector, useDispatch } from 'react-redux';
import { createStore } from 'redux';

// define action types
const INCREMENT_DICE = 'INCREMENT_DICE';
const DECREMENT_DICE = 'DECREMENT_DICE';
const RESET_DICE = 'RESET_DICE';
const ROLL_DICE = 'ROLL_DICE';

// Create actions
const incrementDice = () => {
  return { type: INCREMENT_DICE };
}

const decrementDice = () => {
  return { type: DECREMENT_DICE };
}

const resetDice = () => {
  return { type: RESET_DICE };
}

const rollDice = () => {
  return { type: ROLL_DICE };
}

const initialState = {
  diceCount: 1,
  sum: 0,
};

const randomNumber = (min, max) => {
  return Math.floor(Math.random() * (max - min + 1) + min)
}

const counterReducer = (state = initialState, action) => {
  switch (action.type) {
    case INCREMENT_DICE:
      return {
        diceCount: state.diceCount + 1,
        sum: 0,
      };
    case DECREMENT_DICE:
      return {
        diceCount: state.diceCount - 1,
        sum: 0,
      };
    case RESET_DICE:
      return {
        diceCount: 1,
        sum: 0,
      }
    case ROLL_DICE:
      var sum = 0;
      for (var i = 0; i < state.diceCount; i++)
        sum += randomNumber(1, 6);
      return {
        diceCount: state.diceCount,
        sum: sum,
      }
    default:
      return state;
  }
};

export const store = createStore(counterReducer);

function Dice() {
  const noOfDice = useSelector(state => state.diceCount);
  const sum = useSelector(state => state.sum);
  const dispatch = useDispatch();

  return (
    <div>
      <h2>Dice Simulation Using Redux</h2>
      <p>Number of dices {noOfDice}</p>
      <p>Sum of rolling Dice {sum}</p>
      <p><button onClick={() => dispatch(incrementDice())}>Increment</button>
        <button onClick={() => dispatch(decrementDice())}>Decrement</button>
        <button onClick={() => dispatch(resetDice())}>Reset</button></p>
      <p><button onClick={() => dispatch(rollDice())}>Roll Dice</button></p>
    </div>
  )
}

export default Dice;

Here is an output of the program

Dice Simulation Redux

import { useSelector, useDispatch } from 'react-redux';
import { createStore } from 'redux';

// define action types
const INCREMENT_DICE = 'INCREMENT_DICE';
const DECREMENT_DICE = 'DECREMENT_DICE';
const RESET_DICE = 'RESET_DICE';
const ROLL_DICE = 'ROLL_DICE';

// Create actions
const incrementDice = () => {
  return { type: INCREMENT_DICE };
}

const decrementDice = () => {
  return { type: DECREMENT_DICE };
}

const resetDice = () => {
  return { type: RESET_DICE };
}

const rollDice = () => {
  return { type: ROLL_DICE };
}

const initialState = {
  diceCount: 1,
  sum: 0,
};

const randomNumber = (min, max) => {
  return Math.floor(Math.random() * (max - min + 1) + min)
}

const counterReducer = (state = initialState, action) => {
  switch (action.type) {
    case INCREMENT_DICE:
      return {
        diceCount: state.diceCount + 1,
        sum: 0,
      };
    case DECREMENT_DICE:
      return {
        diceCount: state.diceCount - 1,
        sum: 0,
      };
    case RESET_DICE:
      return {
        diceCount: 1,
        sum: 0,
      }
    case ROLL_DICE:
      var sum = 0;
      for (var i = 0; i < state.diceCount; i++)
        sum += randomNumber(1, 6);
      return {
        diceCount: state.diceCount,
        sum: sum,
      }
    default:
      return state;
  }
};

export const store = createStore(counterReducer);

function Dice() {
  const noOfDice = useSelector(state => state.diceCount);
  const sum = useSelector(state => state.sum);
  const dispatch = useDispatch();

  return (
    <div>
      <h2>Dice Simulation Using Redux</h2>
      <p>Number of dices {noOfDice}</p>
      <p>Sum of rolling Dice {sum}</p>
      <p><button onClick={() => dispatch(incrementDice())}>Increment</button>
        <button onClick={() => dispatch(decrementDice())}>Decrement</button>
        <button onClick={() => dispatch(resetDice())}>Reset</button></p>
      <p><button onClick={() => dispatch(rollDice())}>Roll Dice</button></p>
    </div>
  )
}

export default Dice;
Posted by: Zeeshan Amjad | September 15, 2023

Client side routing in React application


Client side routing is very important concept to create a smooth user experience in single page application (SPA). It also helps us to manage code easily.

Although it is the most common react library for client side routing, but it is not the only one. The other libraries for client side routing are wouter, Hookrouter and Turbolinks among few others.

First create a react-route-dom library using this command

npm i react-route-dom

Let’s create a which has Home page, Contact, Resource and About. Here is a simple code Home, Contact and About page in respective files. For simplicity, the code is very simple, just demonstrate the loading of appropriate component.

Here is a code in home.js file


const Home = () => {
    return(
        <div>Home</div>
    )
}

export default Home;

Here is a code for About component in about.js file


const About = () => {
    return(
        <div>About</div>
    )
}

export default About;

And Contact component is very similar to others, here is its code in contact.js file


const Contact = () => {
    return(
        <div>Contact</div>
    )
}

export default Contact;

Now let’s create another component for Page Not found. We will sue this when user gave the invalid path. Here is a code for this very similar to other components.


const NotFound = () => {
    return(
        <div>Paage Not Found</div>
    )
}

export default NotFound;

Now let’s include the BrowserRouter component in the index.js file and load the App component inside the BrowserRouter. Here is a complete code of index.js file.

import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import { BrowserRouter } from 'react-router-dom'

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <BrowserRouter>
    <App />
  </BrowserRouter>
);

// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();

Now let’s pass a parameter when routing to one component. Let’s create a resource component, which accept category as a component and display that category in the component. Here is a code for Resource component with category as a parameter.

import { useParams } from "react-router-dom"

const Resource = () => {

    const { category } = useParams();

    return(
        <div>Resource: Category = {category}</div>
    )
}

export default Resource;

Value of parameter can be get by useParams().

Now let’s call all of these components from App component. First import all the component in App.js file then define all the Route inside the Routes component. Here is a complete code for it.

import {Routes, Route} from 'react-router-dom'
import Home from './Home';
import Contact from './Contact';
import Resource from './Resource';
import About from './About';
import NotFound from './NotFound';

const App = () => {
    return(
        <Routes>
            <Route path='/' element={<Home />} />
            <Route path='/contact' element={<Contact />} />
            <Route path='/about' element={<About />} />
            <Route path='/resource/:category' element={<Resource />} />
            <Route path='*' element={<NotFound />} />
        </Routes>
    )
}

export default App;

The two important concepts here are parameter is passed using : and parameter name and use * for all the path not defined.

Now when we run the application with localhost:3000/ it displays the home page, localhost:3000/contact displays the contact page localhost:3000/about displays the about page localhost:3000/resource/blogs display resource page with blogs as a category any other path define the Page not found component.

Posted by: Zeeshan Amjad | September 10, 2023

Flux Design Pattern using TypeScript in React


Flux is an interesting unidirectional architectural design pattern introduced by Facebook for React. React has unidirectional binding, unlike Angular which has bidirectional binding. It is the same pattern used by in Redux, which is very popular JavaScript library for statement management. It is important to know that Redux is not the only state management library, other possible choices are MobX, XState, Recoil and Valtio are other choices. 

They key concepts of Flux pattern are Action, Store, Dispatcher and View. Here is a simplest presentation of data flow among all these components.

Flux Pattern

Here we are trying to use the simplest implementation of Flux pattern in TypeScript without using Redux or any other state management libraries.

Here I am going to create a simple program to simulate the rolling dice. We can select the number of dice and then roll the dice. We can even reset the number of dice to 1. Here are four actions we defined.

// action types
enum ActionTypes {
    INCREMENT_DICE = 'INCREMENT_DICE',
    DECREMENT_DICE = 'DECREMENT_DICE',
    RESET_DICE = 'RESET_DICE',
    ROLL_DICE = 'ROLL_DICE'
}

// action interface
interface Action {
    type: ActionTypes;
}

Here is a simplest implementation of Dispatcher. It is very much boilerplate code.

// a simple dispatcher
function createDispatcher<T extends Action>() {

    const listeners: ((action: T) => void)[] = [];

    function register(listener: (action: T) => void) {
        
        listeners.push(listener);

        // unregister the listener
        return function unregister() {
        
            const index = listeners.indexOf(listener);
            if (index !== -1) {
                listeners.splice(index, 1);
            }
        };
    }

    function dispatch(action: T) {
        for (const listener of listeners) {
            listener(action);
        }
    }

    return {
        register,
        dispatch,
    };
}

In our case the store maintains two information, the number of dice and the sum of rolling dice. We have two state variable for this. In our Dice function component, we use useEffect hook to register the dispatcher.

For simplicity, I put all code in one file, although it is not a good programming practice. Here is a complete code of our Dice simulation.

import { useState, useEffect } from "react";

// action types
enum ActionTypes {
    INCREMENT_DICE = 'INCREMENT_DICE',
    DECREMENT_DICE = 'DECREMENT_DICE',
    RESET_DICE = 'RESET_DICE',
    ROLL_DICE = 'ROLL_DICE'
}

// action interface
interface Action {
    type: ActionTypes;
}

// a simple dispatcher
function createDispatcher<T extends Action>() {

    const listeners: ((action: T) => void)[] = [];

    function register(listener: (action: T) => void) {
        
        listeners.push(listener);

        // unregister the listener
        return function unregister() {
        
            const index = listeners.indexOf(listener);
            if (index !== -1) {
                listeners.splice(index, 1);
            }
        };
    }

    function dispatch(action: T) {
        for (const listener of listeners) {
            listener(action);
        }
    }

    return {
        register,
        dispatch,
    };
}

// Create a dispatcher instance for the Action type
const dispatcher = createDispatcher<Action>();

// Create action creators
function incrementDice() {
    dispatcher.dispatch({ type: ActionTypes.INCREMENT_DICE });
}

function decrementDice() {
    dispatcher.dispatch({ type: ActionTypes.DECREMENT_DICE });
}

function resetDice() {
    dispatcher.dispatch({ type: ActionTypes.RESET_DICE });
}

function rollDice() {
    dispatcher.dispatch( { type: ActionTypes.ROLL_DICE });
}

// Create a store to manage state
class Store {
    private state = { diceCount: 1, sum: 0 };
  
    constructor() {
        dispatcher.register(this.handleActions.bind(this));
    }

    private randomNumber(min: number, max: number) : number {
        return Math.floor(Math.random() * (max - min + 1) + min)
    }

    private handleActions(action: Action) {
        switch (action.type) {
            case ActionTypes.INCREMENT_DICE:
                this.state.diceCount++;
                break;

            case ActionTypes.DECREMENT_DICE:
            if (this.state.diceCount > 1)
                this.state.diceCount--;
            break;

            case ActionTypes.RESET_DICE:
                this.state.diceCount = 1;
                break;

            case ActionTypes.ROLL_DICE:
                this.state.sum = 0;
                for (var i = 0; i < this.state.diceCount; i++) 
                    this.state.sum += this.randomNumber(1, 6);
                break;

        }
    }

    getDiceCount() : number {
        return this.state.diceCount;
    }
    
    getSum() : number {
        return this.state.sum
    }
}

const store = new Store();

function Dice() {

    const [noOfDice, setNoOfDice] = useState<number>(store.getDiceCount());
    const [sum, setSum] = useState<number>(store.getSum());

    useEffect(() => {
        const storeSubscription = dispatcher.register(() => {
            setNoOfDice(store.getDiceCount());
            setSum(store.getSum())
        });
    
        return () => {
            storeSubscription();
        };
      }, []);

    return (
        <div>
            <h2>Dice Simulation</h2>
            <p>Number of dices {noOfDice}</p>
            <p>Sum of rolling Dice {sum}</p>
            <p><button onClick={incrementDice}>Increment</button>
            <button onClick={decrementDice}>Decrement</button>
            <button onClick={resetDice}>Reset</button></p>
            <p><button onClick={rollDice}>Roll Dice</button></p>
        </div>
    );
}

export default Dice;

Here is the output of this program.

Dice Simulation

Posted by: Zeeshan Amjad | September 8, 2023

Special Method and Singleton Class in Python


Every Python class has some special method start with __ and end with __. Let’s start with a empty class and see what is special methods are defined in it.

class EmptyClass:
    pass

if __name__ == "__main__":
    print(dir(EmptyClass))

Here is the output of it.

[‘__class__’, ‘__delattr__’, ‘__dict__’, ‘__dir__’, ‘__doc__’, ‘__eq__’, ‘__format__’, ‘__ge__’, ‘__getattribute__’, ‘__getstate__’, ‘__gt__’, ‘__hash__’, ‘__init__’, ‘__init_subclass__’, ‘__le__’, ‘__lt__’, ‘__module__’, ‘__ne__’, ‘__new__’, ‘__reduce__’, ‘__reduce_ex__’, ‘__repr__’, ‘__setattr__’, ‘__sizeof__’, ‘__str__’, ‘__subclasshook__’, ‘__weakref__’]

Python has two different methods for creation a class and initialization of a class. Python first call the __new__ then __init__ method. Let’s override both method to see this behavior. Here is a simple program to demonstrate this.

class MyClass:
    def __new__(self):
        print("New")
        return super(MyClass, self).__new__(self) 
    
    def __init__(self):
        print("Init")

if __name__ == "__main__":
    mc = MyClass();

It prints “New” then “Init”. Let’s use the overridden __new__ method to create a singleton class.  Here is a simple way to create a singleton method.

class Singleton:

    _instance = None

    def __new__(self):
        if self._instance is None:
            self._instance = super(Singleton, self).__new__(self)
        return self._instance

Posted by: Zeeshan Amjad | September 6, 2023

Decorator method in python


After discussing the higher level object in react, I decided to explore decorator method in Python. We just saw an example of using decorator when writing web services using flask https://zamjad.wordpress.com/2023/09/01/writing-webservice-with-python/

Decorator is a method in python, which takes another method as an input, usually to enhance the functionality of the method. It makes our code more readable, help to introduce separation of concern and modularity. As a result, it will be easy to reuse the code. Lots of libraries uses the decorator such as flask, Django, FastAPI, Tornado, Pytest etc.

Here is the simplest form of decorator method in Python

def my_decorator(func):
    def wrapper():
        print("Before calling method")
        func()
        print("After calling method")
    return wrapper

@my_decorator
def HelloWorld():
    print("Hello world");

if __name__ == "__main__":
    HelloWorld();

This simples examples give an idea of how to do logging or authorization with of the existing method.

Let’s do something more useful and try to create a parameter for decorators. Let’s extend the previous code and call the method multiple times depends on what decorator value we pass. Here is an updated version of our new decorator

def my_decorator(n):
    def my_decorator_function(func):
        def wrapper():
            print("Before calling method")
            for _ in range(n):
                func()
            print("After calling method")
        return wrapper
    return my_decorator_function

@my_decorator(5)
def HelloWorld():
    print("Hello World");

if __name__ == "__main__":
    HelloWorld();

This print “Hello World” 5 times because we pass 5 as a decorator parameter. Now let’s try to pass parameter to the method too.

def my_decorator(n):
    def my_decorator_function(func):
        def wrapper(*argc, **kwargs):
            print("Before calling method")
            for _ in range(n):
                func(*argc, **kwargs)
            print("After calling method")
        return wrapper
    return my_decorator_function

@my_decorator(5)
def SayHello(name):
    print(f"Hello {name}");

if __name__ == "__main__":
    SayHello("Zeeshan");

Here argc and kwargs are used to pass variable number of of arguments in the decorated method. argc is for positional argument syntax and kwargs is for keyword argument.

Posted by: Zeeshan Amjad | September 4, 2023

High Order Component in React


Higher Order Component, also known as HOC is very important concept in React. It is a react pattern where a function (or class) component takes a component as an input and return a component. It is one way to enhance the functionality of a component.

React we are also doing lot of composition, but there are some differences between Higher Order Component and Composition. Composite component are created to create other components to create a complex user interface, on the other hand, higher order component is used to enhance the functionality of the existing components. Some typical examples are “Logging”, “Authenticaion”, “Styling”, “Error handling” etc. Redux connect is one such example of higher order component, that uses to connect to Redux store.

Here is a simplest template of creating higher order component in react using class component.

class HighOrderComponent extends React.Component {
    constructor(props) {
      super(props);
      this.state = {
      };
    }
  
    componentDidMount() { 
    }
  
    componentWillUnmount() {
    }
  
    render() {
      return (
        <div>
            <Comment comment={comment} key={comment.id} />
        </div>
      );
    }
  }

Here is an example of higher order component function component.

const HighOrderComponent = (ExistingComponent) => {

    return <ExistingComponent {...props} />;
};

Here is an example to use it

const HighOrderComponent = highOrderComponent(ExistingComponent);

Here is one simple example of creating Higher Order Component of doing logging at the time of mounting and unmounting using function component and useEffect hook

import React from 'react';
import { useEffect } from 'react';

const HighOrderComponent = (ExistingComponent) => {

    return function LoggingComponent(props) {
        useEffect(() => {

            console.log("Mounting ExistingComponent");

            return() => {
                console.log("Unmounting ExistingComponent");
            }
        }, []);

        return (
            <ExistingComponent {...props} />
        );        
    }

};

export default HighOrderComponent;

And it is the usage of this component

import './App.css';
import UserDialog from './UserDialog';
import {Button, Label, Form, Row, Col } from 'reactstrap';
import 'bootstrap/dist/css/bootstrap.min.css';
import { useState } from 'react';
import LoggingComponent from './LoggingComponent'

const UserDialogWithLoggin = LoggingComponent(UserDialog);

function App() {

  const [isOpen, setIsOpen] = useState(false);
  const [firstName, setFirstName] = useState('Zeeshan');
  const [lastName, setLastName] = useState('Amjad');

  const toggle = () => {
    setIsOpen(!isOpen);
  }

  return (
    <div className="App">
      <Form className="form">
        <Row>
          <Col className="md4">First Name</Col>
          <Col className="md8"><Label>{firstName}</Label></Col>
        </Row>
        <Row>
          <Col className="md4">Last Name</Col>
          <Col className="md8"><Label>{lastName}</Label></Col>
        </Row>
        <Button color="primary" onClick={() => setIsOpen(!isOpen)}>Open</Button>
      </Form>
      <UserDialogWithLoggin isOpen={isOpen} 
        toggle={toggle}
        firstName={firstName}
        lastName={lastName}/>
    </div>
  );
}

export default App;
Posted by: Zeeshan Amjad | September 1, 2023

Writing webservice with Python


We saw the example of writing webservice with node here https://zamjad.wordpress.com/2018/09/02/writing-webservice-with-node-js-and-express/

Now we are trying to do the same with python. There are different framework and libraries to write REST APIs such as Flask, Django, FastAPI, Tornado, Bottle, CherryPy, Falcon etc. Here we are going to use the flask lightweigh micro framework. The first step is to install it.

pip install flask

Let’s start with the simple program with flask.

from flask import Flask
app = Flask(__name__)

@app.route("/")
def hello() -> str:
    return "Hello World from Python"


if __name__ == "__main__":
    app.run()

Here used the decorator method @app to define the path for the REST API. By default it is running on port 5000 and run the following on the browser

http://localhost:5000/

If we want to change the port then it will be the second parameter of run method. Here is an updated code to run it on port 3000

from flask import Flask
app = Flask(__name__)

@app.route("/")
def hello() -> str:
    return "Hello World from Python"


if __name__ == "__main__":
    app.run(None, 3000)

Now let’s try to add something useful in this program. Let’s try to convert the nodejs version of the program to calculate time value of money in python. Here we are calculating present value, future value, time to double the money, perpetuity to get infinite dividend and monthly payment of loan.

from flask import Flask, request, jsonify
import math

app = Flask(__name__)

@app.route("/")
def hello() -> str:
    #return jsonify("Hello World from Python")
    return jsonify({
        "methods": [
            {
                "name": "fv",
                "description": "Calculate the future value of money",
                "parameters": {
                    "pv": "Present value of money",
                    "n": "Number of years",
                    "r": "Interest rate"
                }
            },
            {
                "name": "pv",
                "description": "Calculate the present value of money",
                "paramteres": {
                    "fv": "Future value of money",
                    "n": "Number of years",
                    "r": "Interest rate"
                }
            },
            {
                "name": "dt",
                "description": "Calculate the time to double the money",
                "parameters": {
                    "r": "Interest rate"
                }
            },
            {
                "name": "per",
                "description": "Calculate the perpetuity value to get infinite dividend",
                "parameters": {
                    "d": "Desire dividend value",
                    "r": "Interest rate"
                }
            },
            {
                "name": "pmt",
                "description": "Calculate the monthly payment of loan",
                "parameters": {
                    "loan": "Loan amount",
                    "n": "Total monthly payments",
                    "r": "Interest rate"
                }
            }
        ]
    })

@app.route("/fv", methods=["GET"])
def futureValue():
    try:
        pv = float(request.args.get("pv"))
        n = float(request.args.get("n"))
        r = float(request.args.get("r"))
    except ValueError:
        return jsonify({"error": "Invalid values."}), 400
    
    fv = pv * math.pow(1+r/100, n)
    
    return jsonify({"PresentValue": pv, "FutureValue": fv, "InterestRate": r, "Period": n})

@app.route("/pv", methods=["GET"])
def presentValue():
    try:
        fv = float(request.args.get("fv"))
        n = float(request.args.get("n"))
        r = float(request.args.get("r"))
    except ValueError:
        return jsonify({"error": "Invalid values."}), 400
    
    pv = fv / math.pow(1+r/100, n)

    return jsonify({"PresentValue": pv, "FutureValue": fv, "InterestRate": r, "Period": n})

@app.route("/dt", methods=["GET"])
def timeToDouble():
    try:
        r = float(request.args.get("r"))
    except ValueError:
        return jsonify({"error": "Invalid values."}), 400

    dt = math.log(2) / math.log(1 + r/100)

    return jsonify({"InterestRate": r, "TimeToDouble": dt})

@app.route("/per", methods=["GET"])
def pepetuity():
    try:
        d = float(request.args.get("d"))
        r = float(request.args.get("r"))
    except ValueError:
        return jsonify({"error": "Invalid values."}), 400

    per = d / (r/100)

    return jsonify({"InterestRate": r, "Divident": d, "Perpetuity": per})

@app.route("/pmt", methods=["GET"])
def payment():
    try:
        loan = float(request.args.get("loan"))
        n = float(request.args.get("n"))
        r = float(request.args.get("r"))
    except ValueError:
        return jsonify({"error": "Invalid values."}), 400
    
    r = r/100
    interestTerm = math.pow((1+r/12), n)
    pmt = (loan * r/12) / (1 - (1/interestTerm))

    return jsonify({"Loan": loan, "Period": n, "InterestRate": r*100, "Payment": pmt})
    
if __name__ == "__main__":
    app.run()

Older Posts »

Categories