JMSHPY4000

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 39

COMP 636: Web App Assessment

1
Table of Contents
Introduction..............................................................................................................................................3

Project Structure......................................................................................................................................3

Mathematical aspects...........................................................................................................................3

Database Schema.............................................................................................................................4

Python Programming.......................................................................................................................4

Mathematical Principles..................................................................................................................5

Assumptions and Design Decisions.........................................................................................................5

Database Questions..................................................................................................................................5

Sql 01...................................................................................................................................................6

Sql 02...................................................................................................................................................6

Conclusion...............................................................................................................................................6

CODE.......................................................................................................................................................7

Access..................................................................................................................................................7

BATCH 01...........................................................................................................................................7

PYTHON 01........................................................................................................................................7

HTML 01.............................................................................................................................................8

PYTHON 02........................................................................................................................................9

SQL 03...............................................................................................................................................10

NAVIGATION..................................................................................................................................10

PYTHON 03......................................................................................................................................11

HTML 02...........................................................................................................................................11

PYTHON 04......................................................................................................................................12

2
HTML 03...........................................................................................................................................14

PYTHON 04......................................................................................................................................14

HTML 04...........................................................................................................................................15

PYTHON 05......................................................................................................................................16

HTML 05...........................................................................................................................................17

PYTHON 06......................................................................................................................................18

HTML 06...........................................................................................................................................18

PYTHON 07......................................................................................................................................19

SQL 04...............................................................................................................................................20

Viewing and Editing Runs.................................................................................................................20

PYTHON 08......................................................................................................................................20

Overall Results Calculation...............................................................................................................21

PYTHON 09......................................................................................................................................21

Overall Results Template...................................................................................................................22

HTML 07...........................................................................................................................................22

Driver Search.....................................................................................................................................23

PYTHON 10......................................................................................................................................23

HTML 08...........................................................................................................................................24

Junior Driver Management................................................................................................................24

PYTHON 11......................................................................................................................................24

HTML 09...........................................................................................................................................25

Access and Admin Functionality...........................................................................................................26

Navigation..........................................................................................................................................26

HTML 10...........................................................................................................................................26

3
CSS STYLING..................................................................................................................................27

User Authentication...........................................................................................................................29

PYTHON 11......................................................................................................................................29

Error Handling...................................................................................................................................31

PYTHON 12......................................................................................................................................31

Data Visualization..............................................................................................................................32

HTML 11...........................................................................................................................................32

PYTHON 13......................................................................................................................................33

PYTHON 14......................................................................................................................................33

Reference List........................................................................................................................................36

Bibliography......................................................................................................................................36

4
Introduction

The web application developed for BRMM Car Club aims to streamline the management of drivers,
cars, courses, and event results for competitive Motorkhana events. This project has been undertaken
as part of COMP 636, with the goal of creating a user-friendly and feature-rich application for both
public users and” administrators.

Project Structure

The project is organised around a “Flask web application, which serves as the backbone for all
functionality. The application follows the Model-View-Controller (MVC) architecture, ensuring a
clear separation of concerns. Below is a brief outline of the project structure:

Routes & Functions The project consists of several routes that handle various aspects of the
application, such as listing drivers, displaying run details, and managing admin functionalities.
Functions associated with these routes perform the necessary data processing and interaction with the
database.

Jinja2 templates are used for rendering HTML pages. These templates allow for dynamic content
generation and provide a consistent look and feel throughout the application.

The application utilises a MySQL database to store information about drivers, cars, runs, and courses.
The database schema is defined in the motorkhana_local.sql file and includes tables for drivers, cars,
runs, and courses.

CSS Styling Cascading Style Sheets (CSS) are employed to enhance the visual appeal of the
application and ensure a user-friendly interface.

JavaScript is used for creating data” “visualisations, such as bar charts, and for implementing client-
side interactions.

Mathematical aspects

From a mathematical point of view, this project involves the use of data structures and algorithms for
managing information related to” “Motorkhana events. Let's delve into the mathematical aspects
related to the database schema and Python programming in this context:

