0% found this document useful (0 votes)
5 views32 pages

Python Programming Lab Manual 2023

The document is a laboratory manual for the CSC1292 Python Programming with Web Frameworks course, detailing experiments and evaluation rubrics for students. It includes various programming tasks such as a Student Grades Management System, file reading, and a basic calculator application using Tkinter. The manual outlines specific objectives, algorithms, and sample code for each experiment, along with grading criteria for performance assessment.

Uploaded by

k99790177
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views32 pages

Python Programming Lab Manual 2023

The document is a laboratory manual for the CSC1292 Python Programming with Web Frameworks course, detailing experiments and evaluation rubrics for students. It includes various programming tasks such as a Student Grades Management System, file reading, and a basic calculator application using Tkinter. The manual outlines specific objectives, algorithms, and sample code for each experiment, along with grading criteria for performance assessment.

Uploaded by

k99790177
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

LABORATORY MANUAL
REGULATION 2023

CSC1292 – PYTHON PROGRAMMING WITH WEB


FRAMEWORKS LABORATORY

Prepared by, ​ ​ ​ ​ ​ ​ ​ ​ Approved by,


Mrs. I. Karthika AP/CSE ​ ​ ​ ​ ​ Dr. D. Pradeep
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
ACADEMIC YEAR- (2025-2026)-​ EVEN SEMESTER
II YEAR /IV SEM (BATCH 2024-2028)
CSC1292 – PYTHON PROGRAMMING WITH WEB FRAMEWORKS
LABORATORY

Lab Rubrics
Parameters of Maximum
[Link] Proficient Adequate Unacceptable
Evaluation Marks
Demonstrate the
Demonstrate the Not able to
Ability to Identify
Problem Ability to Identify identify the
1 5 the problem with
Recognition the problem. problem.
some assistance.
(5-4) (1-0)
(3-2)
The lab is mostly
The lab is complete
complete and The lab in its
and accurate in the
Completeness accurate in the current state is
2 5 context of
and Accuracy context of some not implementable.
implementation
implementation. (1-0)
(5-4)
(3-2)
The Experiment is The Experiment is
The Experiment is
implemented using not implemented
Coding implemented using
3 5 some coding using any coding
standards coding standards.
standards. standards.
(5-4)
(3-2) (1-0)
The student
The student
answered all viva The student did not
answered few viva
questions asked and answered any viva
4 Viva-voce 10 questions asked
the answer is questions asked
and Partial answers
Perfect (2-0)
(5-3)
(10-6)

Faculty Incharge ​​ ​ DCC Head​ ​ ​ ​ HOD- CSE


CSC1292 - PYTHON PROGRAMMING WITH WEB FRAMEWORKS

TABLE OF CONTENTS

Experiment
ExperimentTitle CO Page no
No.

1 Student Grades Management System using Python CO1 2

2 File Reading Using Manual Iteration in Python CO1 5

Shopping Cart Using Optional Arguments in


3 CO2 7
Python

Performance Comparison of Recursive and Iterative


4 CO2 9
Factorial in Python

5 BankAccount Class Implementation in Python CO3 11

Demonstration of Static and Class Methods in


6 CO3 13
Python

7 Basic Calculator Application Using Tkinter CO4 15

8 Student Registration Form Using Tkinter Widgets CO4 18

9 Demonstration of MVC Architecture Using Django CO5 21

Implementation of User Feedback Collection Using


10 CO5 24
Django Forms

Content Beyond Syllabus


11 Development of a RESTful Web Service Using Django CO5 28
REST Framework

1
CSC1292 - PYTHON PROGRAMMING WITH WEB FRAMEWORKS

Experiment 1
Student Grades Management System using Python
Aim
To design and implement a Python program to manage student grades by adding, updating,
displaying grades, and calculating the class average.

