0% found this document useful (0 votes)
9 views59 pages

RemoveWatermark Flask Practical

The document outlines a series of Flask web application projects, including session management, alert notifications, a To-Do list with CRUD functionality, and email validation. Each project includes an aim, procedure, and code snippets for both the Flask application and corresponding HTML templates. The projects demonstrate various web development concepts using Flask, such as handling user input, managing sessions, and validating data.
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)
9 views59 pages

RemoveWatermark Flask Practical

The document outlines a series of Flask web application projects, including session management, alert notifications, a To-Do list with CRUD functionality, and email validation. Each project includes an aim, procedure, and code snippets for both the Flask application and corresponding HTML templates. The projects demonstrate various web development concepts using Flask, such as handling user input, managing sessions, and validating data.
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
You are on page 1/ 59

CONTENTS

PAGE
S.NO DATE PROGRAM NAME SIGNATURE
NO

01 Session Object

02 Alert Notification

03 To-Do list using CRUD

04 Email Validator

Login & Registration


05
with MySQL

06 Student Module

07 Staff Module
EX.NO: 01
DATE: SESSION OBJECTS

Aim:

To build a Flask web application that stores a user's inputted


username in a session and displays it, with the ability to clear the session
and reset the page. This demonstrates session management in Flask..

procedure:
Step 1: Begin by importing the required modules from Flask: `Flask`,
`session`, `request`, `render_template`, `redirect`, and `url_for`.
Step 2: Create an instance of the Flask app by calling `Flask(__name__)`.
Set the `app.secret_key` to a string like `"super secret key"` to ensure that
the session is secure.
Step 3: Define the main route (`"/"`) using the `@app.route` decorator.
Allow this route to handle both `GET` and `POST` requests.
Step 4: Inside the view function for the main route, check the request
method. If it's a `POST` request, retrieve the username from the
submitted form data using `request.form["username"]`.
Step 5: Store the username in the session by setting `session["username"]
= username`, allowing the username to persist across different requests.
Step 6: After storing the username, use `render_template` to render the
`base.html` template, passing the `username` to the template so it
can be displayed on the webpage.
Step 7: If the request is a `GET`, render the `base.html` template without
passing the username (or simply render the page with a default
empty form).
Step 8: Define another route (`"/delete_session"`) using `@app.route` to
handle `POST` requests. This route is responsible for clearing the session
data.
Step 9: Inside this delete session route, use `session.pop("username",
None)` to remove the username from the session, then redirect the user
to the main page (`index`) using `redirect(url_for("index"))`.
Step 10: Finally, in the `if __name__ == "__main__"` block, run the Flask
application with `app.run(debug=True)` to enable debugging
and start the web server.

CODE:
app.py
from flask import Flask, session, request, render_template, redirect,
url_for
app = Flask(__name__)
app.secret_key = "super secret key" # set a secret key for the session

@app.route("/", methods=["GET", "POST"])


def index():
if request.method == "POST":
username = request.form["username"]
session["username"] = username
return render_template("base.html", username=username)
return render_template("base.html")

@app.route("/delete_session", methods=["POST"])
def delete_session():
session.pop("username", None)
return redirect(url_for("index"))

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

index.html
<!DOCTYPE html>
<html>
<head>
<title>Session Example</title>
</head>
<body>
<h1>Session Example</h1>
{% if username %}
<p>Welcome, {{ username }}!</p>
<form action="/delete_session" method="post">
<input type="submit" value="Delete Session">
</form>
{% else %}
<form action="/" method="post">
<label for="username">Enter your username:</label>
<input type="text" id="username" name="username">
<input type="submit" value="Set Username">
</form>
{% endif %}
</body>
</html>

Output:
Result:
Thus the above program has been executed successfully.
EX.NO: 02
DATE: ALERT NOTIFICATION

Aim:
The aim of this Flask application is to create a simple web form
that collects user input (name, class, and roll number), displays an alert
notification with the submitted information upon form submission, and
redirects back to the form.

Procedure:

Step 1: Initialize a Flask application by creating an instance of the Flask


class.

Step 2: Set a secret key for the application to enable session


management, allowing the use of flash messages.

Step 3: Define a route for the home page ("/") that supports both GET
and POST requests.

Step 4: In the route function, check if the request method is POST to


handle form submissions.

Step 5: If the request method is POST, retrieve the values of name, class,
and roll number from the submitted form.

Step 6: Use the flash function to create a flash message that includes the
retrieved input data.

Step 7: Redirect the user to the same route ("/") to display the input form
again.

Step 8: If the request method is GET, render the index.html template,


which contains the input form.
Step 9: In the HTML template, create a form with fields for name, class,
and roll number, and a submit button.

Step 10: At the bottom of the HTML template, check for flashed
messages and use JavaScript to display an alert with the first message
when it exists.

CODE:
app.py
from flask import Flask, render_template, request, flash, redirect, url_for