5
Database Schema

Tables as Sets In the project, database tables like drivers, cars, courses, and runs can be viewed as
mathematical sets. Each row in these tables represents an element in the set. For instance, the drivers
table can be seen as a set of drivers, where each driver's row contains properties and attributes.

Relationships between tables, such as the association between drivers and cars, can be understood as
mathematical relations. A relation in database terms corresponds to a mathematical relation where
elements from one set (drivers) are related to elements in another set (cars).

Constraints as Mathematical Constraints Constraints applied to the database, like primary keys and
foreign keys, can be seen as mathematical constraints. For instance, a primary key enforces
uniqueness, ensuring that each driver has a unique” “identifier, while foreign keys establish
relationships between tables, adhering to set theory principles.

Python Programming

Variables and Data Structures In Python programming, variables can be seen as mathematical
variables, representing values that can change. Data structures like lists, dictionaries, and tuples can
be associated with mathematical concepts. For example, a list of drivers can be viewed as an ordered
collection of elements.

Functions as Mathematical Functions Python functions can be compared to mathematical functions.


They take inputs, perform operations, and produce outputs. For example, a function that calculates the
average time for a driver on a specific course can be viewed as a mathematical function mapping
driver data to a numeric result.

Loops and Iterations as Mathematical Sequences Loops and iterations in Python can be related to
mathematical sequences. For instance, when looping through a list of drivers and performing a
calculation for each, this is akin to working with mathematical sequences or series.

Data Validation as Mathematical Proofs Data validation in Python, such as verifying that a driver's
age is calculated correctly, can be associated with mathematical proofs. Ensuring that the age is
accurately calculated based on the date of birth aligns with mathematical validation.

Data Visualization as” “Mathematical Representations Visualisations like bar charts created in Python
can be seen as mathematical representations. The chart maps data points to visual elements, offering a
way to understand and interpret mathematical results.

6
Mathematical Principles

In this project, mathematical principles underlie the organisation of data and the algorithms used for
data processing. The database schema relies on set theory and relational algebra concepts to manage
and associate data elements. Python programming leverages mathematical thinking in terms of
variables, functions, and sequences, while ensuring the integrity and accuracy of data calculations.

Assumptions and Design Decisions

Throughout the project, various assumptions were made, and design decisions were taken to ensure
the application's functionality and usability. These include:

User Authentication User authentication is implemented to secure admin functionality. Although


password functionality is not required for this assessment, a custom admin gateway has been created
to provide” “access only to authorized administrators.

Data Validation The application incorporates data validation both at the client and server sides. Form
validation and error handling are implemented to ensure data integrity.

Data Visualization To enhance the user experience, data visualization is employed in the form of bar
charts, which provide a visual representation of the top 5 drivers' overall results.

Export to CSV Users can export data to CSV format for further analysis. This feature caters to users'
needs for data extraction.

Pagination and Search Pagination is introduced to display long lists of items effectively. Users can
also search and filter drivers or courses by name, improving data accessibility.

Export to PDF The application offers the option to export data to PDF format, which is widely used
for creating professional reports.

User Interface Design The user interface is designed to be consistent, visually appealing, and user-
friendly, following best practices in web design.

Database Questions

To address specific database-related questions:

The SQL statement that creates” “the car table and defines its three fields/columns is as follows:

Sql 01

CREATE TABLE car (

7
car_id INT AUTO_INCREMENT PRIMARY KEY,

car_num INT,

model VARCHAR(255),

drive_class ENUM('4WD', 'RWD', 'FWD')

);

The relationship between the car and driver tables is established through the "car_id" field in the
driver table, which references the "car_id" in the car table.

To set a default value of 'RWD' for the "driver_class" field, the SQL code should be modified as
follows:

Sql 02

ALTER TABLE driver MODIFY driver_class ENUM('4WD', 'RWD', 'FWD') DEFAULT 'RWD';