Algorithm
Step 1: Start the program.​
Step 2: Create an empty dictionary to store student names and grades.​
Step 3: Display the menu options to the user.​
Step 4: Read the user’s choice.​
Step 5:
●​ If choice is Add, read student name and grade and store them.
●​ If choice is Update, modify the grade of the existing student.
●​ If choice is Display, show all student names and grades.
●​ If choice is Average, calculate and display the average grade.
Step 6: Repeat steps 3–5 until the user selects Exit.​
Step 7: Stop the program

Program :
# Student Grades Management System
students = {} # Dictionary to store student names and grades
while True:
print("\n--- Student Grades Management System ---")
print("1. Add Student and Grade")
print("2. Update Student Grade")
print("3. Display All Students and Grades")
print("4. Calculate Average Grade")
print("5. Exit")
choice = int(input("Enter your choice: "))
# a. Add student name and grade
if choice == 1:

2
CSC1292 - PYTHON PROGRAMMING WITH WEB FRAMEWORKS

name = input("Enter student name: ")


grade = float(input("Enter grade: "))
students[name] = grade
print("Student added successfully.")
# b. Update grade for existing student
elif choice == 2:
name = input("Enter student name to update: ")
if name in students:
grade = float(input("Enter new grade: "))
students[name] = grade
print("Grade updated successfully.")
else:
print("Student not found.")
# c. Display all students and grades
elif choice == 3:
if not students:
print("No students available.")
else:
print("\nStudent Name\tGrade")
for name, grade in [Link]():
print(name, "\t\t", grade)
# d. Calculate average grade
elif choice == 4:
if not students:
print("No students available to calculate average.")
else:
total = sum([Link]())
average = total / len(students)
print("Average Grade of the Class:", average)
# Exit
elif choice == 5:
print("Exiting program...")
break

3
CSC1292 - PYTHON PROGRAMMING WITH WEB FRAMEWORKS

else:
print("Invalid choice. Please try again.")

Result
Thus, the Python program for the Student Grades Management System was
executed successfully

4
CSC1292 - PYTHON PROGRAMMING WITH WEB FRAMEWORKS

Experiment 2
File Reading Using Manual Iteration in Python
Aim
To develop a Python program to read lines from a text file using manual iteration and
generate a list of even numbers within a user-specified range using list comprehension.

Algorithm
Step 1: Start the program.​
Step 2: Open the specified text file in read mode.​
Step 3: Read and display each line from the file using manual iteration.​
Step 4: Close the file after reading.​
Step 5: Read the starting and ending values from the user.​
Step 6: Generate a list of even numbers within the given range using list
comprehension.​
Step 7: Display the list of even numbers.​
Step 8: Stop the program.

Program:
# Program to read lines from a file using manual iteration
# and generate even numbers using list comprehension
try:
# a. Open a specified text file
file = open("[Link]", "r")
print("Contents of the file:\n")

# b. Read and print each line using manual iteration


for line in file:
print([Link]())
[Link]() # e. Properly close the file
except FileNotFoundError:
print("File not found. Please check the file name.")

5
CSC1292 - PYTHON PROGRAMMING WITH WEB FRAMEWORKS

# b (continued): Get range of numbers from user


start = int(input("\nEnter starting value: "))
end = int(input("Enter ending value: "))

# c. Generate list of even numbers using list comprehension


even_numbers = [num for num in range(start, end + 1) if num % 2 == 0]
# d. Display the even numbers
print("\nList of even numbers:", even_numbers)

Output
Contents of the file:
Hello World
Python Programming
File Handling

Enter starting value: 1


Enter ending value: 10

List of even numbers: [2, 4, 6, 8, 10]

Result
Thus, the Python program to read lines from a file using manual iteration and generate
even numbers using list comprehension was successfully executed.

6
CSC1292 - PYTHON PROGRAMMING WITH WEB FRAMEWORKS

Experiment 3
Shopping Cart Using Optional Arguments in Python
Aim
To create a Python function that adds items to a shopping cart with optional
arguments for quantity and displays the items with their quantities.