app = Flask(__name__)
app.secret_key = "your_secret_key" # Needed for session management

@app.route("/", methods=["GET", "POST"])


def index():
if request.method == "POST":
name = request.form["name"]
class_name = request.form["class"]
roll_number = request.form["roll_number"]

flash(f"Name: {name}, Class: {class_name}, Roll Number:


{roll_number}")
return redirect(url_for("index"))
return render_template("index.html")

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

index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>Flask Alert Example</title>
<script>
function showAlert(message) {
if (message) {
alert(message);
}
}
</script>
<style>
body {
font-family: Arial, sans-serif;
background-color: #f4f4f4;
margin: 0;
padding: 20px;
}

h1 {
color: #333;
text-align: center;
}

form {
background: white;
padding: 20px;
border-radius: 8px;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
max-width: 400px;
margin: auto;
}

label {
font-weight: bold;
display: block;
margin-bottom: 5px;
}

input[type="text"] {
width: 100%;
padding: 10px;
border: 1px solid #ccc;
border-radius: 4px;
margin-bottom: 15px;
}

button {
background-color: #5cb85c;
color: white;
padding: 10px;
border: none;
border-radius: 4px;
cursor: pointer;
width: 100%;
font-size: 16px;
}

button:hover {
background-color: #4cae4c;
}
</style>
</head>
<body>
<h1>Input Form</h1>
<form method="POST">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required><br><br>

<label for="class">Class:</label>
<input type="text" id="class" name="class" required><br><br>

<label for="roll_number">Roll Number:</label>


<input type="text" id="roll_number" name="roll_number"
required><br><br>

<button type="submit">Submit</button>
</form>

{% with messages = get_flashed_messages(with_categories=true) %}


{% if messages %}
<script>
const message = "{{ messages[0][1] }}"; // Take the first flashed
message
showAlert(message);
</script>
{% endif %}
{% endwith %}
</body>
</html>

Output:
Result:
Thus the above program has been executed successfully.
EX.NO: 03
DATE: To-Do List Using CRUD

Aim:
To develop a Flask-based To-Do list application that allows users
to perform basic CRUD operations on tasks, providing functionality to
add, update, and delete tasks dynamically through a web interface.

procedure:
Step 1: Initialize the Flask application and create an empty list to store
tasks.
Step 2: Create a route for the index page ("/") that renders the
index.html template and passes the list of tasks.

Step 3: In the index.html file, create an HTML form to add new tasks
with a submit button, and display the current tasks as a list.

Step 4: Define the /add route to handle the POST request for adding
tasks. Retrieve the task from the form input and append it to the task list
if it's not empty.
Step 5: Redirect the user back to the index page after adding a task.
Step 6: In the index.html file, include forms next to each task to allow
updates and a delete button for removing tasks.

Step 7: Define the /update/<int:task_id> route to handle task updates.


Retrieve the task ID from the URL and update the task content if
it exists.

Step 8: After updating a task, redirect the user back to the index page to
display the updated list.

Step 9: Define the /delete/<int:task_id> route to handle task deletion.


Remove the task from the list if the ID is valid.
Step 10: Redirect the user back to the index page after deleting a task,
ensuring the updated task list is displayed.

CODE:
app.py
from flask import Flask, render_template, request, redirect, url_for

app = Flask(__name__)

tasks = []

@app.route("/")
def index():
return render_template("index.html", tasks=tasks)

@app.route("/add", methods=["POST"])
def add_task():
task_content = request.form.get("task")
if task_content:
tasks.append(task_content)
return redirect(url_for("index"))

@app.route("/update/<int:task_id>", methods=["POST"])
def update_task(task_id):
new_content = request.form.get("task")
if new_content and 0 <= task_id < len(tasks):
tasks[task_id] = new_content
return redirect(url_for("index"))

@app.route("/delete/<int:task_id>")
def delete_task(task_id):
if 0 <= task_id < len(tasks):
tasks.pop(task_id)
return redirect(url_for("index"))

if __name__ == "__main__":
app.run(debug=True)
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>Flask To-Do App</title>
<style>
body {
font-family: Arial, sans-serif;
background-color: #f4f4f4;
margin: 0;
padding: 20px;
}
h1 {
text-align: center;
color: #333;
}
form {
display: flex;
justify-content: center;
}
input[type="text"] {
padding: 10px;
border: 2px solid #007BFF;
border-radius: 5px;
width: 300px;
transition: border-color 0.3s ease;
}
input[type="text"]:focus {
border-color: #0056b3;
outline: none;
}
button {
padding: 10px 15px;
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
margin-left: 10px;
transition: background-color 0.3s ease, transform 0.3s ease;
}
button:hover {
transform: scale(1.05);
}
ul {
width: 40%;
margin-left: 30%;
list-style-type: none;
padding: 0;
}
li {
background-color: white;
margin-bottom: 5px;
padding: 15px;
border-radius: 5px;
display: flex;
justify-content: space-between;
align-items: center;
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}
a{
text-decoration: none;
color: white;
}
a:hover {
text-decoration: underline;
}
</style>
</head>
<body>
<h1>To-Do List</h1>

<form action="/add" method="POST">


<input type="text" name="task" placeholder="Enter a new task"
required>
<button type="submit" style="background-color: blue;">Add
Task</button>
</form>
<ul>
{% for task in tasks %}
<li>
<form action="/update/{{ loop.index0 }}" method="POST"
style="display:inline;">
<input type="text" name="task" value="{{ task }}" required>
<button type="submit" style="background-color:
green;">Update</button>
</form>
<a href="/delete/{{ loop.index0 }}">
<button style="background-color: red;">Delete</button>
</a>
</li>
{% endfor %}
</ul>
</body>
</html>
output:

Result:
Thus the above program has been executed successfully.
EX.NO: 04
DATE: EMAIL VALIDATOR

Aim:
The aim of this Flask application is to validate user-provided email
addresses using regular expressions and provide feedback on the
validity of the email input. It also offers a simple API endpoint that
returns a greeting message in JSON format.
procedure:
Step 1: Import the necessary modules including Flask, render_template,
request, redirect, url_for, jsonify, and re.
Step 2: Initialize the Flask application by creating an instance of the
Flask class.
Step 3: Define a function is_valid_email(email) that takes an email
string as an input and validates it using a regular expression.
Step 4: Create a route for the index page ("/") that accepts both GET and
POST requests.
Step 5: Inside the index route, initialize variables for validation_result
and result_class to hold the validation message and CSS class
respectively.
Step 6: If the request method is POST, retrieve the email input from the
form.
Step 7: Call the is_valid_email(email) function to check if the email is
valid. If valid, set validation_result to indicate success and
assign "valid" to result_class; if invalid, set
validation_result to indicate failure and assign "invalid" to
result_class.
Step 8: Render the index.html template, passing in the
validation_result and result_class.
Step 9: Define an additional route for the API endpoint ("/api/greet")
that returns a JSON response with a greeting message.
Step 10: Run the Flask application in debug mode when the script is
executed directly.
CODE:
app.py
from flask import Flask, render_template, request, redirect, url_for,
jsonify
import re

app = Flask(__name__)

def is_valid_email(email):
# Simple regex for validating an Email
pattern = r"^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$"
return re.match(pattern, email) is not None

@app.route("/", methods=["GET", "POST"])


def index():
validation_result = None
result_class = None # New variable to hold the CSS class
if request.method == "POST":
email = request.form["email"]
if is_valid_email(email):
validation_result = f"The email '{email}' is valid."
result_class = "valid" # Set class for valid emails
else:
validation_result = f"The email '{email}' is invalid."
result_class = "invalid" # Set class for invalid emails
return render_template("index.html", result=validation_result,
result_class=result_class)

return render_template("index.html", result=validation_result,


result_class=result_class)

@app.route("/api/greet")
def greet():
# Return a JSON response
return jsonify(message="Hello, API!", greet="vanakkam da mapla")
if __name__ == "__main__":
app.run(debug=True)

index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>Email Validator</title>
<style>
body {
font-family: Arial, sans-serif;
background-color: #f4f4f4;
color: #333;
margin: 0;
padding: 20px;
}

h1 {
text-align: center;
color: #4CAF50;
}

form {
background-color: white;
padding: 20px;
border-radius: 5px;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
max-width: 400px;
margin: auto;
}
label {
display: block;
margin-bottom: 10px;
}

input[type="text"] {
width: calc(100% - 20px);
padding: 10px;
margin-bottom: 20px;
border: 1px solid #ccc;
border-radius: 5px;
}

button {
background-color: #4CAF50;
color: white;
border: none;
padding: 10px 15px;
border-radius: 5px;
cursor: pointer;
width: 100%;
}

button:hover {
background-color: #45a049;
}

h2 {
text-align: center;
font-weight: bold;
}

.valid {
color: green; /* Green for valid emails */
}

.invalid {
color: red; /* Red for invalid emails */
}
</style>
</head>
<body>
<h1>Email Validator</h1>
<form method="POST" action="/">
<label for="email">Enter your email:</label>
<input type="text" name="email" id="email" required>
<button type="submit">Validate</button>
</form>

{% if result %}
<h2 class="{{ result_class }}">{{ result }}</h2> <!-- Apply the CSS class
here -->
{% endif %}

</body>
</html>

output:
For Valid Mail Id’s:
For Invalid Mail Id’s:

Result:
Thus the above program has been executed successfully.
EX.NO: 05
DATE: LOGIN & REGISTRATION IN MYSQL

Aim:

The aim of this program is to create a login and registration system


using Flask and MySQL, where users can register, log in, log out, and
manage their sessions securely.

ALGORITHM:
Step 1: Set up the Flask app and configure the MySQL connection with
the required host, user, password, and database settings. Initialize
MySQL in the app.
Step 2: Create the /login route. On form submission, fetch the username
and password, validate against the database, and initiate a session upon
successful login, or display an error message for incorrect
credentials.
Step 3: Manage user sessions. Use session data to track if a user is
logged in and display the correct interface (e.g., index page for logged-in
users).
Step 4: Implement the /logout route, which clears session data and
redirects the user back to the login page.
Step 5: Set up the /register route. On form submission, validate the
username, password, and email, checking for existing accounts and
correct formatting. Insert the new user into the database if valid.
Step 6: Ensure input validation. Verify that usernames contain only valid
characters, emails match a standard format, and all required fields are
filled out.
Step 7: Use HTML templates for login, registration, and the index page.
Dynamically display messages and content based on the user's
login status using Jinja2.
Step 8: Apply CSS styling for a consistent user interface across login,
registration, and index pages, focusing on buttons, input fields,
and headers.
Step 9: Test to ensure registration, login, logout, and validation function
as expected, and fix any issues with user sessions or input errors.
CODE:
app.py
from flask import Flask, render_template, request, redirect, url_for,
session
from flask_mysqldb import MySQL
import MySQLdb.cursors
import re

app = Flask(__name__)

app.secret_key = 'yedhuku da indha manam ketta polappu'

app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_USER'] = 'root'
app.config['MYSQL_PASSWORD'] = 'gacCS@23'
app.config['MYSQL_DB'] = 'geeklogin'

mysql = MySQL(app)

@app.route('/')
@app.route('/login', methods =['GET', 'POST'])
def login():
msg = ''
if request.method == 'POST' and 'username' in request.form and
'password' in request.form:
username = request.form['username']
password = request.form['password']
cursor =
mysql.connection.cursor(MySQLdb.cursors.DictCursor)
cursor.execute('SELECT * FROM accounts WHERE username
= % s AND password = % s', (username, password, ))
account = cursor.fetchone()
if account:
session['loggedin'] = True
session['id'] = account['id']
session['username'] = account['username']
msg = 'Logged in successfully !'
return render_template('index.html', msg = msg)
else:
msg = 'Incorrect username / password !'
return render_template('login.html', msg = msg)

@app.route('/logout')
def logout():
session.pop('loggedin', None)
session.pop('id', None)
session.pop('username', None)
return redirect(url_for('login'))

@app.route('/register', methods =['GET', 'POST'])


def register():
msg = ''
if request.method == 'POST' and 'username' in request.form and
'password' in request.form and 'email' in request.form :
username = request.form['username']
password = request.form['password']
email = request.form['email']
cursor =
mysql.connection.cursor(MySQLdb.cursors.DictCursor)
cursor.execute('SELECT * FROM accounts WHERE username
= % s', (username, ))
account = cursor.fetchone()
if account:
msg = 'Account already exists !'
elif not re.match(r'[^@]+@[^@]+\.[^@]+', email):
msg = 'Invalid email address !'
elif not re.match(r'[A-Za-z0-9]+', username):
msg = 'Username must contain only characters and
numbers !'
elif not username or not password or not email:
msg = 'Please fill out the form !'
else:
cursor.execute('INSERT INTO accounts VALUES
(NULL, % s, % s, % s)', (username, password, email, ))
mysql.connection.commit()
msg = 'You have successfully registered !'
elif request.method == 'POST':
msg = 'Please fill out the form !'
return render_template('register.html', msg = msg)

login.html:
<html>
<head>
<meta charset="UTF-8">
<title> Login </title>
<link rel="stylesheet" href="{{ url_for('static',
filename='style.css') }}">
</head>
<body></br></br></br></br></br>
<div align="center">
<div align="center" class="border">
<div class="header">
<h1 class="word">Login</h1>
</div></br></br></br>
<h2 class="word">
<form action="{{ url_for('login') }}"
method="post">
<div class="msg">{{ msg }}</div>
<input id="username" name="username"
type="text" placeholder="Enter Your Username"
class="textbox"/></br></br>
<input id="password" name="password"
type="password" placeholder="Enter Your Password"
class="textbox"/></br></br></br>
<input type="submit" class="btn"
value="Sign In"></br></br>
</form>
</h2>
<p class="bottom">Don't have an account? <a
class="bottom" href="{{url_for('register')}}"> Sign Up here</a></p>
</div>
</div>
</body>
</html>

register.html:
<html>
<head>
<meta charset="UTF-8">
<title> Register </title>
<link rel="stylesheet" href="{{ url_for('static',
filename='style.css') }}">
</head>
<body></br></br></br></br></br>
<div align="center">
<div align="center" class="border">
<div class="header">
<h1 class="word">Register</h1>
</div></br></br></br>
<h2 class="word">
<form action="{{ url_for('register') }}"
method="post">
<div class="msg">{{ msg }}</div>
<input id="username" name="username"
type="text" placeholder="Enter Your Username"
class="textbox"/></br></br>
<input id="password" name="password"
type="password" placeholder="Enter Your Password"
class="textbox"/></br></br>
<input id="email" name="email"
type="text" placeholder="Enter Your Email ID"
class="textbox"/></br></br>
<input type="submit" class="btn"
value="Sign Up"></br>
</form>
</h2>
<p class="bottom">Already have an account? <a
class="bottom" href="{{url_for('login')}}"> Sign In here</a></p>
</div>
</div>
</body>
</html>