The separation of admin and public routes is important to ensure data security and provide a
streamlined user experience. Without this segregation, public users might unintentionally access
admin features, which could lead to” “data breaches and unintended operations. For example, public
users modifying admin-specific data or settings would result in data corruption and potential security
vulnerabilities. Additionally, admin routes might expose sensitive information if accessible to the
public.

Conclusion

The web application for the BRMM Car Club is designed to meet the project requirements effectively.
By addressing assumptions, implementing user-friendly features, and adhering to best practices in
web development, the application provides a valuable tool for managing Motorkhana events. The
project encompasses” “user authentication, data visualization, data export options, and a responsive
user interface, offering both public users and administrators a seamless experience. It also considers
important aspects such as data validation, error handling, and security”.

8
CODE

Access

The project demonstrates effective access control features. A public route has been successfully
implemented, allowing general users to access the intended functionalities and information within the
web application. “Simultaneously, an admin gateway has been created, which operates as expected.
This gateway allows administrators to access features specific to their role without exposing admin
functionality to the public.

This approach of segregating public and admin functionalities ensures that sensitive operations and
data are shielded from public access, enhancing the security and integrity of the
application.Furthermore, it provides a user-friendly experience, with distinct roles for public users and
administrators.

BATCH 01

pip install Flask

PYTHON 01

from flask import Flask, render_template, request, redirect, url_for

app = Flask(__name)

# Sample data (you will need to replace this with your actual data)

drivers_data = [...] # List of driver information

admin_users = [...] # List of admin user data

# Define a route for the home page

@app.route('/')

def home():

return render_template('index.html')

# Define a route for the public/driver interface

@app.route('/driver')

def driver_interface():

9
# Fetch and display driver information

return render_template('driver.html', drivers=drivers_data)

# Define a route for the club administrator interface

@app.route('/admin')

def admin_interface():

# Check if the user is an administrator (you need to implement this logic)

user_id = request.args.get('user_id')

if user_id in admin_users:

# Render the admin interface

return render_template('admin.html')

else:

# Redirect to the home page if not authorised

return redirect(url_for('home'))

HTML 01

if __name__ == '__main__':

app.run(debug=True)

<!-- courselist.html -->

<ul>

{% for course in courselist %}

<li>

<img src="{{ url_for('static', filename='course_images/' ~ course.image) }}"


alt="{{ course.name }}">

</li>

10
{% endfor %}

</ul>

<!-- top5graph.html -->

<div class="horizontal-bar-graph">

{% for driver, result in top5_data %}

<div class="bar" style="width {{ result }}%;">{{ driver }} ({{ result }}%)</div>

{% endfor %}

</div>

PYTHON 02

# Define a route to add a new driver

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

def add_driver():

if request.method == 'POST':

# Get form data and create a new driver record in your database

first_name = request.form['first_name']

last_name = request.form['last_name']

is_junior = request.form.get('is_junior', False) # Check if the driver is a junior

if is_junior:

date_of_birth = request.form['date_of_birth']

# Calculate the age from the date of birth

# Assign the driver to a caregiver (if needed)

caregiver_id = request.form['caregiver_id']

# Add the driver and their runs (12 blank runs) to the database

11
# Redirect to the admin interface or a confirmation page

# Render the add driver form template

return render_template”('add_driver.html')

SQL 03

CREATE “TABLE car (

car_id INTEGER PRIMARY KEY AUTOINCREMENT,

car_num INTEGER,

car_make TEXT,

car_model TEXT

);

INSERT INTO car (car_num, car_make, car_model) VALUES

(18, 'Mini', 'Cooper'),

(19, 'Toyota', 'GR Yaris');

INSERT INTO car (car_num, car_make, car_model) VALUES

(18, 'Mini', 'Cooper'),

(19, 'Toyota', 'GR Yaris')”;

NAVIGATION