Algorithm
Step 1: Start the program.​
Step 2: Initialize an empty dictionary to represent the shopping cart.​
Step 3: Define a function to add items to the cart with an optional quantity parameter.​
Step 4: Call the function to add items to the cart.​
Step 5: Display all items and their quantities in the shopping cart.​
Step 6: Stop the program.

Program:
# Shopping Cart Program

cart = {}
# a & b. Function to add items with optional quantity
def add_item(item_name, quantity=1):
if item_name in cart:
cart[item_name] += quantity
else:
cart[item_name] = quantity
# Adding items to the cart
add_item("Pen", 5)
add_item("Notebook")
add_item("Pencil", 3)
# c. Display items and quantities
print("Shopping Cart Items:")
for item, qty in [Link]():
print(item, ":", qty)

7
CSC1292 - PYTHON PROGRAMMING WITH WEB FRAMEWORKS

Output
Shopping Cart Items:
Pen : 5
Notebook : 1
Pencil : 3

Result
Thus, the Python program to add items to a shopping cart using a function with
optional arguments was successfully executed

8
CSC1292 - PYTHON PROGRAMMING WITH WEB FRAMEWORKS

Experiment 4
Performance Comparison of Recursive and Iterative Factorial in Python

Aim
To develop a Python program to compare the performance of recursive and iterative
implementations of the factorial function using time benchmarking.

Algorithm
Step 1: Start the program.​
Step 2: Define a recursive function to compute the factorial of a number.​
Step 3: Define an iterative function to compute the factorial of a number.​
Step 4: Read the input number from the user.​
Step 5: Measure and record the execution time of the recursive factorial function.​
Step 6: Measure and record the execution time of the iterative factorial function.​
Step 7: Display the factorial result and time taken by both implementations.​
Step 8: Stop the program.

Program:
import time
# a. Recursive factorial function
def fact_recursive(n):
if n == 0 or n == 1:
return 1
return n * fact_recursive(n - 1)
# a. Iterative factorial function
def fact_iterative(n):
result = 1
for i in range(1, n + 1):
result *= i
return result
# Input
n = int(input("Enter a number: "))

9
CSC1292 - PYTHON PROGRAMMING WITH WEB FRAMEWORKS

# b & c. Measure time for recursive approach


start_time = [Link]()
rec_result = fact_recursive(n)
rec_time = [Link]() - start_time
# b & c. Measure time for iterative approach
start_time = [Link]()
iter_result = fact_iterative(n)
iter_time = [Link]() - start_time
# Display results
print("\nFactorial of", n)
print("Recursive Result:", rec_result)
print("Time taken (Recursive):", rec_time, "seconds")
print("\nIterative Result:", iter_result)
print("Time taken (Iterative):", iter_time, "seconds")

Output
Enter a number: 10
Factorial of 10
Recursive Result: 3628800
Time taken (Recursive): 0.000012 seconds
Iterative Result: 3628800
Time taken (Iterative): 0.000005 seconds

Result
Thus, the Python program successfully compared the execution time of recursive and
iterative factorial implementations, and the performance of both methods was displayed.

10
CSC1292 - PYTHON PROGRAMMING WITH WEB FRAMEWORKS

Experiment 5
BankAccount Class Implementation in Python
Aim
To develop a Python program using a BankAccount class that allows users to deposit
money, withdraw money, and check the current account balance.

Algorithm
Step 1: Start the program.​
Step 2: Define a BankAccount class with an initial balance.​
Step 3: Create methods to deposit amount into the account.​
Step 4: Create methods to withdraw amount from the account.​
Step 5: Create a method to display the current account balance.​
Step 6: Create an object of the BankAccount class.​
Step 7: Perform deposit, withdrawal, and balance check operations.​
Step 8: Stop the program.

