Python Crash Course

Certainly! Here are ten examples for each of the topics you mentioned:

BASICS

  1. Basics:
    Example 1: Printing a message
   print("Hello, World!")

Example 2: Arithmetic operations

   a = 10
   b = 5
   print("Addition:", a + b)
   print("Subtraction:", a - b)
   print("Multiplication:", a * b)
   print("Division:", a / b)
   print("Modulo:", a % b)

Example 3: String concatenation

   name = "Alice"
   age = 25
   print("My name is " + name + " and I am " + str(age) + " years old.")

Example 4: Using the input function

   name = input("Enter your name: ")
   print("Hello, " + name + "!")

Example 5: Conditional statements

   num = int(input("Enter a number: "))
   if num > 0:
       print("The number is positive.")
   elif num < 0:
       print("The number is negative.")
   else:
       print("The number is zero.")

Example 6: Working with loops (for loop)

   for i in range(5):
       print(i)

Example 7: Working with loops (while loop)

   count = 0
   while count < 5:
       print(count)
       count += 1

Example 8: Using the len() function

   text = "Hello, World!"
   print("Length:", len(text))

Example 9: Using the str() function

   num = 42
   text = "The answer is: " + str(num)
   print(text)

Example 10: Importing and using modules

   import math

   radius = 5
   area = math.pi * radius ** 2
   print("Area of the circle:", area)

CONDITIONAL STATEMENTS IF ELSE

  1. If-Else Statements:
    Example 1: Checking if a number is even or odd
   num = int(input("Enter a number: "))
   if num % 2 == 0:
       print("The number is even.")
   else:
       print("The number is odd.")

Example 2: Checking if a year is a leap year

   year = int(input("Enter a year: "))
   if year % 400 == 0 or (year % 4 == 0 and year % 100 != 0):
       print("The year is a leap year.")
   else:
       print("The year is not a leap year.")

Example 3: Determining the maximum of three numbers

   num1 = float(input("Enter the first number: "))
   num2 = float(input("Enter the second number: "))
   num3 = float(input("Enter the third number: "))
   max_num = max(num1, num2, num3)
   print("The maximum number is:", max_num)

Example 4: Checking if a student passed or failed

   score = float(input("Enter the student's score: "))
   if score >= 60:
       print("The student passed.")
   else:
       print("The student failed.")

Example 5

: Categorizing a number into different ranges

   num = float(input("Enter a number: "))
   if num < 0:
       print("The number is negative.")
   elif num >= 0 and num <= 10:
       print("The number is between 0 and 10.")
   elif num > 10 and num <= 20:
       print("The number is between 10 and 20.")
   else:
       print("The number is greater than 20.")

Example 6: Checking if a person is eligible to vote

   age = int(input("Enter your age: "))
   if age >= 18:
       print("You are eligible to vote.")
   else:
       print("You are not eligible to vote yet.")

Example 7: Checking if a number is positive, negative, or zero (alternative approach)

   num = float(input("Enter a number: "))
   if num > 0:
       print("The number is positive.")
   elif num < 0:
       print("The number is negative.")
   else:
       print("The number is zero.")

Example 8: Checking if a character is a vowel or consonant

   char = input("Enter a character: ").lower()
   if char in ['a', 'e', 'i', 'o', 'u']:
       print("The character is a vowel.")
   else:
       print("The character is a consonant.")

Example 9: Checking if a number is a multiple of another number

   num1 = int(input("Enter the first number: "))
   num2 = int(input("Enter the second number: "))
   if num1 % num2 == 0:
       print(num1, "is a multiple of", num2)
   else:
       print(num1, "is not a multiple of", num2)

Example 10: Checking if a year is a leap year (alternative approach)

   year = int(input("Enter a year: "))
   if year % 400 == 0 or (year % 4 == 0 and year % 100 != 0):
       print("The year is a leap year.")
   else:
       print("The year is not a leap year.")

For loop with range

  1. Printing numbers from 0 to 9:
for i in range(10):
    print(i)
  1. Printing even numbers from 2 to 10:
for i in range(2, 11, 2):
    print(i)
  1. Calculating the sum of numbers from 1 to 100:
total = 0
for i in range(1, 101):
    total += i
print("Sum:", total)
  1. Printing numbers in reverse order from 9 to 0:
for i in range(9, -1, -1):
    print(i)
  1. Multiplying each number in the range by 2 and printing the result:
for i in range(10):
    result = i * 2
    print(result)
  1. Printing the square of each number in the range from 1 to 5:
for i in range(1, 6):
    square = i ** 2
    print(square)
  1. Printing numbers in increments of 5 from 0 to 50:
for i in range(0, 51, 5):
    print(i)
  1. Checking if a number is divisible by 3 in the range from 1 to 20:
for i in range(1, 21):
    if i % 3 == 0:
        print(i, "is divisible by 3")
  1. Printing the ASCII value of each character in a string:
text = "Hello"
for char in text:
    ascii_value = ord(char)
    print(char, ":", ascii_value)
  1. Repeating a specific action a certain number of times using range:
for _ in range(5):
    print("Hello, world!")

LIST

  1. List:
    Example 1: Accessing list elements
   fruits = ["apple", "banana", "orange", "grape", "mango"]
   print(fruits[0])  # "apple"
   print(fruits[2])  # "orange"

Example 2: Modifying list elements

   numbers = [1, 2, 3, 4, 5]
   numbers[2] = 10
   print(numbers)  # [1, 2, 10, 4, 5]

Example 3: Appending elements to a list

   numbers = [1, 2, 3]
   numbers.append(4)
   print(numbers)  # [1, 2, 3, 4]

Example 4: Removing elements from a list

   fruits = ["apple", "banana", "orange", "grape"]
   fruits.remove("banana")
   print(fruits)  # ["apple", "orange", "grape"]

Example 5: Slicing a list

   numbers = [1, 2, 3, 4, 5]
   print(numbers[1:4])  # [2, 3, 4]