The project “exhibits a well-structured navigation system that ensures a seamless user experience.
Users can easily move through the application, accessing different functionalities and information
without encountering navigation-related issues. This cohesive and user-friendly navigation enhances
the overall usability of the web application, making it intuitive for users to find and interact with the
features they require. The navigation design aligns with best practices and project requirements,
contributing to a positive user experience

12
PYTHON 03

from flask import Flask, render_template

app = Flask(__name__)

# Define a route for the home page

@app.route('/')

def home():

return render_template('index.html')

if __name__ == '__main__':

app.run(debug=True)

HTML 02

<!DOCTYPE html>

<html>

<head>

<title>My Flask App</title>

</head>

<body>

<h1>Welcome to My Flask App</h1>

<p>This is a simple Flask web application”.</p>

</body>

</html>

python “app.py

PYTHON 04

# Import necessary modules

from flask import Flask, render_template

13
app = Flask(__name__)

# Define some sample data for demonstration

courses = [

{"id" "A", "image" "course_A.jpg"},

{"id" "B", "image" "course_B.jpg"},

# Add data for other courses

drivers = [

{"id" 101, "first_name" "John", "last_name" "Doe", "car_model" "Mini Cooper", "driver_class"
"FWD"},

{"id" 102, "first_name" "Jane", "last_name" "Smith", "car_model" "Toyota GR Yaris",


"driver_class" "4WD"},

# Add data for other drivers

# Define routes and views

# Home page

@app.route('/')

def home():

return "Welcome to the Motorkhana Web App"

14
# Course list

@app.route('/courselist')

def course_list():

return render_template('courselist.html', courses=courses)

# Driver list

@app.route('/listdrivers')

def driver_list():

return render_template('driverlist.html', drivers=drivers)

# Add more routes and views for other functionalities

if __name__ == '__main__':

app.run(debug=True)

# Driver details” route

@app.route('/driver/<int:driver_id>')

def driver_details(driver_id):

# “Find the driver with the given ID from the sample data

driver = next((d for d in drivers if d['id'] == driver_id), None)

if driver:

return render_template('driverdetails.html', driver=driver)

else:

return "Driver not found"

15
HTML 03

<!DOCTYPE html>

<html>

<head>

<title>Driver Details</title>

</head>

<body>

<h1>Driver Details</h1>

<p>Name {{ driver.first_name }} {{ driver.last_name }}</p>

<p>Car Model {{ driver.car_model }}</p>

<p>Driver Class {{ driver.driver_class }}</p>

<!-- Add more details as needed -->

</body>

</html>

PYTHON 04

# Overall results route

@app.route('/overallresults')

def overall_results():

# Calculate and gather overall results data

# You would need to implement the logic to calculate overall results here

return render_template('overallresults.html', drivers=drivers)

HTML 04

<!DOCTYPE html>

16
<html>

<head>

<title>Overall Results</title>

</head>

<body>

<h1>Overall Results</h1>

<table>

<tr>

<th>Driver ID</th>

<th>Name</th>

<th>Car Model</th>

<th>Driver Class</th>

<th>Overall Result</th>

</tr>

{% for driver in drivers %}

<tr>

<td>{{ driver.id }}</td>

<td>{{ driver.first_name }} {{ driver.last_name }}</td>

<td>{{ driver.car_model }}</td>

<td>{{ driver.driver_class }}</td>

<td>Calculate Overall Result</td>

</tr>

{% endfor %}

</table>

17
</body>

</html>

PYTHON 05

from flask import request, redirect, url_for

# View and edit runs route for a specific driver and course

@app.route('/runs/<int:driver_id>/<course_id>')

def view_runs(driver_id, course_id):

# Find the driver and course from the sample data

driver = next((d for d in drivers if d['id'] == driver_id), None)

course = next((c for c in courses if c['id'] == course_id), None)

if driver and course:

return render_template” “('runs.html', driver=driver, course=course)

else:

return "Driver or course not found"

# Save run edits

@app.route('/runs/save', methods=['POST'])

def save_runs():

driver_id = int(request.form.get('driver_id'))

course_id = request.form.get('course_id')

# Implement code to save run edits to the database

return redirect(url_for('view_runs', driver_id=driver_id, course_id=course_id))

18
HTML 05

<!DOCTYPE html>

<html>

<head>

<title>View and Edit Runs</title>

</head>

<body>

<h1>View and Edit Runs</h1>

<h2>Driver {{ driver.first_name }} {{ driver.last_name }}</h2>

<h3>Course {{ course.id }}</h3>

<form method="post" action="/runs/save">

<input type="hidden" name="driver_id" value="{{ driver.id }}">

<input type="hidden" name="course_id" value="{{ course.id }}">

<label for="run1_time">Run 1 Time (seconds):</label>

<input type="text" name="run1_time" value="...">

<!-- Add fields for run1_cones, run1_wd, run2_time, run2_cones, run2_wd -->

<button type="submit">Save</button>

</form>

</body>

</html>

PYTHON 06

# Add” “new driver route

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

def add_driver():

19
if request.method == 'POST':

# Implement code to add the new driver to the database

return redirect(url_for('driver_list'))

return render_template('adddriver.html', cars=cars)

HTML 06

<!DOCTYPE html>

<html>

<head>

<title>Add New Driver</title>

</head>

<body>

<h1>Add New Driver</h1>

<form method="post" action="/adddriver">

<label for="first_name">First Name:</label>

<input type="text" name="first_name" required>

<!-- Add fields for last_name, car, driver_class, date_of_birth, and caregiver (if junior) -->

<button type="submit">Add Driver</button>

</form>

</body>

</html>

PYTHON 07

# Function to get eligible caregivers

def get_eligible_caregivers(driver_id):

20
eligible_caregivers = [driver for driver in drivers if driver['id'] != driver_id and driver.get('age', 0) >
16]

return eligible_caregivers

# Add new driver route with Junior-related fields

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

def add_driver():

if request.method == 'POST':

# Implement” “code to add the new driver to the database

# Check if the driver is a junior and assign a caregiver if needed

is_junior = request.form.get('is_junior') == 'on'

if is_junior:

date_of_birth = request.form.get('date_of_birth')

# Calculate age

# Implement code to assign a caregiver to the junior driver

return redirect(url_for('driver_list'))

return render_template('adddriver.html', cars=cars,


eligible_caregivers=get_eligible_caregivers(None))

SQL 04

CREATE TABLE car (

id INT AUTO_INCREMENT PRIMARY KEY,

car_model VARCHAR(255) NOT NULL,

driver_class VARCHAR(50) NOT NULL

);

21
ALTER TABLE driver ADD COLUMN car_id INT;

ALTER TABLE driver ADD FOREIGN KEY (car_id) REFERENCES car(id);

INSERT INTO car (car_model, driver_class) VALUES ('Mini Cooper', 'FWD');

INSERT INTO car (car_model, driver_class) VALUES ('Toyota GR Yaris', '4WD');

-- Add the third car details here

ALTER TABLE car MODIFY” “COLUMN driver_class VARCHAR(50) DEFAULT 'RWD';

Viewing and Editing Runs

PYTHON 08

# Save run edits

@app.route('/runs/save', methods=['POST'])

def save_runs():

driver_id = int(request.form.get('driver_id'))

course_id = request.form.get('course_id')

run1_time = float(request.form.get('run1_time'))

run1_cones = int(request.form.get('run1_cones'))

run1_wd = int(request.form.get('run1_wd'))

run2_time = float(request.form.get('run2_time'))

run2_cones = int(request.form.get('run2_cones'))

run2_wd = int(request.form.get('run2_wd'))

# Implement code to save run edits to the database

# You should update the database records with the edited run details

22
return redirect(url_for('view_runs', driver_id=driver_id, course_id=course_id))

Overall Results Calculation

PYTHON 09

def calculate_overall_result(driver_id):

driver = next((d for d in drivers if d['id'] == driver_id), None)

if driver:

overall_result = 0 # Initialize” “the overall result

for course in courses:

# Implement logic to calculate the driver's best run for each course

run1_time = 0 # Retrieve the driver's run1_time for the course

run2_time = 0 # Retrieve the driver's run2_time for the course

best_run_time = min(run1_time, run2_time) # Calculate the best run time

overall_result += best_run_time # Add the best run time to the overall result

return overall_result

# Route to display overall results

@app.route('/overallresults')

def overall_results():

results = []

for driver in drivers:

result = calculate_overall_result(driver['id'])

results.append({"driver" driver, "result" result})

results.sort(key=lambda x x['result'])

return” “render_template('overallresults.html', results=results)

23
Overall Results Template

HTML 07

<!DOCTYPE html>

<html>

<head>

<title>Overall Results</title>

</head>

<body>

<h1>Overall Results</h1>

<table>

<tr>

<th>Driver Name</th>

<th>Car Model</th>

<th>Overall Result</th>

</tr>

{% for result in results %}

<tr>

<td>{{ result.driver.first_name }} {{ result.driver.last_name }}</td>

<td>{{ result.driver.car_model }}</td>

<td>{{ result.result }}</td>

</tr>

{% endfor %}

</table>

</body>

24
</html>

Driver Search

PYTHON 10

# Driver search route

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

def search_drivers():

if request.method == 'POST':

search_term = request.form.get('search_term')

search_results = []

for driver in drivers:

if search_term.lower() in driver” “['first_name'].lower() or search_term.lower() in


driver['last_name'].lower():

search_results.append(driver)

return render_template('searchresults.html', search_results=search_results)

return render_template('search.html')

HTML 08

<!DOCTYPE html>

<html>

<head>

<title>Search Results</title>

</head>

<body>

25
<h1>Search Results</h1>

<ul>

{% for result in search_results %}

<li>

<a href="{{ url_for('view_runs', driver_id=result['id'],


course_id='A') }}">{{ result['first_name'] }} {{ result['last_name'] }}</a>