Program:
# BankAccount class implementation
class BankAccount:
def __init__(self, balance=0):
[Link] = balance
# a. Deposit method
def deposit(self, amount):
if amount > 0:
[Link] += amount
print("Amount deposited:", amount)
else:
print("Invalid deposit amount")
# b. Withdraw method
def withdraw(self, amount):
if amount <= [Link] and amount > 0:
[Link] -= amount
print("Amount withdrawn:", amount)

11
CSC1292 - PYTHON PROGRAMMING WITH WEB FRAMEWORKS

else:
print("Insufficient balance or invalid amount")
# c. Check balance method
def check_balance(self):
print("Current Balance:", [Link])
# Creating an account object
account = BankAccount(1000)
# Performing operations
[Link](500)
[Link](300)
account.check_balance()
Output
Amount deposited: 500
Amount withdrawn: 300
Current Balance: 1200

Result
Thus, the Python program implementing the BankAccount class was successfully
executed, allowing deposit, withdrawal, and balance inquiry operations.

12
CSC1292 - PYTHON PROGRAMMING WITH WEB FRAMEWORKS

Experiment 6
Demonstration of Static and Class Methods in Python

Aim
To develop a Python program that demonstrates the use of static methods and class
methods and highlights their differences.

Algorithm
Step 1: Start the program.​
Step 2: Define a class with a class-level variable.​
Step 3: Create a static method to perform a utility operation.​
Step 4: Create a class method to modify the class-level variable.​
Step 5: Call the static method using the class name.​
Step 6: Call the class method to update class-level data.​
Step 7: Display the results.​
Step 8: Stop the program.

Program:
class Student:
college_name = "Green Valley Engineering College" # Class-level data
def __init__(self, name):
[Link] = name
# a. Static method (utility function)
@staticmethod
def is_valid_age(age):
return age >= 18
# b. Class method (modifies class-level data)
@classmethod
def change_college(cls, new_name):
cls.college_name = new_name
# Using static method
print("Is age 20 valid?", Student.is_valid_age(20))
# Using class method

13
CSC1292 - PYTHON PROGRAMMING WITH WEB FRAMEWORKS

print("College before change:", Student.college_name)


Student.change_college("Sunrise Institute of Technology")
print("College after change:", Student.college_name)

Output
Is age 20 valid? True
College before change: GreenValley Engineering College
College after change: Sunrise Institute of Technology

Result
Thus, the Python program successfully demonstrated the usage and differences
between static methods and class methods.

14
CSC1292 - PYTHON PROGRAMMING WITH WEB FRAMEWORKS

Experiment 7
Basic Calculator Application Using Tkinter
Aim
To develop a basic calculator application using Python Tkinter to perform simple
arithmetic operations through a graphical user interface.

Algorithm
Step 1: Start the program.​
Step 2: Import the Tkinter module.​
Step 3: Create the main application window.​
Step 4: Create an entry field to display input and results.​
Step 5: Create buttons for digits and arithmetic operations.​
Step 6: Define functions to handle button clicks, evaluate expressions, and clear
input.​
Step 7: Arrange all widgets using a grid layout.​
Step 8: Run the Tkinter main loop.​
Step 9: Stop the program.

Program:
import tkinter as tk
# Function to update expression
def press(key):
entry_var.set(entry_var.get() + str(key))
# Function to evaluate expression
def equal():
try:
result = eval(entry_var.get())
entry_var.set(str(result))
except:
entry_var.set("Error")
# Function to clear entry
def clear():
entry_var.set("")
# Create main window

15
CSC1292 - PYTHON PROGRAMMING WITH WEB FRAMEWORKS

