Python Java SQL Course Notes C C++ HTML CSS JS

Notes

Quick, copy-friendly code notes — paste any snippet straight into your project.

GET

pyhon
from flask import Flask, jsonify, request
import config

app = Flask(__name__)

@app.route("/")
def hello_world():
    return "Home Page"

@app.route("/mobiles")
def mobiles():
    return "Mobiles List"

@app.route("/mobiles/oppo")
def oppo_mobiles():
    return "Oppo Mobiles List"

@app.route("/students")
def students():
    mydb = config.connect()
    mc = mydb.cursor(dictionary=True)
    mc.execute("select * from students;")
    r = mc.fetchall()
    return jsonify(r)

@app.route("/students/<int:id>",methods=["GET"])
def one_students(id):
    mydb = config.connect()
    mc = mydb.cursor(dictionary=True)
    mc.execute('''select * from students where
    roll_no=%s;''',(id,))
    r = mc.fetchall()
    return jsonify(r)

@app.route("/students/<gender>",methods=["GET"])
def gender_students(gender):
    mydb = config.connect()
    mc = mydb.cursor(dictionary=True)
    mc.execute('''select * from students where
    gender=%s;''',(gender,))
    r = mc.fetchall()
    return jsonify(r)

POST

pyhon
@app.route("/stu/",methods=["POST"])
def add_student():
    data = request.get_json()
    roll_no = data["roll_no"]
    name = data["name"]
    dob = data["dob"]
    gender = data["gender"]
    phone = data["phone"]
    mydb = config.connect()
    mc = mydb.cursor()
    mc.execute('''insert into students values
    (%s,%s,%s,%s,%s);''', (roll_no,name,dob,gender,phone))
    mydb.commit()
    return {"message": "Student added successfully"}
JS
fetch("http://127.0.0.1:5000/stu/", {
    method: "POST",
    headers: {
        "Content-Type": "application/json"
    },
    body: JSON.stringify({
        roll_no: "101",
        name: "Raghu",
        dob: "1995-05-10",
        gender: "M",
        phone: "9876543210"
    })
})
.then(response => response.json())
.then(data => console.log(data));

PUT

pyhon
@app.route("/stu/<roll_no>", methods=["PUT"])
def update_student(roll_no):

    data = request.get_json()

    name = data["name"]
    dob = data["dob"]
    gender = data["gender"]
    phone = data["phone"]

    mydb = config.connect()
    mc = mydb.cursor()

    mc.execute("""
        UPDATE students
        SET name=%s, dob=%s, gender=%s, phone=%s
        WHERE roll_no=%s
    """, (name, dob, gender, phone, roll_no))

    mydb.commit()

    return {"message": "Student updated successfully"}
JS
fetch("http://127.0.0.1:5000/stu/6", {
    method: "PUT",
    headers: {
        "Content-Type": "application/json"
    },
    body: JSON.stringify({
        name: "Raghu Kumar",
        dob: "1995-05-10",
        gender: "M",
        phone: "9876543211"
    })
})
.then(response => response.json())
.then(data => console.log(data));

Delete

pyhon
@app.route("/stu/<int:id>", methods=["DELETE"])
def delete_student(id):
    mydb = config.connect()
    mc = mydb.cursor()

    mc.execute("DELETE FROM students WHERE roll_no=%s", (id,))
    mydb.commit()

    if mc.rowcount == 0:
        return "Student not found", 404

    return "Student deleted successfully"
JS
const id = 101;

fetch(`http://127.0.0.1:5000/stu/${id}`, {
    method: "DELETE"
})
.then(response => response.text())
.then(data => console.log(data))
.catch(error => console.error(error));

Beautiful Soup

Python
import requests
from bs4 import BeautifulSoup

url = "https://www.flipkart.com/search?q=mobiles&otracker=search&otracker1=search&marketplace=FLIPKART&as-show=on&as=off"

headers = {
    "User-Agent": (
        "Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
        "AppleWebKit/537.36 (KHTML, like Gecko) "
        "Chrome/130.0.0.0 Safari/537.36"
    )
}

response = requests.get(
    url,
    headers=headers,
    timeout=15
)

print("Status code:", response.status_code)

if response.status_code == 200:
    soup = BeautifulSoup(response.text, "html.parser")

    # Inspect the returned HTML to identify product containers
    products = soup.select("div[data-id]")

    for product in products:
        name = product.select_one("div.RG5Slk")
        price = product.select_one("div.MKiFS6")
        rating = product.select_one("div.QiMO5r")
        link = product.select_one("a[href]")

        print("Product:", name.get_text(strip=True) if name else "N/A")
        print("Price:", price.get_text(strip=True) if price else "N/A")
        print("Rating:", rating.get_text(strip=True) if rating else "N/A")

        if link:
            print("Link:", "https://www.flipkart.com" + link["href"])

        print("-" * 50)
else:
    print("Request failed or access was restricted.")

Selenium

Selenium
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import Select
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