Example 6: Checking if an element exists in a list

   fruits = ["apple", "banana", "orange", "grape"]
   if "banana" in fruits:
       print("Banana is in the list.")

Example 7: Counting occurrences of an element in a list

   numbers = [1, 2, 3, 1, 2, 1, 4, 1]
   count = numbers.count(1)
   print("Number of occurrences:", count)

Example 8: Sorting a list

   numbers = [5, 3, 1, 4, 2]
   numbers.sort()
   print(numbers)  # [1, 2, 3, 4, 5]

Example 9: Reversing a list

   fruits = ["apple", "banana", "orange", "grape"]
   fruits.reverse()
   print(fruits)  # ["grape", "orange", "banana", "apple"]

Example 10: Combining two lists

   list1 = [1, 2, 3]
   list2 = [4, 5, 6]
   combined_list = list1 + list2
   print(combined_list)  # [1, 2, 3, 4, 5, 6]

DICTIONARY

  1. Example 1: Accessing dictionary values
   student = {"name": "Alice", "age": 20, "grade": "A"}
   print(student["name"])  # "Alice"
   print(student["age"])   # 20

Example 2: Adding new key-value pairs to a dictionary

   student = {"name": "Alice", "age": 20}
   student["grade"] = "A"
   print(student)  # {"name": "Alice", "age": 20, "grade": "A"}

Example 3: Modifying dictionary values

   student = {"name": "Alice", "age": 20, "grade": "A"}
   student["age"] = 21
   print(student)  # {"name": "Alice", "age": 21, "grade": "A"}

Example 4: Checking if a key exists in a dictionary

   student = {"name": "Alice", "age": 20, "grade": "A"}
   if "age" in student:
       print("Age:", student["age"])  # Age: 20

Example 5: Removing a key-value pair from a dictionary

   student = {"name": "Alice", "age": 20, "grade": "A"}
   del student["grade"]
   print(student)  # {"name": "Alice", "age": 20}

Example 6: Getting all keys from a dictionary

   student = {"name": "Alice", "age": 20, "grade": "A"}
   keys = student.keys()
   print(keys)  # ["name", "age", "grade"]

Example 7: Getting all values from a dictionary

   student = {"name": "Alice", "age": 20, "grade": "A"}
   values = student.values()
   print(values)  # ["Alice", 20, "A"]

Example 8: Checking the length of a dictionary

   student = {"name": "Alice", "age": 20, "grade": "A"}
   length = len(student)
   print("Length:", length)  # Length: 3

Example 9: Clearing a dictionary

   student = {"name": "Alice", "age": 20, "grade": "A"}
   student.clear()
   print(student)  # {}

Example 10: Copying a dictionary

   student = {"name": "Alice", "age": 20, "grade": "A"}
   student_copy = student.copy()
   print(student_copy)  # {"name": "Alice", "age": 20, "grade": "A"}

LIST OF DICTIONARIES

employees = [
    {"name": "John", "age": 32, "department": "HR", "salary": 50000},
    {"name": "Emily", "age": 28, "department": "IT", "salary": 60000},
    {"name": "Michael", "age": 35, "department": "Finance", "salary": 70000},
    {"name": "Sophia", "age": 29, "department": "Sales", "salary": 55000},
    {"name": "Daniel", "age": 31, "department": "IT", "salary": 62000},
    {"name": "Olivia", "age": 27, "department": "HR", "salary": 48000},
    {"name": "William", "age": 33, "department": "Finance", "salary": 75000},
    {"name": "Ava", "age": 30, "department": "Sales", "salary": 58000},
    {"name": "James", "age": 34, "department": "IT", "salary": 65000},
    {"name": "Emma", "age": 26, "department": "HR", "salary": 52000}
]

Now, let’s provide 10 examples using the same list of employees:

  1. Accessing values in the list:
print(employees[0]["name"])     # Output: "John"
print(employees[3]["age"])      # Output: 29
  1. Modifying a value in the list:
employees[2]["salary"] = 72000
print(employees[2])             # Output: {'name': 'Michael', 'age': 35, 'department': 'Finance', 'salary': 72000}
  1. Adding a new key-value pair to a dictionary:
employees[1]["position"] = "Senior Software Engineer"
print(employees[1])             # Output: {'name': 'Emily', 'age': 28, 'department': 'IT', 'salary': 60000, 'position': 'Senior Software Engineer'}
  1. Removing a key-value pair from a dictionary:
del employees[4]["age"]
print(employees[4])             # Output: {'name': 'Daniel', 'department': 'IT', 'salary': 62000}
  1. Counting the number of dictionaries in the list:
count = len(employees)
print("Number of employees:", count)   # Output: Number of employees: 10
  1. Calculating the average age of all employees:
total_salary = 0
num_employees = len(employees)

for employee in employees:
    total_salary += employee["salary"]

average_salary = total_salary / num_employees

print("Average salary:", average_salary)
  1. Finding the employee with the highest salary:
max_salary = 0
employee_with_max_salary = None

for employee in employees:
    if employee["salary"] > max_salary:
        max_salary = employee["salary"]
        employee_with_max_salary = employee

print("Employee with the highest salary:")
print("Name:", employee_with_max_salary["name"])
print("Salary:", employee_with_max_salary["salary"])
  1. Finding all employees having highest salary:
max_salary = 0
employees_with_max_salary = []

for employee in employees:
    if employee["salary"] > max_salary:
        max_salary = employee["salary"]
        employees_with_max_salary = [employee]
    elif employee["salary"] == max_salary:
        employees_with_max_salary.append(employee)

print("Employees with the highest salary:")
for employee in employees_with_max_salary:
    print("Name:", employee["name"])
    print("Salary:", employee["salary"])
    print()
  1. Calculating total, average, highest and lowest salaries all employees:
total_salary = 0
highest_salary = float("-inf")
lowest_salary = float("inf")