index.html:
<html>
<head>
<meta charset="UTF-8">
<title> Index </title>
<link rel="stylesheet" href="{{ url_for('static',
filename='style.css') }}">
</head>
<body></br></br></br></br></br>
<div align="center">
<div align="center" class="border">
<div class="header">
<h1 class="word">Index</h1>
</div></br></br></br>
<h1 class="bottom">
Hi {{session.username}}!!</br></br>
Welcome to the index page...
</h1></br></br></br>
<a href="{{ url_for('logout') }}"
class="btn">Logout</a>
</div>
</div>
</body>
</html>

style.css:
.header{
padding: 5px 120px;
width: 150px;
height: 70px;
background-color: #236B8E;
}

.border{
padding: 80px 50px;
width: 400px;
height: 450px;
border: 1px solid #236B8E;
border-radius: 0px;
background-color: #9AC0CD;
}

.btn {
padding: 10px 40px;
background-color: #236B8E;
color: #FFFFFF;
font-style: oblique;
font-weight: bold;
border-radius: 10px;
}

.textbox{
padding: 10px 40px;
background-color: #236B8E;
text-color: #FFFFFF;
border-radius: 10px;
}

::placeholder {
color: #FFFFFF;
opacity: 1;
font-style: oblique;
font-weight: bold;
}