root = [Link]()
[Link]("Basic Calculator")
entry_var = [Link]()
# Entry widget
entry = [Link](root, textvariable=entry_var, font=("Arial", 18), bd=5, relief="ridge",
justify="right")
[Link](row=0, column=0, columnspan=4)
# Buttons
buttons = [
'7', '8', '9', '/',
'4', '5', '6', '*',
'1', '2', '3', '-',
'0', '.', '=', '+'
]
row = 1
col = 0
for btn in buttons:
if btn == '=':
[Link](root, text=btn, width=10, height=2, command=equal).grid(row=row,
column=col, columnspan=2)
col += 1
else:
[Link](root, text=btn, width=5, height=2, command=lambda x=btn:
press(x)).grid(row=row, column=col)
col += 1
if col > 3:
col = 0
row += 1
# Clear button
[Link](root, text="C", width=10, height=2, command=clear).grid(row=row, column=0,
columnspan=4)
# Run application
[Link]()

16
CSC1292 - PYTHON PROGRAMMING WITH WEB FRAMEWORKS

Output:

Result
Thus, the basic calculator using Tkinter was successfully developed and executed,
enabling users to perform simple arithmetic operations through a graphical user interface.

17
CSC1292 - PYTHON PROGRAMMING WITH WEB FRAMEWORKS

Experiment 8
Student Registration Form Using Tkinter Widgets
Aim
To develop a Student Registration Form using Python Tkinter widgets for collecting
and displaying student details.

Algorithm
Step 1: Start the program.​
Step 2: Import the Tkinter module.​
Step 3: Create the main application window.​
Step 4: Create labels and entry widgets for student details.​
Step 5: Create radio buttons for gender selection.​
Step 6: Create a drop-down list for course selection.​
Step 7: Create a submit button to display the entered details.​
Step 8: Run the Tkinter main loop.​
Step 9: Stop the program.

Program:
import tkinter as tk
from tkinter import messagebox

# Function to display submitted details


def submit():
name = entry_name.get()
roll = entry_roll.get()
gender = gender_var.get()
course = course_var.get()

[Link](
"Registration Successful",
f"Name: {name}\nRoll No: {roll}\nGender: {gender}\nCourse: {course}"
)

18
CSC1292 - PYTHON PROGRAMMING WITH WEB FRAMEWORKS

# Main window
root = [Link]()
[Link]("Student Registration Form")
[Link]("400x300")

# Labels and Entry widgets


[Link](root, text="Student Registration Form", font=("Arial", 14)).pack(pady=10)

[Link](root, text="Name").pack()
entry_name = [Link](root)
entry_name.pack()

[Link](root, text="Roll Number").pack()


entry_roll = [Link](root)
entry_roll.pack()

# Gender (Radio Buttons)


[Link](root, text="Gender").pack()
gender_var = [Link]()
[Link](root, text="Male", variable=gender_var, value="Male").pack()
[Link](root, text="Female", variable=gender_var, value="Female").pack()

# Course (Dropdown)
[Link](root, text="Course").pack()
course_var = [Link]()
course_var.set("CSE")
[Link](root, course_var, "CSE", "IT", "ECE", "EEE").pack()

# Submit Button
[Link](root, text="Submit", command=submit).pack(pady=10)

# Run application
[Link]()

19
CSC1292 - PYTHON PROGRAMMING WITH WEB FRAMEWORKS

Output:

Result
Thus, the Student Registration Form using Tkinter widgets was successfully
developed and executed, allowing users to enter and submit student details through a
graphical interface.

20
CSC1292 - PYTHON PROGRAMMING WITH WEB FRAMEWORKS

Experiment 9
Demonstration of MVC Architecture Using Django

Aim
To create a simple Django project to demonstrate the MVC (Model–View–Controller)
design pattern by defining a model, creating views, implementing URL routing, and
rendering HTML content using templates.

Algorithm
Step 1: Create a new Django project and an application.​
Step 2: Define a model to represent the database table.​
Step 3: Create a view to process user requests and fetch data from the model.​
Step 4: Configure URL routing to map URLs to the corresponding view.​
Step 5: Design an HTML template to display data dynamically.​
Step 6: Run the Django server and access the webpage through a browser.​
Step 7: Stop the program.