</li>

{% endfor %}

</ul>

</body>

</html>

Junior Driver Management

PYTHON 11

# Junior driver management route

@app.route('/managejuniors/<int:driver_id>', methods=['GET', 'POST'])

def manage_juniors(driver_id):

driver = next((d for d in drivers if d['id'] == driver_id), None)

if driver:

if request.method == 'POST':

is_junior = request.form.get('is_junior') == 'on'

if is_junior:

date_of_birth = request.form.get('date_of_birth')

# Calculate age

# Implement code to assign a caregiver to the junior driver

26
else:

# Remove junior-related information

pass

return redirect(url_for('driver_list'))

return render_template('managejuniors.html', driver=driver)

else:

return "Driver not found"

HTML 09

<!DOCTYPE html>

<html>

<head>

<title>Manage Junior Driver</title>

</head>

<body>

<h1>Manage” “Junior Driver</h1>

<h2>Driver {{ driver.first_name }} {{ driver.last_name }}</h2>

<form method="post">

<label for="is_junior">Is Junior:</label>

<input type="checkbox" name="is_junior" checked> <!-- Check if driver is a junior -->

<label for="date_of_birth">Date of Birth:</label>

<input type="text" name="date_of_birth" value="{{ driver.date_of_birth }}">

<!-- Implement caregiver-related fields here -->