.word{
color: #FFFFFF;
font-style: oblique;
font-weight: bold;
}

.bottom{
color: #236B8E;
font-style: oblique;
font-weight: bold;
}

OUTPUT:
Login Page:
Registration Page:
If Registration Successful:

Before registration, Database table:


After registration, Database table:

If login successful, Indexpage is displayed:


If Login fails:

Result:
Thus the above program has been executed successfully.
EX.NO: 06
DATE: STUDENT MODULE

Aim:

The aim of this program is to create an event management system


that allows users to view available events and book tickets, with the
booking details being stored in a MySQL database.

Algorithm:
Step 1: Initialize the Flask application and configure MySQL for
database connectivity, ensuring that event and booking data are stored
and retrieved correctly.
Step 2: Define two main routes: /home for displaying available events
and /book/<event_name> for handling event bookings.
Step 3: In the /home route, connect to the MySQL database, fetch all
events using an SQL query, and pass the event data to the home.html
page for rendering.
Step 4: In the /book/<event_name> route, query the database for the
details of the selected event and display the booking form on book.html.
Step 5: When the user submits the form in /book/<event_name>,
retrieve the user's booking information, including their name, email, and
number of seats and store this information in the booked table of the
database.
Step 6: Use Flask's flash function to display a success message
confirming that the booking has been recorded, then redirect the user
back to the homepage.
Step 7: Render the home.html page with event data displayed in a table,
where users can click "Book Now" to access the booking form for each
event.
Step 8: In the book.html page, display event details and provide input
fields for the user's booking information, pre-filling certain fields with
event data.
Step 9: Upon form submission, validate the data, update the database
with the booking, and display confirmation feedback to the user.
Step 10: Run the Flask application, ensuring the server is responsive to
user actions like viewing events, booking tickets, and receiving booking
confirmations.