import time


# -----------------------------------
# 1. Open Chrome
# -----------------------------------

driver = webdriver.Chrome()

driver.maximize_window()

time.sleep(2)


# -----------------------------------
# 2. Open Selenium practice website
# -----------------------------------

driver.get("https://the-internet.herokuapp.com/")

time.sleep(2)


# -----------------------------------
# 3. Go to Inputs page
# -----------------------------------

driver.get("https://the-internet.herokuapp.com/inputs")

time.sleep(2)

print("Opened Inputs page")


# Find the input box
input_box = driver.find_element(By.TAG_NAME, "input")

# Enter a value
input_box.send_keys("12345")

time.sleep(2)

print("Entered value:", input_box.get_attribute("value"))


# -----------------------------------
# 4. Move to Add/Remove Elements
# -----------------------------------

driver.get("https://the-internet.herokuapp.com/add_remove_elements/")

time.sleep(2)

print("Moved to Add/Remove page")


# Click Add Element
add_button = driver.find_element(By.XPATH, "//button[text()='Add Element']")

add_button.click()

time.sleep(2)

print("Clicked Add Element")


# Find Delete button
delete_button = driver.find_element(
    By.XPATH,
    "//button[text()='Delete']"
)

print("Delete button found")


# Click Delete
delete_button.click()

time.sleep(2)

print("Clicked Delete")


# -----------------------------------
# 5. Move to Dropdown page
# -----------------------------------

driver.get("https://the-internet.herokuapp.com/dropdown")

time.sleep(2)

print("Moved to Dropdown page")


# Find dropdown
dropdown = driver.find_element(By.ID, "dropdown")

# Select Option 2
select = Select(dropdown)

select.select_by_visible_text("Option 2")

time.sleep(2)

print("Selected Option 2")


# -----------------------------------
# 6. Move to Dynamic Loading
# -----------------------------------

driver.get(
    "https://the-internet.herokuapp.com/dynamic_loading/2"
)

time.sleep(2)

print("Moved to Dynamic Loading page")


# Click Start
start_button = driver.find_element(
    By.CSS_SELECTOR,
    "#start button"
)

start_button.click()

print("Clicked Start")


# Wait until Hello World appears
message = WebDriverWait(driver, 10).until(
    EC.visibility_of_element_located(
        (By.ID, "finish")
    )
)

print("Dynamic result:", message.text)


# -----------------------------------
# 7. Close browser
# -----------------------------------

time.sleep(3)

driver.quit()

print("Automation completed")

Create Multiple Folders

pyhon
import os

# Folder to store files
folder = "c:\\path"

# Create folder if it does not exist
os.makedirs(folder, exist_ok=True)

# Create 10 files
for i in range(1, 11):
    filename = f"file_{i}.txt"
    filepath = os.path.join(folder, filename)

    with open(filepath, "w") as file:
        file.write(f"This is file number {i}")

    print(filename, "created successfully")

print("All files created!")

Rename Files

pyhon
import os

# Folder containing the files
folder_path = "C:\\path"

# Get all files in the folder
files = os.listdir(folder_path)

for filename in files:
    old_path = os.path.join(folder_path, filename)

    # Skip folders
    if os.path.isfile(old_path):
        new_filename = "Python_" + filename
        new_path = os.path.join(folder_path, new_filename)

        os.rename(old_path, new_path)

        print(filename, "->", new_filename)

print("All files renamed successfully!")

email

pyhon
import smtplib
from email.message import EmailMessage

sender = "your_email"
password = "your_app_password"
receiver = "receiver_email"

message = EmailMessage()
message["From"] = sender
message["To"] = receiver
message["Subject"] = "Python Automation Test"

message.set_content(
    "Hello!\n\n"
    "This email was sent automatically using Python."
)

with smtplib.SMTP_SSL("smtp.gmail.com", 465) as server:
    server.login(sender, password)
    server.send_message(message)

print("Email sent successfully!")

scheduling

pyhon

import schedule
import time
from datetime import datetime

# Task 1: Display a daily reminder
def reminder():
    print("Reminder: Attend your Python class!",
          datetime.now().strftime("%H:%M:%S"))

# Task 2: Generate a report
def generate_report():
    print("Report generated successfully!",
          datetime.now().strftime("%H:%M:%S"))

# Task 3: Back up data
def backup_data():
    print("Data backup completed!",
          datetime.now().strftime("%H:%M:%S"))


# Schedule the tasks at different intervals
schedule.every(1).minutes.do(reminder)
schedule.every(2).minutes.do(generate_report)
schedule.every(3).minutes.do(backup_data)

print("Task scheduler started...")
print("Reminder: Every 1 minute")
print("Report: Every 2 minutes")
print("Backup: Every 3 minutes")
print("Press Ctrl+C to stop.\n")

try:
    while True:
        schedule.run_pending()
        time.sleep(1)

except KeyboardInterrupt:
    print("Scheduler stopped.")