for employee in employees:
    salary = employee["salary"]
    total_salary += salary

    if salary > highest_salary:
        highest_salary = salary

    if salary < lowest_salary:
        lowest_salary = salary

average_salary = total_salary / len(employees)

print("Total Salary:", total_salary)
print("Highest Salary:", highest_salary)
print("Lowest Salary:", lowest_salary)
print("Average Salary:", average_salary)
  1. Print all employees using PrettyTable:
# Print all employees
all_employees_table = PrettyTable(["Name", "Department", "Salary"])
for employee in employees:
    all_employees_table.add_row([employee["name"], employee["department"], employee["salary"]])
all_employees_table.title = "All Employees"
print(all_employees_table)

Mini Project

Print department wise highest salaried employees

Expected output

Demo

Basic

  1. WAP to read 2 numbers and print addition
  2. WAP to read 2 numbers and print subtraction
  3. WAP to read 2 numbers and print multiplication
  4. WAP to read 2 numbers and print division
  5. WAP to read 2 numbers and print modulus (Remainder)
  6. WAP to read radius and print area and circumference of circle
  7. WAP to read length and breadth and print area and perimeter of rectangle

Conditional Statement (if else)

  1. WAP to read a number and check if its positive or negative
  2. WAP to read a number and check it is even or odd
  3. WAP to read 2 numbers and find greatest among them
  4. WAP to read 3 numbers and find greatest among them
  5. WAP to read marks of 5 subjects and check the student is pass or failed
    1. add validation for marks less than 0
    2. add validation for marks greater than 100

Loops

  1. WAP to print hello world 10 times with numbering
  2. WAP to print square of numbers from 1 to 10
  3. WAP to print numbers from 1 to given number
  4. WAP to print cube of numbers from 1 to given number
  5. WAP to read a number and print table of that number
  6. WAP to execute Fizz Buzz Problem / Print number 1 to 100
    1. if number is divisible by 3 then print Fizz
    2. if number is divisible by 5 then print Buzz
    3. if number is divisible by both 3 and 5 then print Fizz Buzz
  7. WAP to execute lift program of 20 floor
    1. print number with delay of 1 sec (use time module’s sleep method)
    2. skip 13 number
    3. break after printing 13
  8. WAP to create random jackpot number and take input from user to guess the number. Based on level the attempt to guess the number should change
    1. Easy – 20 attempts
    2. Medium – 10 attempts
    3. Difficult – 5 attempts

Deploy Flask App on Heroku

mkdir app
cd app

app.py

from flask import Flask, jsonify, request

app = Flask(__name__)

@app.route("/")
def index():
    return "Hello World!"

@app.route('/add')
def add():
    num1 = int(request.args.get('num1'));
    num2 = int(request.args.get('num2'));

    return f"{num1} + {num2} = {num1 + num2}"

#if __name__ == "__main__":
    #app.run(debug=True);
    #app.run(host="0.0.0.0", port=int("1234"), debug=True)

runtime.txt

python-3.10.8

Procfile

web: gunicorn app:app

requirements.txt

click==8.0.3
colorama==0.4.4
Flask==2.0.2
Flask-Cors==3.0.10
gunicorn==20.1.0
itsdangerous==2.0.1
Jinja2==3.0.3
MarkupSafe==2.0.1
PyMySQL==1.0.2
six==1.16.0
Werkzeug==2.0.2

OR

You can output all dependencies using following command

python -m pip freeze > requirements.txt
heroku login

#onetime
heroku create <appname>
heroku git:remote -a <appname>
git init

#repeat whenever you make changes
git add .
git commit -m 'heroku push'
git push heroku master

Test API

https://myflaskapp2022.herokuapp.com/
https://myflaskapp2022.herokuapp.com/add?num1=5&num2=9

Troubleshoot

heroku logs --tail --app eflask-app-dusra

If still it is not working please do check spellings of files

https://devcenter.heroku.com/articles/buildpacks

Flask Cheat Sheet

keyword arguments

Keyword arguments (or named arguments) are values that, when passed into a function, are identifiable by specific parameter names.
keyword argument is preceded by a parameter and the assignment operator, = . Keyword arguments can be likened to dictionaries in that they map a value to a keyword.

The order of the arguments does not matter

def my_function(child3, child2, child1):
  print("The youngest child is " + child3)

my_function(child1 = "Emil", child2 = "Tobias", child3 = "Linus")

The phrase Keyword Arguments are often shortened to kwargs in Python documentations.

arguments vs keyword arguments (*args vs **kwargs)

def foo(*args, **kwargs):
    print(args);
    print(kwargs);
    
foo(5, 6, 7, name="Shailesh", age=32, city="Nagpur");
output

Decorators

A decorator is a design pattern in Python that allows a user to add new functionality to an existing object without modifying its structure.
Decorators are usually called before the definition of a function you want to decorate.

### CREATE CUSTOM DECORATOR ###
from functools import wraps

def my_decorator(f):
    @wraps(f)
    def msg(*args, **kwargs):
        print("I am from custom decorator")
        print("Arguments:", args)
        print("Keyword Arguments:", kwargs)
        
        return f(*args, **kwargs)
        
    return msg;


@my_decorator    
def add(x, y):
    print(f"{x} + {y} = {x + y}")

    
@my_decorator
def sub(x, y):
    print(f"{x} - {y} = {abs(x - y)}")
    
    
#invoke functions
add(5, y=6)
sub(5, y=6)
output

Flask Framework

Flask is a micro web framework written in Python. It is classified as a microframework because it does not require particular tools or libraries.
It has no database abstraction layer, form validation, or any other components where pre-existing third-party libraries provide common functions.

install flask module

python -m pip install Flask

hello world

from flask import Flask, jsonify, request, render_template

app = Flask(__name__)

#YOUR FUNCTIONS HERE

if __name__ == "__main__":
    app.run(debug=True);
    #app.run(host="0.0.0.0", port=int("1234"), debug=True)