CODE:
app.py
from flask import Flask, render_template, request, url_for, redirect, flash,
session
from flask_mysqldb import MySQL
import MySQLdb.cursors

app = Flask(__name__)

app.secret_key = "po da venna"

app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_USER'] = 'root' app.config['MYSQL_PASSWORD']
= 'root' app.config['MYSQL_DB'] = 'flask'
mysql = MySQL(app)

@app.route('/')
@app.route("/home", methods=["GET"])
def home():
cur = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
cur.execute("SELECT * FROM events")
events = cur.fetchall()
cur.close()
return render_template("home.html", events=events)

@app.route("/book/<event_name>", methods=["GET", "POST"])


def book(event_name):
cur = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
cur.execute("SELECT * FROM events WHERE event_name = %s",
(event_name,))
event = cur.fetchone()
cur.close()

if request.method == "POST":
name = request.form["name"]
mail = request.form["mail"]
mobile = request.form["mobile"]
date = request.form["event_date"]
time = request.form["event-time"]
venue = request.form["venue"]
seats = request.form["seats"]

cur = mysql.connection.cursor()
cur.execute("INSERT INTO booked (name, email, mobile,
event_name, event_date, event_time, venue, seats) VALUES (%s, %s, %s,
%s, %s, %s, %s, %s)",
(name, mail, mobile, event_name, date, time, venue, seats))
mysql.connection.commit()
cur.close()