Program:
Step 1: Create Django Project and App
django-admin startproject studentproject
cd studentproject
python [Link] startapp studentapp
Add studentapp to INSTALLED_APPS in [Link].

a. Model ([Link])
Model represents the database table
from [Link] import models
class Student([Link]):
name = [Link](max_length=50)
roll_no = [Link]()
def __str__(self):
return [Link]

21
CSC1292 - PYTHON PROGRAMMING WITH WEB FRAMEWORKS

Run:
python [Link] makemigrations
python [Link] migrate

b. View ([Link])
View handles user request and response
from [Link] import render
from .models import Student
def student_list(request):
students = [Link]()
return render(request, '[Link]', {'students': students})

c. URL Routing ([Link])


App-level URL (studentapp/[Link])
from [Link] import path
from . import views
urlpatterns = [
path('', views.student_list, name='student_list'),
]
Project-level URL (studentproject/[Link])
from [Link] import admin
from [Link] import path, include
urlpatterns = [
path('admin/', [Link]),
path('students/', include('[Link]')),
]

d. Template ([Link])
Create folder:​
studentapp/templates/[Link]
<!DOCTYPE html>
<html>
<head>

22
CSC1292 - PYTHON PROGRAMMING WITH WEB FRAMEWORKS

<title>Student List</title>
</head>
<body>
<h2>Student Details</h2>
<ul>
{% for student in students %}
<li>{{ [Link] }} - {{ student.roll_no }}</li>
{% endfor %}
</ul>
</body>
</html>

Output
When the user opens:
[Link]
➡️A web page displaying the list of students is shown.

Result
Thus, a simple Django project demonstrating the MVC (MVT) design pattern was
successfully implemented, and dynamic web content was rendered using models, views,
URLs, and templates.

23
CSC1292 - PYTHON PROGRAMMING WITH WEB FRAMEWORKS

Experiment 10
Implementation of User Feedback Collection Using Django Forms
Aim
To develop a Django form for collecting and validating user feedback and to handle
form submissions through a web interface.
Algorithm
Step 1: Create a Django project and an application.​
Step 2: Define a model with fields for name, email, and feedback message.​
Step 3: Create a Django form to collect and validate user input.​
Step 4: Develop a view to display the form and process submissions.​
Step 5: Configure URL routing to link the form page to the view.​
Step 6: Design HTML templates for the feedback form and success page.​
Step 7: Run the server and submit feedback through the web page.​
Step 8: Stop the program.

Program:
Program: Django Feedback Form
Step 1: Create Project and App
django-admin startproject feedbackproject
cd feedbackproject
python [Link] startapp feedbackapp
Add feedbackapp to INSTALLED_APPS in [Link].
a. Model ([Link])
Defines database table for feedback
from [Link] import models

class Feedback([Link]):
name = [Link](max_length=50)
email = [Link]()
message = [Link]()

def __str__(self):
return [Link]

24
CSC1292 - PYTHON PROGRAMMING WITH WEB FRAMEWORKS

Run migrations:
python [Link] makemigrations
python [Link] migrate
b. Form with Validation ([Link])
from django import forms
from .models import Feedback

class FeedbackForm([Link]):
class Meta:
model = Feedback
fields = ['name', 'email', 'message']
✔️Django automatically validates that all fields are filled.
c. View ([Link])
Handles form display and submission
from [Link] import render
from .forms import FeedbackForm

def feedback_view(request):
if [Link] == 'POST':
form = FeedbackForm([Link])
if form.is_valid():
[Link]()
return render(request, '[Link]')
else:
form = FeedbackForm()

return render(request, '[Link]', {'form': form})


d. URL Routing
App-level URL (feedbackapp/[Link])
from [Link] import path
from .views import feedback_view
urlpatterns = [
path('', feedback_view, name='feedback'),

25
CSC1292 - PYTHON PROGRAMMING WITH WEB FRAMEWORKS

]
Project-level URL (feedbackproject/[Link])
from [Link] import admin
from [Link] import path, include

urlpatterns = [
path('admin/', [Link]),
path('feedback/', include('[Link]')),
]
e. Templates
[Link]
<!DOCTYPE html>
<html>
<head>
<title>Feedback Form</title>
</head>
<body>
<h2>User Feedback</h2>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Submit</button>
</form>
</body>
</html>
[Link]
<!DOCTYPE html>
<html>
<head>
<title>Success</title>
</head>
<body>
<h3>Thank you for your feedback!</h3>

26
CSC1292 - PYTHON PROGRAMMING WITH WEB FRAMEWORKS

</body>
</html>
Output:

Result
Thus, the Django feedback form was successfully developed and executed, allowing
users to submit validated feedback through a web interface.

27
CSC1292 - PYTHON PROGRAMMING WITH WEB FRAMEWORKS

Content beyond syllabus


Development of a RESTful Web Service Using Django REST Framework

Aim

To develop a simple RESTful API using Django REST Framework to perform CRUD
operations and return data in JSON format.

Algorithm:
Step 1: Create a new Django project and application.
Step 2: Install Django REST Framework and add it to INSTALLED_APPS.
Step 3: Define a model to store student details in the database.
Step 4: Run migrations to create the database table.
Step 5: Create a serializer to convert model objects into JSON format.
Step 6: Develop API views to handle HTTP GET and POST requests.
Step 7: Configure URL routing to map API endpoints to the views.
Step 8: Run the Django development server.
Step 9: Access the API using a browser or API testing tool and verify the output.
Step 10: Stop the program

Program
Step 1: Install DRF
pip install djangorestframework
Add to INSTALLED_APPS:
'rest_framework',

Step 2: Model ([Link])


from [Link] import models

class Student([Link]):
name = [Link](max_length=50)
marks = [Link]()

def __str__(self):
return [Link]
Run:
python [Link] makemigrations

28
CSC1292 - PYTHON PROGRAMMING WITH WEB FRAMEWORKS

python [Link] migrate

Step 3: Serializer ([Link])


from rest_framework import serializers
from .models import Student

class StudentSerializer([Link]):
class Meta:
model = Student
fields = '__all__'

Step 4: API View ([Link])


from rest_framework.decorators import api_view
from rest_framework.response import Response
from .models import Student
from .serializers import StudentSerializer

@api_view(['GET', 'POST'])
def student_api(request):
if [Link] == 'GET':
students = [Link]()
serializer = StudentSerializer(students, many=True)
return Response([Link])

if [Link] == 'POST':
serializer = StudentSerializer(data=[Link])
if serializer.is_valid():
[Link]()
return Response([Link])

Step 5: URL Configuration ([Link])


from [Link] import path
from .views import student_api

urlpatterns = [
path('api/students/', student_api),
]

Output
GET Request (Browser):
[Link]
[
{
"id": 1,
"name": "Karthik",

29
CSC1292 - PYTHON PROGRAMMING WITH WEB FRAMEWORKS

"marks": 85
}
]
POST Request (JSON Input):
{
"name": "Anu",
"marks": 90
}

Output
When the Django development server is running and the API URL is accessed:
URL:
[Link]
GET Request Output (JSON Response):
[
{
"id": 1,
"name": "Arun",
"marks": 88
},
{
"id": 2,
"name": "Divya",
"marks": 92
}
]
POST Request Input (JSON):
{
"name": "Karthik",
"marks": 85
}
POST Request Output (JSON Response):
{
"id": 3,
"name": "Karthik",
"marks": 85
}

Result
Thus, a Django REST API was successfully developed using Django REST
Framework to exchange data in JSON format, which is beyond the basic Django syllabus.

30

You might also like