render html template [NOTE: MAKE SURE TO KEEP ALL TEMPLATE FILES IN templates DIRECTORY]

@app.route('/')
def index():
    #return "Hello World";
    
    data = {'company_name': "TCET"}
    return render_template('hello_world.html', data = data)

templates/hello_world.html

<h1>Hello World</h1>
<h3>Welcome to {{data['company_name']}}</h3>

read get value

@app.route('/sqr', methods=['GET'])
def getSqr():
    num1 = int(request.args.get('num1'));
    return f"Square of {num1} is {num1 * num1}"


@app.route('/add', methods=['GET'])
def add():
    num1 = int(request.args.get('num1'));
    num2 = int(request.args.get('num2'));
    
    return f"{num1} + {num2} = {num1 + num2}";

read post value

@app.route('/sub', methods=['POST'])
def sub():
    num1 = int(request.form.get('num1'));
    num2 = int(request.form.get('num2'));
    
    return f"{num1} - {num2} = {num1 - num2}";

read raw json

@app.route('/mul', methods=['POST'])
def mul():
    raw_json = request.get_json();
    num1 = int(raw_json['num1']);
    num2 = int(raw_json['num2']);
    
    return f"{num1} * {num2} = {num1 * num2}";

install pymysql module

python -m pip install PyMySQL

install cors module

python -m pip install -U flask-cors

get users from database

from flask import Flask, jsonify, request
from flask_cors import CORS
import pymysql

app = Flask(__name__)
cors = CORS(app)

@app.route('/users', methods=['GET'])
def get_users():
    # To connect MySQL database
    conn = pymysql.connect(host='localhost', user='root', password = "", db='databasename')
        
    cur = conn.cursor()
    cur.execute("select * from users LIMIT 10")
    output = cur.fetchall()

    print(type(output)); #this will print tuple	

    for rec in output:
        print(rec);
        
    # To close the connection
    conn.close()

    return jsonify(output);

fetch data using javascript fetch api

let url = "http://localhost:5000";
fetch(url)
    .then(response => response.json())
    .then(response => console.table(response));

Flask RESTful API

Flask-RESTful is an extension for Flask that adds support for quickly building REST APIs.

install flask-restful

python -m pip install flask-restful

MyApi Resource

from flask import Flask, request
from flask_restful import Resource, Api

app = Flask(__name__)
api = Api(app)

class MyApi(Resource):
    def __init__(self):
        print("Constructor called...")
        
    def get(self):
        return {"msg" : "get method"}
        
    def post(self):
        return {"msg" : "post method"}
        
    def put(self):
        return {"msg" : "put method"}
    
    def delete(self):
        return {"msg" : "delete method"}
    
    
api.add_resource(MyApi, '/myapiurl')

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

Authenticate REST API

from flask import Flask, request, make_response
from flask_restful import Resource, Api
from functools import wraps


app = Flask(__name__)
api = Api(app)


#define custom decorator @authorize
def authorize(f):
    @wraps(f)
    def kuchbhi(*args, **kwargs):
        err_msg = "Authentication required";
    
        if(request.authorization == None):
            return make_response('Not Authorized', 403, {'WWW-Authenticate' : err_msg})
            
        unm = request.authorization.username
        pwd = request.authorization.password
        
        if(unm == 'admin' and pwd == 'admin@123'):
            print("Correct username and password")
            return f(*args, **kwargs)
        
        return make_response('Not Authorized', 403, {'WWW-Authenticate' : err_msg})
    
    return kuchbhi


class MyApi(Resource):
    
    def __init__(self):
        print("Constructor called...")

    @authorize 
    def get(self):
        return {"msg" : "get method"}

    @authorize    
    def post(self):
        return {"msg" : "post method"}

    @authorize    
    def put(self):
        return {"msg" : "put method"}

    @authorize
    def delete(self):
        return {"msg" : "delete method"}
    
api.add_resource(MyApi, '/myapiurl')

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


apply authorize decorator to all methods of call

from flask import Flask, request, make_response
from flask_restful import Resource, Api
from functools import wraps

app = Flask(__name__)
api = Api(app)

#define custom decorator authorize
def authorize(f):
    @wraps(f)
    def kuchbhi(*args, **kwargs):
        err_msg = "Authentication required";
    
        if(request.authorization == None):
            return make_response('Not Authorized', 403, {'WWW-Authenticate' : err_msg})
            
        unm = request.authorization.username
        pwd = request.authorization.password
        
        if(unm == 'admin' and pwd == 'admin@123'):
            print("Correct username and password")
            return f(*args, **kwargs)
        
        return make_response('Not Authorized', 403, {'WWW-Authenticate' : err_msg})
    
    return kuchbhi


class MyApi(Resource):
    method_decorators = [authorize]
    
    def __init__(self):
        print("Constructor called...")
        
    def get(self):
        return {"msg" : "get method"}
        
    def post(self):
        return {"msg" : "post method"}
        
    def put(self):
        return {"msg" : "put method"}
    
    def delete(self):
        return {"msg" : "delete method"}
    
api.add_resource(MyApi, '/myapiurl')

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

Testing API

test response status
test_myapiapp.py
where myapiapp.py is the file where all restful api defined

#from filename import app
from rest_api import app
import unittest
import base64

class RestAPITest(unittest.TestCase):
    
    def test_status(self):
        tester = app.test_client(self)
        response = tester.get('/myapiurl')
        self.assertEqual(response.status_code, 200)
   
if __name__ == "__main__":
    unittest.main()

test content type

def test_content_type(self):
    tester = app.test_client(self)
    response = tester.get('/myapiurl')

    self.assertEqual(response.content_type, "application/json")

test content data

def test_content(self):
    tester = app.test_client(self)
    response = tester.get('/myapiurl')        
    self.assertTrue(b'get' in response.data)

To pass Basic Auth credentials in header