flash("Booking successful!", "success")


return redirect(url_for("home"))

return render_template("book.html", event=event)


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

home.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>Events Home</title>
<style>
body {
font-family: Arial, sans-serif;
background-color: #f4f4f4;
margin: 0;
padding: 20px;
}
h1 {
text-align: center;
}
table {
width: 100%;
border-collapse: collapse;
margin-bottom: 20px;
}
table, th, td {
border: 1px solid #ddd;
}
th, td {
padding: 8px;
text-align: center;
}
th {
background-color: #f2f2f2;
}
button {
padding: 8px 12px;
border: none;
border-radius: 4px;
cursor: pointer;
}
.btn-book {
background-color: #28a745;
color: white;
}
.btn-book:hover {
background-color: #218838;
}
.flash-success {
color: green;
text-align: center;
}
</style>
</head>
<body>
<h1>Available Events</h1>

<table>
<tr>
<th>Event Name</th>
<th>Date</th>
<th>Venue</th>
<th>Action</th>
</tr>
{% for event in events %}
<tr>
<td>{{ event['event_name'] }}</td>
<td>{{ event['date'] }}</td>
<td>{{ event['venue'] }}</td>
<td>
<a href="{{ url_for('book', event_name=event['event_name'])
}}">
<button class="btn-book">Book Now</button>
</a>
</td>
</tr>
{% endfor %}
</table>

{% with messages = get_flashed_messages(with_categories=true) %}


{% if messages %}
{% for category, message in messages %}
<p class="flash-{{ category }}">{{ message }}</p>
{% endfor %}
{% endif %}
{% endwith %}
</body>
</html>
book.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>Book Event</title>
<style>
body {
font-family: Arial, sans-serif;
background-color: #f4f4f4;
margin: 0;
padding: 20px;
}
h1 {
text-align: center;
}
form {
background-color: white;
padding: 20px;
border-radius: 5px;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
max-width: 400px;
margin: auto;
}
label, input {
display: block;
width: 100%;
margin-bottom: 15px;
}
input[type="text"], input[type="email"], input[type="tel"],
input[type="date"], input[type="time"], input[type="number"] {
padding: 10px;
border: 1px solid #ccc;
border-radius: 5px;
}
button {
padding: 10px;
border: none;
border-radius: 5px;
background-color: #28a745;
color: white;
cursor: pointer;
width: 100%;
}
button:hover {
background-color: #218838;
}
.flash-success {
color: green;
text-align: center;
}
</style>
</head>
<body>
<h1>Book Event: {{ event['event_name'] }}</h1>
<form method="POST">
<label for="name">Your Name</label>
<input type="text" id="name" name="name" required>

<label for="mail">Your Email</label>


<input type="email" id="mail" name="mail" required>
<label for="mobile">Your Mobile Number</label>
<input type="tel" id="mobile" name="mobile" required>

<label for="event_date">Event Date</label>


<input type="date" id="event_date" name="event_date" value="{{
event['date'] }}" required>

<label for="event-time">Event Time</label>


<input type="time" id="event-time" name="event-time" required>
<label for="venue">Venue</label>
<input type="text" id="venue" name="venue" value="{{
event['venue'] }}" required>
<label for="seats">Number of Seats</label>
<input type="number" id="seats" name="seats" min="1" required>
<button type="submit">Confirm Booking</button>
</form>

{% with messages = get_flashed_messages(with_categories=true) %}


{% if messages %}
{% for category, message in messages %}
<p class="flash-{{ category }}">{{ message }}</p>
{% endfor %}
{% endif %}
{% endwith %}
</body>
</html>

OUTPUT:
Home Page
Booking a Event

Booked Success
Result:
Thus the above program has been executed successfully.

EX.NO: 07
DATE: STAFF MODULE

Aim:

To develop an event management system using Flask that allows


users to create, view, update, and delete events, as well as view details of
booked events.

Algorithm:

Step 1: Import the necessary libraries, including Flask for web handling
and MySQL for database interactions.

Step 2: Create a Flask application instance to manage the web app


functionalities.

Step 3: Configure the MySQL database connection with the necessary


parameters: host, user, password, and database name.

Step 4: Define the "/host" route to handle event creation. In the POST
request, extract event details (event name, date, venue) from the form.

Step 5: Within the "/host" route, connect to the MySQL database and
insert the event into the "events" table.

Step 6: After inserting the event, flash a success message to inform the
user of the successful event creation and redirect to the home page.

Step 7: Define the "/home" route to display all events. In the GET
request, fetch all event records from the "events" table.