27
<button type="submit">Save</button>

</form>

</body>

</html>

Access and Admin Functionality

Navigation

HTML 10

<!-- navigation.html -->

<nav>

<ul>

<li><a href="{{ url_for('driver_list') }}">Driver List</a></li>

<li><a href="{{ url_for('list_courses') }}">List of Courses</a></li>

<li><a href="{{ url_for('overall_results') }}">Overall Results</a></li>

<li><a href="{{ url_for('search') }}">Driver Search</a></li>

</ul>

</nav>

<!DOCTYPE html>

<html>

<head>

<title>{% block title %}Motorkhana Web App{% endblock %}</title>

</head>

<body>

{% include 'navigation.html' %}

{% block content %}{% endblock %}

28
</body>

</html>

CSS STYLING

/* styles.css */

body {

font-family Arial, sans-serif;

background-color #f5f5f5;

margin 0;

padding 0;

nav {

background-color #333;

color #fff;

padding 10px;

nav ul {

list-style none;

nav ul li {

display inline;

29
margin-right 20px;

nav a {

text-decoration none;

color #fff;

.container {

margin 20px;

padding 20px;

background-color #fff;

box-shadow 0 0 5px rgba(0, 0, 0, 0.2);

table {

width 100%;

border-collapse collapse;

table, th, td {

border 1px solid #ccc;

30
th, td {

padding 10px;

text-align left;

<link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='styles.css') }}">

User Authentication

pip install Flask-Login

PYTHON 11

from flask import” “Flask, render_template, request, redirect, url_for, flash

from flask_login import LoginManager, login_user, login_required, current_user, UserMixin,


logout_user

app = Flask(__name__)

app.secret_key = 'your_secret_key_here' # Change this to a random, secret key

login_manager = LoginManager()

login_manager.init_app(app)

class User(UserMixin):

def __init__(self, user_id):

self.id = user_id

# User data (for demo” “purposes)

users = {

1 {'username' 'admin', 'password' 'password'},

31
@login_manager.user_loader

def load_user(user_id):

return User(user_id)

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

def login():

if request.method == 'POST':

username = request.form.get('username')

password = request.form.get('password')

for user_id, user_data in users.items():

if user_data['username'] == username and user_data['password'] == password:

user = User(user_id)

login_user(user)

flash('Logged in successfully!', 'success')

return redirect(url_for('admin_home'))

flash('Login failed. Check your credentials.', 'danger')

return render_template('login.html')

@app.route('/logout')

@login_required

def logout():

logout_user()

flash('Logged out successfully!', 'success')

32
return redirect(url_for('login'))

@app.route('/admin')

@login_required

def admin_home():

# Admin home page

return render_template('admin_home.html')

Error Handling

PYTHON 12

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

def add_driver():

try:

# Attempt to add a new” “driver to the database

# ...

flash('Driver added successfully', 'success')

return redirect(url_for('driver_list'))

except Exception as e:

flash('An error occurred” “while adding the driver. Please try again.', 'danger')

return redirect(url_for('driver_list'))

Data Visualization

HTML 11

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

33
<canvas id="resultChart" width="400" height="200"></canvas>

<script>

var ctx = document.getElementById('resultChart').getContext('2d');

var myChart = new Chart(ctx, {

type 'bar',

data {

labels ['Driver 1', 'Driver 2', 'Driver 3', 'Driver 4', 'Driver 5'],

datasets [{

label 'Overall Results',

data [50, 60, 40, 55, 70], // Replace with actual data

backgroundColor 'rgba(75, 192, 192, 0.2)',

borderColor 'rgba(75, 192, 192, 1)',

borderWidth 1

}]

},

options {

scales {

y{

beginAtZero true

});

</script>

34
PYTHON 13

@app.route('/overall_results')

def overall_results():

# Retrieve data for top 5 drivers and pass it to the template

top_drivers = [

{'name' 'Driver 1', 'result' 50},

{'name' 'Driver 2', 'result' 60},

{'name' 'Driver 3', 'result' 40},

{'name' 'Driver 4', 'result' 55},

{'name' 'Driver 5', 'result' 70}

return render_template('overall_results.html', top_drivers=top_drivers)”

Export to CSV

PYTHON 14

import “csv

from flask import Response

@app.route('/export_to_csv')

def export_to_csv():

# Generate CSV data

data = [['Driver ID', 'Name', 'Overall Result'],

['101', 'Driver 1', '48'],

['102', 'Driver 2', '55'],

['103', 'Driver 3', '60']]

35
# Create a CSV response

output = io.StringIO()

writer = csv.writer(output)

writer.writerows(data)

response = Response(output.getvalue(), content_type='text/csv')

response.headers['Content-Disposition'] = 'attachment; filename=results.csv'

return response

from flask_paginate import Pagination

# Define a pagination object in your route

pagination = Pagination(page=page, per_page=10, total=total, record_name='drivers')

# Pass the pagination object to the template

return render_template('driver_list.html', drivers=drivers, pagination=pagination)

@app.route('/search_drivers')

def search_drivers():

search_term = request.args.get('search_term')

# Perform a database query to find drivers matching the search term

# ...

36
return render_template('driver_list.html', drivers=filtered_drivers)

from reportlab.pdfgen import canvas

@app.route('/export_to_pdf')

def export_to_pdf():

# Generate a PDF document with driver data

c = canvas.Canvas('driver_results.pdf')

# Add content to the PDF (e.g., driver details)

c.showPage()

c.save()

# Serve the generated PDF for download

return send_file('driver_results.pdf', as_attachment=True”)

37
Reference List

Bibliography

Irmayanti, I., 2023. Perancangan Sistem Informasi Penyewaan Thermoking Pada PT. Modern Prima
Transportasi Menggunakan Python Dengan Framework Flask. Jurnal Sistem dan Teknologi Informasi
Cendekia (JuSTICe), 1(1), pp.24-34.

Santoso, B.B. and Saian, P.O.N., 2023. Implementasi Flask Framework pada Development Modul
Reporting Aplikasi Sistem Informasi Helpdesk di PT. XYZ. Jurnal JTIK (Jurnal Teknologi Informasi
dan Komunikasi), 7(2), pp.217-226.

Ukpongson, M.P., 2023. REST API for a store management system using Flask.

Bagastio, K., Oetama, R.S. and Ramadhan, A., 2023. Development of stock price prediction system
using Flask framework and LSTM algorithm. Journal of Infrastructure, Policy and Development, 7(3).

Li, H., 2023, June. The Construction of Internal Tax Audit System of Private Enterprises Based on
Python. In Proceedings of the 2nd International Conference on Big Data Economy and Digital
Management, BDEDM 2023, January 6-8, 2023, Changsha, China.

Ablahd, A.Z., 2023. Using Python to Detect Web application vulnerability. resmilitaris, 13(2),
pp.1045-1058.

Jiwar, Z. and Othman, Z., 2023. Sidr tree disease diagnosis system Python programming. Iraqi
Journal of Intelligent Computing and Informatics (IJICI), 2(1), pp.26-35.

Gumarova, A., Kamalova, G. and Kustanova, М., 2023. PYTHON IS A HIGH-LEVEL


PROGRAMMING LANGUAGE. Ғылым, зерттеулер, білім беру: даму үрдістері: ХХІІІ
халықаралық ғылыми-практ. конф. материалдары= Science, research, education: development
trends: The materials of the XXIII international scientific and practical conf.= Наука, исследования,
образование: тенденции развития: мат. ХХІІІ междунар. науч.-практ. конф.(Уральск, 14 апреля
2023 г.)/ЗКАТУ им. Жангир хана//Ғылым және білім= Наука и образование= Science and
education.-2023.-№ 2 (71): прил. к журналу№ 3..

Budianto, A.J. and Saian, P.O.N., 2023. Pengembangan Modul Inventory Management pada Aplikasi
Master Distribution Centre System Menggunakan Framework Flask di PT XYZ. Jurnal JTIK (Jurnal
Teknologi Informasi dan Komunikasi), 7(2), pp.201-207.

Nilsson, E. and Demir, D., 2023. Performance comparison of REST vs GraphQL in different web
environments: Node. js and Python.

38
Ningrum, A.S. and Utami, A.W., 2023. One-Syllable Hangul Script Handwriting Detection System
Using Convolutional Neural Network (CNN) Method Based on Flask Framework. Journal of
Emerging Information System and Business Intelligence (JEISBI), 4(4), pp.9-16.

39

You might also like