creds = base64.b64encode(b"admin:admin@123").decode("utf-8")
response = tester.get('/myapiurl', headers={"Authorization": f"Basic {creds}"})

complete test file code

#from filename import app
from rest_api import app
import unittest
import base64

class RestAPITest(unittest.TestCase):
    
    def test_status(self):
        tester = app.test_client(self)
        #response = tester.get('/myapiurl')
        
        creds = base64.b64encode(b"admin:admin@123").decode("utf-8")
        response = tester.get('/myapiurl', headers={"Authorization": f"Basic {creds}"})
        
        self.assertEqual(response.status_code, 200)
        
    
    def test_content_type(self):
        tester = app.test_client(self)
        #response = tester.get('/myapiurl')
        
        creds = base64.b64encode(b"admin:admin@123").decode("utf-8")
        response = tester.get('/myapiurl', headers={"Authorization": f"Basic {creds}"})
        
        self.assertEqual(response.content_type, "application/json")
        
        
    def test_content(self):
        tester = app.test_client(self)
        #response = tester.get('/myapiurl')
        
        creds = base64.b64encode(b"admin:admin@123").decode("utf-8")
        response = tester.get('/myapiurl', headers={"Authorization": f"Basic {creds}"})
        
        self.assertTrue(b'get' in response.data)
        
        
if __name__ == "__main__":
    unittest.main()
output

REST API CRUD

app.py

import pymysql

from flask import Flask, jsonify, request
from flask_cors import CORS
import pymysql

app = Flask(__name__)
cors = CORS(app)

# To connect MySQL database
conn = pymysql.connect(host='yourhost', user='youruser', password = "yourpassword", db='yourdatabase')

@app.route('/users', methods=['GET'])
def get_users():

    cur = conn.cursor(pymysql.cursors.DictCursor)
    cur.execute("select * from users LIMIT 10")
    output = cur.fetchall()

    print(type(output)); #this will print tuple

    for rec in output:
        print(rec);

    # To close the connection
    #conn.close()

    return jsonify(output);


@app.route('/users/get_one_record', methods=['GET'])
def get_single_user():

    cur = conn.cursor(pymysql.cursors.DictCursor)
    userid = int(request.args.get('id'));
    cur.execute(f"select * from users WHERE id = {userid}")
    output = cur.fetchone()
    
    return jsonify(output);



@app.route('/users', methods=['DELETE'])
def deleteRecord():
    cur = conn.cursor()
    id = int(request.args.get('id'));

    query = f"delete from users where id = {id}";
    #print(query)
    res = cur.execute(query);
    conn.commit();
    print(cur.rowcount, "record(s) deleted")

    return "Record deleted sussesfully"

@app.route('/users', methods=['POST'])
def insertRecord():

        #get raw json values
        raw_json = request.get_json();
        name= raw_json['name'];
        age= raw_json['age'];
        city= raw_json['city'];

        sql="INSERT INTO users (id,name,age,city) VALUES (NULL,'"+name+"','"+str(age)+"','"+city+"')";
        cur= conn.cursor()

        cur.execute(sql);
        conn.commit()
        return "Record inserted Succesfully"

@app.route('/users', methods=['PUT'])
def updateRecord():

        raw_json = request.get_json();

        #print(type(raw_json));

        id = raw_json['id'];
        name= raw_json['name'];
        age= raw_json['age'];
        city= raw_json['city'];
        sql_update_quary=("UPDATE users SET name = '"+name+"',age = '"+str(age)+"',city = '"+city+"'WHERE id = '"+str(id)+"'");
        cur= conn.cursor()
        cur.execute(sql_update_quary);
        conn.commit()
        return "Record Updated Sussecfully";


if __name__ == "__main__":
    #app.run(debug=True);
    app.run(host="0.0.0.0", port=int("1235"), debug=True)

script.js

//const api_url = "<heroku_app_url>"
const api_url = "http://localhost:8080/users"

function loadData(records = []) {
	var table_data = "";
	for(let i=0; i<records.length; i++) {
		table_data += `<tr>`;
		table_data += `<td>${records[i].name}</td>`;
		table_data += `<td>${records[i].age}</td>`;
		table_data += `<td>${records[i].city}</td>`;
		table_data += `<td>`;
		table_data += `<a href="edit.html?id=${records[i].id}"><button class="btn btn-primary">Edit</button></a>`;
		table_data += '&nbsp;&nbsp;';
		table_data += `<button class="btn btn-danger" onclick=deleteData('${records[i].id}')>Delete</button>`;
		table_data += `</td>`;
		table_data += `</tr>`;
	}
	//console.log(table_data);
	document.getElementById("tbody").innerHTML = table_data;
}

function getData() {
	fetch(api_url)
	.then((response) => response.json())
	.then((data) => { 
		console.table(data); 
		loadData(data);
	});
}


function getDataById(id) {
	fetch(`${api_url}/get_one_record?id=${id}`)
	.then((response) => response.json())
	.then((data) => { 
	
		console.log(data);
		document.getElementById("id").value = data.id;
		document.getElementById("name").value = data.name;
		document.getElementById("age").value = data.age;
		document.getElementById("city").value = data.city;
	})
}


function postData() {
	var name = document.getElementById("name").value;
	var age = document.getElementById("age").value;
	var city = document.getElementById("city").value;
	
	data = {name: name, age: age, city: city};
	
	fetch(api_url, {
		method: "POST",
		headers: {
		  'Accept': 'application/json',
		  'Content-Type': 'application/json'
		},
		body: JSON.stringify(data)
	})
	.then((response) => response.json())
	.then((data) => { 
		console.log(data); 
		window.location.href = "index.html";
	})
}	


function putData() {
	
	var id = document.getElementById("id").value;
	var name = document.getElementById("name").value;
	var age = document.getElementById("age").value;
	var city = document.getElementById("city").value;
	
	data = {id: id, name: name, age: age, city: city};
	
	fetch(api_url, {
		method: "PUT",
		headers: {
		  'Accept': 'application/json',
		  'Content-Type': 'application/json'
		},
		body: JSON.stringify(data)
	})
	.then((response) => response.json())
	.then((data) => { 
		console.table(data);
		window.location.href = "index.html";
	})
}


function deleteData(id) {
	user_input = confirm("Are you sure you want to delete this record?");
	if(user_input) {
		//url = "http://localhost:8080/users?id=1234"
		
		fetch(`${api_url}?id=${id}`, {
			method: "DELETE",
			headers: {
			  'Accept': 'application/json',
			  'Content-Type': 'application/json'
			},
			body: JSON.stringify({"_id": id})
		})
		.then((response) => response.json())
		.then((data) => { 
			console.log(data); 
			window.location.reload();
		})
	}
}

index.html

<!DOCTYPE html>
<html>
	<head>
		<title>CIA Institute - Python Flask Project</title>
		<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" crossorigin="anonymous">
		<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js"crossorigin="anonymous"></script>
	</head>
	<body class="d-flex flex-column h-100 container">
		<header>
			<nav class="navbar navbar-expand-lg navbar-expand-sm navbar-light bg-light">
			  <div class="container-fluid">
				<div class="collapse navbar-collapse" id="navbarNavAltMarkup">
				  <div class="navbar-nav">
					<a class="nav-link active" aria-current="page" href="#">Listing</a>
					<a class="nav-link" href="add.html">Add New</a>
				  </div>
				</div>
			  </div>
			</nav>
		</header>
		
		<table class="table table-striped table-hover text-center">
			<thead>
				<th>Name</th>
				<th>Age</th>
				<th>City</th>
				<th>Action</th>
			</thead>
			<tbody id="tbody">
				
			</tbody>
			<tfoot>
				
			</tfoot>
		</table>
		
		<footer class="footer mt-auto py-3 bg-light">
		  <div class="container text-center">
			<span class="text-muted"> &copy; CIA Institute 2023</span>
		  </div>
		</footer>
	</body>
	<script src="script.js"></script>
	<script>
		getData();
	</script>
</html>

add.html

<html>
	<head>
		<title>CIA Institute - Python Flask Project</title>
		<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" crossorigin="anonymous">
		<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js"crossorigin="anonymous"></script>
	</head>
	<body class="d-flex flex-column h-100 container">
		<header>
			<nav class="navbar navbar-expand-lg navbar-expand-sm navbar-light bg-light">
			  <div class="container-fluid">
				<div class="collapse navbar-collapse" id="navbarNavAltMarkup">
				  <div class="navbar-nav">
					<a class="nav-link" href="index.html">Listing</a>
					<a class="nav-link active" aria-current="page" href="add.html">Add New</a>
				  </div>
				</div>
			  </div>
			</nav>
		</header>
		
		<h3>Add Document</h3>
		
		<form onsubmit="return false;">
		  <div class="mb-3">
			<label for="name" class="form-label">Name</label>
			<input type="text" class="form-control" id="name" autofocus>
		  </div>
		  <div class="mb-3">
			<label for="exampleInputPassword1" class="form-label">Age</label>
			<input type="text" class="form-control" id="age">
		  </div>
		  <div class="mb-3">
			<label for="city" class="form-label">City</label>
			<input type="text" class="form-control" id="city">
		  </div>
		  <button class="btn btn-primary" onclick="return postData()">Submit</button>
		  <a href="index.html" class="btn btn-primary">Cancel</a>
		</form>
		
		<footer class="footer mt-auto py-3 bg-light">
		  <div class="container text-center">
			<span class="text-muted"> &copy; CIA Institute 2022</span>
		  </div>
		</footer>
	</body>
	<script src="script.js"></script>
	<script>
	</script>
</html>

edit.html

<html>
	<head>
		<title>CIA Institute - Python Flask Project</title>
		<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" crossorigin="anonymous">
		<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js"crossorigin="anonymous"></script>
	</head>
	<body class="d-flex flex-column h-100 container">
		<header>
			<nav class="navbar navbar-expand-lg navbar-expand-sm navbar-light bg-light">
			  <div class="container-fluid">
				<div class="collapse navbar-collapse" id="navbarNavAltMarkup">
				  <div class="navbar-nav">
					<a class="nav-link" href="index.html">Listing</a>
					<a class="nav-link active" aria-current="page" href="add.html">Add New</a>
				  </div>
				</div>
			  </div>
			</nav>
		</header>
		<h3>Edit Document</h3>
		<form onsubmit="return false;">
			<input type="hidden" class="form-control" id="id">
		  <div class="mb-3">
			<label for="name" class="form-label">Name</label>
			<input type="text" class="form-control" id="name" autofocus>
		  </div>
		  <div class="mb-3">
			<label for="exampleInputPassword1" class="form-label">Age</label>
			<input type="text" class="form-control" id="age">
		  </div>
		  <div class="mb-3">
			<label for="city" class="form-label">City</label>
			<input type="text" class="form-control" id="city">
		  </div>
		  <button class="btn btn-primary" onclick="return putData()">Update</button>
		  <a href="index.html" class="btn btn-primary">Cancel</a>
		</form>
		
		<footer class="footer mt-auto py-3 bg-light">
		  <div class="container text-center">
			<span class="text-muted"> &copy; CIA Institute 2022</span>
		  </div>
		</footer>
	</body>
	<script src="script.js"></script>
	<script>
		const urlParams = new URLSearchParams(window.location.search);
		const id = urlParams.get('id');
		getDataById(id);
	</script>
</html>

Django REST framework Cheat Sheet

Django Cheat Sheet (codeinsightacademy.com)

pip3 install djangorestframework
python3 manage.py startapp employee
Note: Make sure your sql service is running.

settings.py

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'webpage',
    'rest_framework',
    'employee',
]

employee/models.py

from django.db import models

class Employee(models.Model):
    post = models.CharField(max_length = 100)
    name = models.CharField(max_length = 100)
    salary = models.IntegerField()
    is_active = models.BooleanField(default=False)
    added_date = models.DateField(auto_created=True)
    updated_date = models.DateField(auto_now=True)

    def __str___(self):
        return self.title

to make and apply the migrations run

./manage.py makemigrations
./manage.py migrate

employee/serializers.py

from rest_framework import serializers
from employee.models import Employee

class EmployeeSerializer(serializers.ModelSerializer):
    class Meta:
        model = Employee
        fields = "__all__"

employee/views.py

from django.shortcuts import render
from rest_framework.generics import ListAPIView
from rest_framework.generics import CreateAPIView
from rest_framework.generics import DestroyAPIView
from rest_framework.generics import UpdateAPIView
from employee.serializers import EmployeeSerializer
from employee.models import Employee

class ListEmpAPIView(ListAPIView):
    queryset = Employee.objects.all()
    serializer_class = EmployeeSerializer

class CreateEmpAPIView(CreateAPIView):
    queryset = Employee.objects.all()
    serializer_class = EmployeeSerializer

class UpdateEmpAPIView(UpdateAPIView):
    queryset = Employee.objects.all()
    serializer_class = EmployeeSerializer

class DeleteEmpAPIView(DestroyAPIView):
    queryset = Employee.objects.all()
    serializer_class = EmployeeSerializer

employee/urls.py

from django.urls import path
from employee import views

urlpatterns = [
    path("",views.ListEmpAPIView.as_view(),name="employee_list"),
    path("create/", views.CreateEmpAPIView.as_view(),name="employee_create"),
    path("update/<int:pk>/",views.UpdateEmpAPIView.as_view(),name="update_employee"),
    path("delete/<int:pk>/",views.DeleteEmpAPIView.as_view(),name="delete_employee")
]

main urls.py

urlpatterns = [
path('admin/', admin.site.urls),
path('api/v1/employee/',include("employee.urls"))
]

Run the api in postman with urls

POST request : http://localhost:8000/api/v1/employee/create/ 
GET request : http://localhost:8000/api/v1/employee
UPDATE request : http://localhost:8000/api/v1/employee/update/1/ 
DELETE request : http://localhost:8000/api/v1/employee/delete/1/ 

Django Cheat Sheet

Install Django

python -m pip install Django==3.1.3

Verify Django Installation

python -m django --version

List all installed python modules / packages

python -m pip list

Create new django project

django-admin startproject projectname

Run Django Project

python manage.py runserver

Create New App

python manage.py startapp newappname

manage.py help

python manage.py help

MySql Database connection

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql', 
        'NAME': 'DB_NAME',
        'USER': 'DB_USER',
        'PASSWORD': 'DB_PASSWORD',
        'HOST': 'localhost',   # Or an IP Address that your DB is hosted on
        'PORT': '3306',
    }
}

open db shell with default connection

python manage.py dbshell

MySql Database Connection Troubleshoot in Windows OS
Download whl package which is compatible with your python version
https://www.lfd.uci.edu/~gohlke/pythonlibs/
Find: mysqlclient

To check whether python is 32 or 64 bit just run following command

python -m pip install mysqlclient-1.4.6-cp37-cp37m-win32.whl

open django project shell in terminal

python manage.py shell

open db shell with specific connection

python manage.py dbshell --database "connection_name"

Create model of legacy(existing) database table using inspectdb

python manage.py inspectdb --database='connection_name' table_name

Import Models in shell

from app.models import ModelName

Select data from table using Django ORM

queryset = ModelName.objects.all()
print(queryset.query)
print(list(queryset))

Filter data using ORM

queryset = ModelName.objects.filter(column=value)
queryset = ModelName.objects.get(column=value) #this will give you single record
queryset = ModelName.objects.filter(column__iexact=value, column2__exact=value2)
queryset = ModelName.objects.filter(col__subcol=value) #for relationship

Limit records in ORM

queryset = ModelName.objects.all()[:10]

Order by in ORM

queryset = ModelName.objects.all().order_by('columnname')
queryset = ModelName.objects.all().order_by('-columnname')
queryset = ModelName.objects.all().order_by('columnname').reverse()

Relationship in models.py (this should be in Model which has foreign key)

foreign_key_col = models.ForeignKey(PrimaryModelName, related_name = 'related_name', on_delete = models.CASCADE, db_column = 'foreign_key_column_name')

install packages from requirements.txt for your project

python -m pip install -r requirements.txt"

Django restframework Cheat Sheet (codeinsightacademy.com)

OOPS

  1. Design a class Rectangle
    data members
    length
    breadth
    member functions/methods
    setDimension()
    area()
    perimeter()

  2. Design a class Worker
    data members
    wages
    wdays
    member function / method
    setData()
    payment()

  3. Design a class Box
    data members
    length
    breadth
    height
    member functions / methods
    setDimension()
    volume()

  4. Design a class Rectangle (only for Java / C++)
    data members
    length
    breadth
    member functions / methods
    setDimension()
    area()
    perimeter()
    It must overload setDimension() method twice:
    1. by passing 1 argument
    2. by passing 2 arguments

  5. Design a class Box (only for Java / C++)
    data members
    length
    breadth
    height
    member functions / methods
    volume()
    It must contain 3 constructors
    1. 1 parameter
    2. 2 parameter
    3. 3 paramter
  6. Design a class Account
    data members
    balance
    member functions / methods
    deposit(amt)
    withdraw(amt)
    showBalance()

  7. Design a class Set
    data members
    3 numbers
    member functions / methods
    SUM()
    MEAN()
    MAX()
    MIN()

  8. Design a class Student
    data members
    roll_number
    name
    member functions / methods
    setData()
    getData()

  9. Design a class Account
    data members
    balance
    interest_rate
    interest_rate must be shared by all objects (static modifier) and its default value 10.25
    interest(no_of_years)

  10. Design a class Student
    data members
    roll_number
    name
    member functions / methods
    setData()
    getData()

  11. Design a class Account
    account_number
    balance
    interest_rate
    member functions / methods
    interest(no_of_years)

  12. Design a class Student
    data members
    roll_number
    name
    member function / methods
    getData()
    roll_number must be automatically generated.It also keep track of total number of Students.

  13. Design a package MyCircle and MyRectangle (Only for Java)
    radius
    length
    breadth
    member functions / methods:
    area()
    circumference()
    perimeter()

  14. Design a class Student
    data members
    roll_number
    name
    member functions / methods
    getData()
    showData()
    Create 5 objects of Student using Array

  15. Design a class Student and List ClassRoom
    add list of Students in ClassRoom
    display List

  16. Design a class Account and List Bank
    add list of Account in Bank
    display List

  17. Create array of Student Objects
    data members
    roll_no
    name
    college
    member functions / methods
    readData()
    showData()

  18. Create a class RBI (Only for Java)
    data members
    balance
    member functions
    RBI()
    deposit(int amt)
    withdraw(int amt)
    showBalance()