Step 8: Render the "home.html" template with the retrieved event data
to display the list of events on the home page.

Step 9: Define the "/update/<event_name>" route for updating event


details. Fetch the current event data based on the provided event name.
Step 10: In a POST request for the "/update/<event_name>" route,
extract updated event details from the form, update the event in the
database, flash a success message, and redirect to the home page. Render
the "update.html" template for GET requests.

Step 11: Define the "/delete/<event_name>" route to delete specified


events from the database. After executing the delete query, flash a
success message and redirect to the home page.

Step 12: Define the "/booked" route to display booked events. In a GET
request, retrieve all booked event records from the "booked" table and
render the "booked.html" template with the data.

Step 13: Run the Flask application in debug mode to facilitate error
detection during development.

CODE:
app.py
from flask import Flask, render_template, request, url_for, redirect, flash,
session
from flask_mysqldb import MySQL
import MySQLdb.cursors

app = Flask(__name__)

app.secret_key = "po da venna"

app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_USER'] = 'root' # replace with your MySQL
username
app.config['MYSQL_PASSWORD'] = 'root' # replace with your MySQL
password
app.config['MYSQL_DB'] = 'flask' # replace with your database name

mysql = MySQL(app)

@app.route("/host", methods=["GET", "POST"])


def host():
if request.method == "POST":
event_name = request.form["hostevent"]
date = request.form["hostdate"]
venue = request.form["venue"]

cur = mysql.connection.cursor()
cur.execute("INSERT INTO events (event_name, date, venue)
VALUES (%s, %s, %s)",
(event_name, date, venue))
mysql.connection.commit()
cur.close()

flash("Event created successfully!", "success")


return redirect(url_for("home"))

return render_template("host.html")

@app.route('/')
@app.route('/home',methods=["GET","POST"])
def home():
if request.method == "GET":
cur = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
cur.execute("SELECT * FROM events")
events = cur.fetchall()
cur.close()
return render_template("home.html",events=events)
return render_template("home.html")

@app.route("/update/<event_name>", methods=["GET", "POST"])


def update(event_name):
cur = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
cur.execute("SELECT * FROM events WHERE event_name = %s",
(event_name,))
event = cur.fetchone()
cur.close()

if request.method == "POST":
new_event_name = request.form["hostevent"]
date = request.form["hostdate"]
venue = request.form["venue"]
cur = mysql.connection.cursor()
cur.execute("UPDATE events SET event_name = %s, date = %s,
venue = %s WHERE event_name = %s",
(new_event_name, date, venue, event_name))
mysql.connection.commit()
cur.close()

flash("Event updated successfully!", "success")


return redirect(url_for("home"))

return render_template("update.html", event=event)

@app.route("/delete/<event_name>")
def delete(event_name):
cur = mysql.connection.cursor()
cur.execute("DELETE FROM events WHERE event_name = %s",
(event_name,))
mysql.connection.commit()
cur.close()

flash("Event deleted successfully!", "danger")


return redirect(url_for("home"))

@app.route("/booked",methods=["GET"])
def booked():
if request.method == "GET":
cur = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
cur.execute("SELECT * FROM booked")
booked = cur.fetchall()
cur.close()
return render_template("booked.html",booked=booked)
return render_template("booked.html")

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

booked.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>Booked Events</title>
<style>
body {
font-family: Arial, sans-serif;
background-color: #f4f4f4;
margin: 0;
padding: 20px;
}
table {
width: 100%;
border-collapse: collapse;
}
table, th, td {
border: 1px solid #ddd;
}
th, td {
padding: 8px;
text-align: center;
}
th {
background-color: #f2f2f2;
}
button {
padding: 5px 10px;
border: none;
border-radius: 4px;
cursor: pointer;
}

</style>
</head>
<body>

<h1>Booked Events</h1>

<table>
<tr>
<th>Name</th>
<th>Email</th>
<th>Mobile</th>
<th>Event Name</th>
<th>Event Date</th>
<th>Event Time</th>
<th>Venue</th>
<th>Seats</th>
</tr>
{% for book in booked %}
<tr>
<td>{{ book['name'] }}</td>
<td>{{ book['email'] }}</td>
<td>{{ book['mobile'] }}</td>
<td>{{ book['event_name'] }}</td>
<td>{{ book['event_date'] }}</td>
<td>{{ book['event_time'] }}</td>
<td>{{ book['venue'] }}</td>
<td>{{ book['seats'] }}</td>
</tr>
{% endfor %}
</table>

</body>
</html>

