Python 36
Introduction to Jinja2
Jinja2 is a template engine for python, mainly used with Flask(and also Django-like systems)
It allows us to
write HTML + Python logic
Display dynamic data
Use loops, conditions variables
Jinja2 gives (Clear,Reusable,Professional)
Browser understand only HTML, Python generate data,Jinja2 combines both.
Without Jinj2(Bad practice)
@app.route("/")
def home():
return "<h1>Welcome Naga</h1>
With Jinja2(Best practice)
@app.route("/")
def home():
return render_template("Index.html",name="naga")
<h1>welcome {{name}}</h1>
Create template with Jinja2
Connecting Flask to database and displaying records
Examples :
Task1:
app.py
from flask import Flask,render_template
app = Flask(__name__)
@app.route('/')
def home():
return render_template('index.html', name=
"Subbu" , age=15)
if __name__=='__main__':
app.run(debug=True)
templates>index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title> </head>
<body>
{% if age >= 18 %}
<h1>You are eligible to vote:{{name}} {{age}}</h1>
{% else %}
<h1>You are not eligible to vote:{{name}} {{age}}</h1>
{% endif %}
</body>
</html>
You are not eligible to vote:Subbu 15
Task2:
List
app.py
from flask import Flask,render_template
app = Flask(__name__)
@app.route('/')
def home():
std = ["Raja", "Subbu", "Pavan","Kumar","Ajay"]
return render_template('index.html', students=std)
if __name__=='__main__':
app.run(debug=True)
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title> </head>
<body>
<ul>
{% for stdind in students %}
<li>{{stdind}}</li>
{% endfor %}
</ul>
</body>
</html>
- Raja
- Subbu
- Pavan
- Kumar
- Ajay
Task3: Display Table format
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<table border="1">
<tr>
<th>Student Name</th>
<th>Age</th>
<th>Marks</th>
</tr>
{% for name, age,mark in student_data %}
<tr>
<td>{{ name }}</td>
<td>{{ age }}</td>
<td>{{ mark }}</td>
</tr>
{% endfor %}
</table>
</body>
</html>
app.py
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def home():
std = ["Raja", "Subbu", "Pavan", "Kumar", "Ajay"]
ag = [23, 24, 22, 25, 23]
marks = [85, 90, 78, 88, 92]
# Combine lists into list of tuples
student_data = list(zip(std, ag, marks))
return render_template('index.html', student_data=student_data)
if __name__ == '__main__':
app.run(debug=True)
used zip function combine multiple iterables (like lists, tuples, etc.) element-wise. It creates an iterator that aggregates
elements from each of the iterables.
Output:
| Student Name | Age | Marks |
|---|---|---|
| Raja | 23 | 85 |
| Subbu | 24 | 90 |
| Pavan | 22 | 78 |
| Kumar | 25 | 88 |
| Ajay | 23 | 92 |
Task4: Template inheritance
base.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Cloud Computing In Telugu</title>
<link rel="stylesheet" href="{{url_for('static',filename='css/style.css') }}">
</head>
<body>
<nav >
<ul class="menu">
<li><a href = "/">Home</a></li>
<li><a href="/registration">Student Registration</a></li>
<li><a href="/courses"> Courses</a></li>
</ul>
</nav>
<!-- Header Section -->
<header>
<h1>Cloud Computing In Telugu</h1>
<section>
<p>Learn how websites are built from scratch</p>
</header>
<!-- Main Content -->
<main>
{% block content %}
{% endblock %}
</main>
<!-- Footer -->
<footer>
<p>Regards,</p>
<p>
<a href="https://www.cloudcomputingintelugu.com" target="_blank">
Cloud Computing In Telugu
</a>
</p>
</footer>
</body>
</html>
index.html
{% extends "base.html" %}
{% block content %}
<!-- Introduction -->
<section id="sec1">
<p>
In this training, you will learn how websites are created from scratch.
This course is designed for beginners with no prior technical background.
</p>
<p>
Web development is the process of building and maintaining websites.
It involves designing the structure, styling the appearance, and adding interactivity.
</p>
</section>
<!-- Topics Covered -->
<section id="sec2">
<h2>Topics Covered in This Training</h2>
<ul>
<li>HTML fundamentals</li>
<li>Page structure and elements</li>
<li>Text formatting and links</li>
<li>Images, lists, and tables</li>
<li>Forms and user input</li>
<li>Introduction to CSS</li>
<li>Basics of JavaScript</li>
<li>Pythin full-stack development</li>
</ul>
</section>
<!-- Technologies Overview -->
<section>
<p>
HTML is responsible for creating the structure of a web page.
CSS is used to make the web page look attractive.
JavaScript adds interactivity and dynamic behavior.
</p>
</section>
<!-- Outcomes -->
<section id="sec3">
<h2>After Completing This Training, You Will Be Able To</h2>
<ul>
<li>Create simple and well-structured web pages</li>
<li>Understand and read existing website code</li>
<li>Apply basic styling using CSS</li>
<li>Add simple interactions using JavaScript</li>
<li>Build a strong foundation for frontend development</li>
</ul>
</section>
<!-- Audience -->
<section id="sec4">
<p>
This training is suitable for students, beginners, and working professionals.
Anyone interested in building websites or starting a career in web development can join.
</p>
</section>
{% endblock %}
student.html
{% extends "base.html" %}
{% block content %}
<form method="post">
<table>
<tr><td><label>Student Name: </label></td><td><input type ="text" name="name"></td></tr>
<tr><td><label>Course: </label></td><td><input type ="text" name="course"></td></tr>
<tr><td><label>Email Id: </label></td><td><input type ="email" name="email"></td></tr>
<tr style="text-align: center;"><td colspan="2"><button type="submit">Submit</button></td></tr>
</table>
<h1>{{msg}}</h1>
<table>
<tr>
<th>Student Id</th>
<th>Student Name</th>
<th>Course Selected</th>
<th>Email Id</th>
</tr>
{% for student in std %}
<tr>
<td>{{student.id}}</td>
<td>{{student.name}}</td>
<td>{{student.course}}</td>
<td>{{student.email}}</td>
</tr>
{% endfor %}
</table>
</form>
{% endblock %}
index.html
{% extends "base.html" %}
{% block content %}
<!-- Introduction -->
<section id="sec1">
<p>
In this training, you will learn how websites are created from scratch.
This course is designed for beginners with no prior technical background.
</p>
<p>
Web development is the process of building and maintaining websites.
It involves designing the structure, styling the appearance, and adding interactivity.
</p>
</section>
<!-- Topics Covered -->
<section id="sec2">
<h2>Topics Covered in This Training</h2>
<ul>
<li>HTML fundamentals</li>
<li>Page structure and elements</li>
<li>Text formatting and links</li>
<li>Images, lists, and tables</li>
<li>Forms and user input</li>
<li>Introduction to CSS</li>
<li>Basics of JavaScript</li>
<li>Pythin full-stack development</li>
</ul>
</section>
<!-- Technologies Overview -->
<section>
<p>
HTML is responsible for creating the structure of a web page.
CSS is used to make the web page look attractive.
JavaScript adds interactivity and dynamic behavior.
</p>
</section>
<!-- Outcomes -->
<section id="sec3">
<h2>After Completing This Training, You Will Be Able To</h2>
<ul>
<li>Create simple and well-structured web pages</li>
<li>Understand and read existing website code</li>
<li>Apply basic styling using CSS</li>
<li>Add simple interactions using JavaScript</li>
<li>Build a strong foundation for frontend development</li>
</ul>
</section>
<!-- Audience -->
<section id="sec4">
<p>
This training is suitable for students, beginners, and working professionals.
Anyone interested in building websites or starting a career in web development can join.
</p>
</section>
{% endblock %}
static>css>style.css
body{
font-family: Arial, sans-serif;
line-height: 1.6;
background-color: #f4f6f8;
margin:0;
padding: 20px;
}
main{
width:80%;
margin:30px;
padding: 25px;
background-color: white;
border-radius: 6px;
}
header{
background-color: #2c3e50;
color: white;
padding:20px;
text-align:center;
}
section{
margin-bottom:25px
}
h2{
color:#2c3e50;
border-bottom: 2px solid #ddd ;
padding-bottom: 5px;
}
ul{
margin-left: 20px;
}
footer{
text-align: center;
padding: 15px;
background-color: #2c3e50;
color:white
}
footer a{
color: #ffd700;
text-decoration: none;
}
/* Menu bar */
nav{
background-color: #2c3e50;
}
.menu{
list-style: none;
margin: 0;
padding: 0;
display: flex;
}
.menu li{
margin: 0;
}
.menu li a{
display: block;
padding: 14px 20px;
color: white;
text-decoration: none;
font-weight: bold;
}
.menu li a{
display: block;
padding: 14px 20px;
color: white;
text-decoration: none;
font-weight: bold;
}
.menu li a:hover{
background-color: #1a252f;
}
button {
height: 50px;
width: 250px;
padding: 10px 20px;
margin: 8px;
background-color: #2563eb; /* Blue */
color: white;
border: none;
border-radius: 8px;
font-family: Arial, Helvetica, sans-serif;
font-size: 16px;
font-weight: 500;
cursor: pointer;
transition: all 0.3s ease;
}
table {
border-collapse: collapse;
width: 70%;
}
th, td {
border: 1px solid black;
padding: 8px;
text-align: center;
}
th {
background-color: #f2f2f2;
}
app.py
# pip install pymysql
from flask import Flask,render_template, request
app=Flask(__name__)
@app.route("/")
def home():
return render_template("index.html")
@app.route("/registration",methods=["GET", "POST"])
def student():
return render_template("student.html")
@app.route("/courses")
def courses():
return render_template("courses.html")
if __name__=="__main__":
app.run(debug=True)
courses.html
{% extends "base.html" %}
{% block content %}
<form>
<ul>
<li>AWS</li>
<li>Azure</li>
<li>GCP</li>
<li>DevOps</li>
</ul>
</form>
</body>
</html>
{% endblock %}
Output
Task 5:
Get and Post student details using database
Install: pip install pymysql for db connection
app.py
# pip install pymysql
from flask import Flask,render_template, request
import pymysql
def dbconnection():
conn=pymysql.connect(host="Localhost",user="ccitsource",password="SourcePassword123!",database="ccitdbsource")
return conn
app=Flask(__name__)
@app.route("/")
def home():
return render_template("index.html")
@app.route("/registration",methods=["GET", "POST"])
def student():
message="Get method called"
if request.method=="POST":
name=request.form.get("name")
course=request.form.get("course")
email=request.form.get("email")
message="Post method called"
conn=dbconnection()
cursor=conn.cursor()
sql="insert into student(std_name,course,email_id) values(%s,%s,%s)"
cursor.execute(sql,(name,course,email))
conn.commit()
cursor.close()
conn.close()
message="Student Registered Successfully"
# GET the student details
conn=dbconnection()
cursor=conn.cursor(pymysql.cursors.DictCursor)
sql="select std_name,course,email_id from student"
cursor.execute(sql)
student=cursor.fetchall()
cursor.close()
conn.close()
return render_template("student.html", msg=message, std=student)
@app.route("/courses")
def courses():
return render_template("courses.html")
if __name__=="__main__":
app.run(debug=True)
index.html
--Same as above task4
base.html
--Same as above task4
style.css
--Same as above task4
student.html
{% extends "base.html" %}
{% block content %}
<form method="post">
<table>
<tr><td><label>Student Name: </label></td><td><input type ="text" name="name"></td></tr>
<tr><td><label>Course: </label></td><td><input type ="text" name="course"></td></tr>
<tr><td><label>Email Id: </label></td><td><input type ="email" name="email"></td></tr>
<tr style="text-align: center;"><td colspan="2"><button type="submit">Submit</button></td></tr>
</table>
<h1>{{msg}}</h1>
<table>
<tr>
<th>Student Name</th>
<th>Course Selected</th>
<th>Email Id</th>
</tr>
{% for student in std %}
<tr>
<td>{{student.std_name}}</td>
<td>{{student.course}}</td>
<td>{{student.email_id}}</td>
</tr>
{% endfor %}
</table>
</form>
{% endblock %}
Mysql:
create table ccitdbsource.student(
std_name varchar(100),
mobile decimal(20),
course varchar(100),
email_id varchar(100));
Ouput:
Student.html
{% extends "base.html" %}
{% block content %}
<form method="post" action="/registration">
<table>
<tr><td><label>Student Name: </label></td><td><input type ="text" name="name"></td></tr>
<tr><td><label>Course: </label></td><td><input type ="text" name="course"></td></tr>
<tr><td><label>Email Id: </label></td><td><input type ="email" name="email"></td></tr>
<tr style="text-align: center;"><td colspan="2"><button type="submit">Submit</button></td></tr>
</table>
{% if msg %}
<h3 style="color: green;">{{ msg }}</h3>
{% endif %}
</form>
<table>
<tr>
<th>Student Name</th>
<th>Course Selected</th>
<th>Email Id</th>
<th>Action</th>
</tr>
{% for student1 in std %}
<tr>
<td>{{student1.std_name}}</td>
<td>{{student1.course}}</td>
<td>{{student1.email_id}}</td>
<td style="text-align:center;">
<form method="post" action="{{ url_for('delete_student', std_name=student1.std_name) }}">
<button type="delete"
onclick="return confirm('Are you sure you want to delete this student?')">
Delete
</button>
</form>
</td>
</tr>
{% endfor %}
</table>
</form>
{% endblock %}
--Thanks
app.py
# pip install pymysql
from flask import Flask,render_template, request,url_for,redirect
import pymysql
app=Flask(__name__)
def dbconnection():
conn=pymysql.connect(host="Localhost",user="ccitsource",password="SourcePassword123!",database="ccitdbsource")
return conn
@app.route("/")
def home():
return render_template("index.html")
@app.route("/registration",methods=["GET", "POST"])
def student():
message="All Students records"
if request.method=="POST":
name=request.form.get("name")
course=request.form.get("course")
email=request.form.get("email")
message="post method called"
if name and course and email:
conn = dbconnection()
cursor = conn.cursor()
sql = "INSERT INTO student (std_name, course, email_id) VALUES (%s, %s, %s)"
cursor.execute(sql, (name, course, email))
conn.commit()
cursor.close()
conn.close()
else:
message = "All Students records"
# GET the student details
conn=dbconnection()
cursor=conn.cursor(pymysql.cursors.DictCursor)
sql="select std_name,course,email_id from student"
cursor.execute(sql)
student=cursor.fetchall()
cursor.close()
conn.close()
return render_template("student.html", msg=message, std=student)
@app.route("/delete_student/<string:std_name>", methods=["POST"])
def delete_student(std_name):
conn=dbconnection()
cursor=conn.cursor()
sql="delete from student where std_name=%s"
cursor.execute(sql,(std_name,))
conn.commit()
cursor.close()
conn.close()
return redirect(url_for("student"))
@app.route("/courses")
def courses():
return render_template("courses.html")
if __name__=="__main__":
app.run(debug=True)
remaining Same as above
base.html
style.css
index.html
Output:
No comments:
Post a Comment