Hello World django

Here are simple steps to create hello world web application in python using django framework

  1. Step 1: Install virtual environment and create virtual environment for your project
    pip install virtualenvwrapper-win
    
    mkvirtualenv myproject
  2. pip install virtualenv
  3. virtualenv name_to_your_env
    
  4. name_to_your_env\Scripts\activate
  5. After activation 
    
    $ django-admin.py startproject HelloWorld  $ cd HelloWorld 
    $ ls HelloWorld manage.py
  6. $ python manage.py runserver 
    Validating models... 
    0 errors found ... 
    Django version 1.6.5, using settings 'HelloWorld.settings' 
    Starting development server at http://127.0.0.1:8000/ 
    Quit the server with CONTROL-C.
  7. $ django-admin startapp HelloWorldApp
    $ ls
    HelloWorld HelloWorldApp manage.py
  8. edit settings.py under HelloWorld project directory
    # Application definition
    INSTALLED_APPS = ( ‘django.contrib.admin’,
    ‘django.contrib.auth’,
    ‘django.contrib.contenttypes’,
    ‘django.contrib.sessions’,
    ‘django.contrib.messages’,
    ‘django.contrib.staticfiles’,
    ‘HelloWorldApp’, )
  9. modify the urls.py which is under the project directory, HelloWorld
    from django.conf.urls import patterns, include, url 
    from HelloWorldApp.views import foo 
    
    #from django.contrib import admin 
    #admin.autodiscover() 
    
    urlpatterns = patterns('', 
    # Examples: 
    # url(r'^$', 'HelloWorld.views.home', name='home'), 
    # url(r'^blog/', include('blog.urls')), 
    #url(r'^admin/', include(admin.site.urls)), 
    url(r'HelloWorldApp/$', foo), 
    )
  10. modify views.py under app directory, HelloWorldApp
    # Create your views here. 
    from django.http import HttpResponse 
    def foo(request): 
        return HttpResponse("Hello World!")
  11. Run the server
    python manage.py runserver

     

  12. Hit this URL on browser
    http://localhost:8000/HelloWorldApp/

 

Ref Links:

  • https://docs.djangoproject.com/en/1.11/howto/windows/
  • http://www.bogotobogo.com/python/Django/Python_Django_hello_world.php
  • https://stackoverflow.com/questions/18684231/python-setup-command-not-found
  • https://stackoverflow.com/questions/8074955/cannot-import-name-patterns
  • https://scotch.io/tutorials/build-your-first-python-and-django-application
  • http://jinja.pocoo.org/docs/2.10/templates/

Arrays Programs (Multi Dimensional)

  1. WAP to read a matrix of size 3 X 5 and find their SUM
  2. WAP to read a matrix of size 3 X 5 and find sum of each ROW
  3. WAP to read a matrix of size 3 X 3 and check if it is NULL or NOT
  4. WAP to read a matrix of size 3 X 5 and count all EVEN and ODD numbers
  5. WAP to read matrix of size 3 X 3 and check if it is UNIT Matrix or NOT
  6. WAP to read 2 matrix of size 3 X 3 and find their Addition
  7. WAP to read 2 matrix of size 3 X 3 and find their Product
  8. WAP to read matrix of size 3 X 3 and find its Transpose
  9. WAP to read matrix of size 3 X 3 and find its Transpose without using second matrix
  10. WAP to read matrix of size 3 X 3 and find its Upper Triangular Matrix
  11. WAP to read matrix of size 3 X 3 and find its Lower Triangular Matrix
  12. WAP to read matrix of size 3 X 3 and check if sum of its diagonal is same or not
  13. WAP to read matrix of size 3 X 3 and check if sum of its middle row is same as sum of its middle column
  14. WAP to create TIC-TAC-TOE by showing number and take 9 inputs from 2 users.
    1 2 3
    4 5 6
    7 8 9

    X O X
    O X O
    O O X

    PLAYER 1 WIN
    O X O
    X O X
    O X O

    PLAYER 2 WIN

Arrays Programs (One Dimensional)

  1. WAP to read an array of 10 numbers and find their sum
  2. WAP to read temperature days of Week and find their Mean
  3. WAP to read an array of 10 numbers and find greatest of them
  4. WAP to read an array of 10 numbers and count all EVEN and ODD numbers
  5. WAP to rad an array of 10 numbers and find sum, mean, min, max
  6. WAP to read an array of 10 numbers and search a number in it
  7. WAP to read an array of 10 numbers and sort it in ascending order
  8. WAP to read an array of 10 numbers and sort it in descending order
  9. WAP to insert a number at given position in an array (optional)
  10. WAP to remove a number from given position from an array (optional)
  11. WAP to arrange all even numbers at top and all odd numbers at bottom of an array (optional)