home.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>Events</title>
<style>
body {
font-family: Arial, sans-serif;
background-color: #f4f4f4;
margin: 0;
padding: 20px;
}
table {
width: 100%;
border-collapse: collapse;
}
table, th, td {
border: 1px solid #ddd;
}
th, td {
padding: 8px;
text-align: center;
}
th {
background-color: #f2f2f2;
}
button {
padding: 5px 10px;
border: none;
border-radius: 4px;
cursor: pointer;
}
.btn-host{
margin-top: 25%;
background-color: green;
color: white;
}
.btn-edit {
background-color: #007bff;
color: white;
}
.btn-edit:hover {
background-color: #0056b3;
}
.btn-delete {
background-color: #dc3545;
color: white;
}
.btn-delete:hover {
background-color: #c82333;
}
div{
display: flex;
justify-content: space-evenly ;
}
</style>
</head>
<body>
<div>
<h1>All Events</h1>
<a href="{{url_for('host')}}"><button class="btn-host">Host
Event</button> </a>
<a href="{{url_for('booked')}}"><button class="btn-host">Booked
Event</button> </a>
</div>

<table>
<tr>
<th>Event Name</th>
<th>Date</th>
<th>Venue</th>
<th>Actions</th>
</tr>
{% for event in events %}
<tr>
<td>{{ event['event_name'] }}</td>
<td>{{ event['date'] }}</td>
<td>{{ event['venue'] }}</td>
<td>
<a href="{{ url_for('update', event_name=event['event_name'])
}}">
<button class="btn-edit">Edit</button>
</a>
<a href="{{ url_for('delete', event_name=event['event_name'])
}}">
<button class="btn-delete">Delete</button>
</a>
</td>
</tr>
{% endfor %}
</table>

{% with messages = get_flashed_messages(with_categories=true) %}


{% if messages %}
{% for category, message in messages %}
<p class="flash-{{ category }}">{{ message }}</p>
{% endfor %}
{% endif %}
{% endwith %}
</body>
</html>

host.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>Host Event</title>
<style>
body {
font-family: Arial, sans-serif;
background-color: #f4f4f4;
margin: 0;
padding: 20px;
}
form {
background-color: white;
padding: 20px;
border-radius: 5px;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
max-width: 400px;
margin: auto;
}
label, input, button {
display: block;
width: 100%;
margin-bottom: 15px;
}
input[type="text"], input[type="date"] {
padding: 10px;
border: 1px solid #ccc;
border-radius: 4px;
}
button {
padding: 10px;
border: none;
border-radius: 4px;
background-color: #28a745;
color: white;
cursor: pointer;
}
button:hover {
background-color: #218838;
}
.flash-success {
color: green;
}
.flash-danger {
color: red;
}
</style>
</head>
<body>
<h1>Host a New Event</h1>
<form method="POST" action="{{ url_for('host') }}">
<label for="hostevent">Event Name</label>
<input type="text" id="hostevent" name="hostevent" required>

<label for="hostdate">Date</label>
<input type="date" id="hostdate" name="hostdate" required>

<label for="venue">Venue</label>
<input type="text" id="venue" name="venue" required>

<button type="submit">Create Event</button>


</form>

{% with messages = get_flashed_messages(with_categories=true) %}


{% if messages %}
{% for category, message in messages %}
<p class="flash-{{ category }}">{{ message }}</p>
{% endfor %}
{% endif %}
{% endwith %}
</body>
</html>

update.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>Update Event</title>
<style>
body {
font-family: Arial, sans-serif;
background-color: #f4f4f4;
margin: 0;
padding: 20px;
}
form {
background-color: white;
padding: 20px;
border-radius: 5px;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
max-width: 400px;
margin: auto;
}
label, input, button {
display: block;
width: 100%;
margin-bottom: 15px;
}
input[type="text"], input[type="date"] {
padding: 10px;
border: 1px solid #ccc;
border-radius: 4px;
}
button {
padding: 10px;
border: none;
border-radius: 4px;
background-color: #007bff;
color: white;
cursor: pointer;
}
button:hover {
background-color: #0056b3;
}
.flash-success {
color: green;
}
.flash-danger {
color: red;
}
</style>
</head>
<body>
<h1>Update Event</h1>
<form method="POST" action="{{ url_for('update',
event_name=event['event_name']) }}">
<label for="hostevent">Event Name</label>
<input type="text" id="hostevent" name="hostevent" value="{{
event['event_name'] }}" required>

<label for="hostdate">Date</label>
<input type="date" id="hostdate" name="hostdate" value="{{
event['date'] }}" required>

<label for="venue">Venue</label>
<input type="text" id="venue" name="venue" value="{{
event['venue'] }}" required>

<button type="submit">Update Event</button>


</form>

{% with messages = get_flashed_messages(with_categories=true) %}


{% if messages %}
{% for category, message in messages %}
<p class="flash-{{ category }}">{{ message }}</p>
{% endfor %}
{% endif %}
{% endwith %}
</body>
</html>

OUTPUT:
Home Page

Host Event Page

Event hosted success

Booked Event Page


Updating existing event

Updated Success

Result:
Thus the above program has been executed successfully.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy