Improve the following codebase;

"from flask import Flask, render_template_string, redirect, url_for, flash, request
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager, UserMixin, login_user, login_required, logout_user, current_user
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, SubmitField, FloatField, IntegerField, SelectMultipleField
from wtforms.validators import DataRequired, Length, EqualTo, ValidationError
import math
from werkzeug.security import generate_password_hash, check_password_hash

app = Flask(__name__)
app.config['SECRET_KEY'] = 'replace_with_a_secure_random_key'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///vapes.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
login_manager = LoginManager(app)
login_manager.login_view = 'login'

# Database Models
class User(UserMixin, db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(150), nullable=False, unique=True)
    password = db.Column(db.String(150), nullable=False)

class Vape(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    brand = db.Column(db.String(100), nullable=False)
    model = db.Column(db.String(100), nullable=False)
    flavor = db.Column(db.String(100), nullable=False)
    nicotine_strength = db.Column(db.Float, nullable=False)
    e_juice_capacity = db.Column(db.Float, nullable=False)
    battery_capacity = db.Column(db.Integer, nullable=False)
    watts = db.Column(db.Float, nullable=False)
    coil_resistance = db.Column(db.Float, nullable=False)
    lpfo = db.Column(db.Float, nullable=False)

    @property
    def true_puffs(self):
        return 3000 * math.exp(-0.03 * self.watts) * self.e_juice_capacity

    @property
    def puffs_per_penny(self):
        return self.true_puffs / self.lpfo if self.lpfo else 0

# Forms
class RegistrationForm(FlaskForm):
    username = StringField('Username', validators=[DataRequired(), Length(min=4, max=150)])
    password = PasswordField('Password', validators=[DataRequired(), Length(min=6)])
    confirm = PasswordField('Confirm Password', validators=[DataRequired(), EqualTo('password')])
    submit = SubmitField('Register')
    def validate_username(self, username):
        if User.query.filter_by(username=username.data).first():
            raise ValidationError('Username already exists.')

class LoginForm(FlaskForm):
    username = StringField('Username', validators=[DataRequired(), Length(min=4, max=150)])
    password = PasswordField('Password', validators=[DataRequired()])
    submit = SubmitField('Login')

# User Loader
@login_manager.user_loader
def load_user(user_id):
    return User.query.get(int(user_id))

# Routes
@app.route('/')
def home():
    search = request.args.get('search', '')
    brand = request.args.get('brand', '')
    flavor = request.args.get('flavor', '')
    sort = request.args.get('sort', '')
    vapes = Vape.query
    if search:
        vapes = vapes.filter((Vape.brand.ilike(f'%{search}%')) | (Vape.model.ilike(f'%{search}%')) | (Vape.flavor.ilike(f'%{search}%')))
    if brand:
        vapes = vapes.filter_by(brand=brand)
    if flavor:
        vapes = vapes.filter_by(flavor=flavor)
    if sort:
        if sort in ['true_puffs', 'puffs_per_penny', 'lpfo']:
            vapes = vapes.order_by(getattr(Vape, sort).desc())
    vapes = vapes.all()
    brands = Vape.query.with_entities(Vape.brand).distinct()
    flavors = Vape.query.with_entities(Vape.flavor).distinct()
    return render_template_string(home_template, vapes=vapes, brands=brands, flavors=flavors)

@app.route('/vape/<int:vape_id>')
def vape_detail(vape_id):
    vape = Vape.query.get_or_404(vape_id)
    return render_template_string(detail_template, vape=vape)

@app.route('/compare', methods=['GET', 'POST'])
def compare():
    vape_ids = request.args.getlist('vapes')
    if len(vape_ids) < 2:
        flash('Please select at least two vapes to compare.', 'warning')
        return redirect(url_for('home'))
    vapes = Vape.query.filter(Vape.id.in_(vape_ids)).all()
    return render_template_string(compare_template, vapes=vapes)

@app.route('/register', methods=['GET', 'POST'])
def register():
    form = RegistrationForm()
    if form.validate_on_submit():
        hashed = generate_password_hash(form.password.data)
        user = User(username=form.username.data, password=hashed)
        db.session.add(user)
        db.session.commit()
        flash('Registration successful. You can now log in.', 'success')
        return redirect(url_for('login'))
    return render_template_string(register_template, form=form)

@app.route('/login', methods=['GET', 'POST'])
def login():
    form = LoginForm()
    if form.validate_on_submit():
        user = User.query.filter_by(username=form.username.data).first()
        if user and check_password_hash(user.password, form.password.data):
            login_user(user)
            flash('Logged in successfully.', 'success')
            return redirect(url_for('home'))
        else:
            flash('Invalid username or password.', 'danger')
    return render_template_string(login_template, form=form)

@app.route('/logout')
@login_required
def logout():
    logout_user()
    flash('Logged out successfully.', 'info')
    return redirect(url_for('home'))

# Templates
home_template = '''
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Puffs Per Penny</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
    <a class="navbar-brand" href="{{ url_for('home') }}">Puffs Per Penny</a>
    <div class="collapse navbar-collapse">
        <ul class="navbar-nav ml-auto">
            {% if current_user.is_authenticated %}
                <li class="nav-item"><a class="nav-link" href="#">Hello, {{ current_user.username }}</a></li>
                <li class="nav-item"><a class="nav-link" href="{{ url_for('logout') }}">Logout</a></li>
            {% else %}
                <li class="nav-item"><a class="nav-link" href="{{ url_for('login') }}">Login</a></li>
                <li class="nav-item"><a class="nav-link" href="{{ url_for('register') }}">Register</a></li>
            {% endif %}
        </ul>
    </div>
</nav>
<div class="container mt-4">
    {% with messages = get_flashed_messages(with_categories=true) %}
      {% if messages %}
        {% for category, message in messages %}
          <div class="alert alert-{{ category }} alert-dismissible fade show" role="alert">
            {{ message }}
            <button type="button" class="close" data-dismiss="alert">&times;</button>
          </div>
        {% endfor %}
      {% endif %}
    {% endwith %}
    <h1 class="mb-4">Vape Catalog</h1>
    <form method="get" class="form-inline mb-4">
        <input type="text" name="search" class="form-control mr-2" placeholder="Search..." value="{{ request.args.get('search','') }}">
        <select name="brand" class="form-control mr-2">
            <option value="">All Brands</option>
            {% for b in brands %}
                <option value="{{ b.brand }}" {% if request.args.get('brand') == b.brand %}selected{% endif %}>{{ b.brand }}</option>
            {% endfor %}
        </select>
        <select name="flavor" class="form-control mr-2">
            <option value="">All Flavors</option>
            {% for f in flavors %}
                <option value="{{ f.flavor }}" {% if request.args.get('flavor') == f.flavor %}selected{% endif %}>{{ f.flavor }}</option>
            {% endfor %}
        </select>
        <select name="sort" class="form-control mr-2">
            <option value="">Sort By</option>
            <option value="true_puffs" {% if request.args.get('sort') == 'true_puffs' %}selected{% endif %}>True Puffs</option>
            <option value="puffs_per_penny" {% if request.args.get('sort') == 'puffs_per_penny' %}selected{% endif %}>Puffs Per Penny</option>
            <option value="lpfo" {% if request.args.get('sort') == 'lpfo' %}selected{% endif %}>Lowest Price Found Online</option>
        </select>
        <button type="submit" class="btn btn-primary">Filter</button>
    </form>
    <form method="get" action="{{ url_for('compare') }}">
        <div class="form-group">
            <label for="vapes">Select Vapes to Compare:</label>
            <select multiple class="form-control" id="vapes" name="vapes">
                {% for vape in vapes %}
                    <option value="{{ vape.id }}">{{ vape.brand }} {{ vape.model }}</option>
                {% endfor %}
            </select>
        </div>
        <button type="submit" class="btn btn-secondary">Compare Selected</button>
    </form>
    <div class="row mt-4">
        {% for vape in vapes %}
            <div class="col-md-4">
                <div class="card mb-4">
                    <div class="card-body">
                        <h5 class="card-title">{{ vape.brand }} {{ vape.model }}</h5>
                        <p class="card-text"><strong>Flavor:</strong> {{ vape.flavor }}</p>
                        <p class="card-text"><strong>Nicotine:</strong> {{ vape.nicotine_strength }} mg</p>
                        <p class="card-text"><strong>PPPP:</strong> {{ vape.puffs_per_penny|round(2) }}</p>
                        <a href="{{ url_for('vape_detail', vape_id=vape.id) }}" class="btn btn-info btn-sm">View Details</a>
                    </div>
                </div>
            </div>
        {% endfor %}
    </div>
</div>
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script>
</body>
</html>
'''

detail_template = '''
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>{{ vape.brand }} {{ vape.model }} - Details</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
    <a class="navbar-brand" href="{{ url_for('home') }}">Puffs Per Penny</a>
    <div class="collapse navbar-collapse">
        <ul class="navbar-nav ml-auto">
            {% if current_user.is_authenticated %}
                <li class="nav-item"><a class="nav-link" href="#">Hello, {{ current_user.username }}</a></li>
                <li class="nav-item"><a class="nav-link" href="{{ url_for('logout') }}">Logout</a></li>
            {% else %}
                <li class="nav-item"><a class="nav-link" href="{{ url_for('login') }}">Login</a></li>
                <li class="nav-item"><a class="nav-link" href="{{ url_for('register') }}">Register</a></li>
            {% endif %}
        </ul>
    </div>
</nav>
<div class="container mt-4">
    <h2>{{ vape.brand }} {{ vape.model }}</h2>
    <ul class="list-group">
        <li class="list-group-item"><strong>Flavor:</strong> {{ vape.flavor }}</li>
        <li class="list-group-item"><strong>Nicotine Strength:</strong> {{ vape.nicotine_strength }} mg</li>
        <li class="list-group-item"><strong>E Juice Capacity:</strong> {{ vape.e_juice_capacity }} ml</li>
        <li class="list-group-item"><strong>Battery Capacity:</strong> {{ vape.battery_capacity }} mAh</li>
        <li class="list-group-item"><strong>Watts:</strong> {{ vape.watts }}</li>
        <li class="list-group-item"><strong>Coil Resistance:</strong> {{ vape.coil_resistance }} Ω</li>
        <li class="list-group-item"><strong>Lowest Price Found Online (LPFO):</strong> ${{ vape.lpfo }}</li>
        <li class="list-group-item"><strong>True Puffs:</strong> {{ vape.true_puffs|round(2) }}</li>
        <li class="list-group-item"><strong>Puffs Per Penny:</strong> {{ vape.puffs_per_penny|round(2) }}</li>
    </ul>
    <a href="{{ url_for('compare') }}?vapes={{ vape.id }}" class="btn btn-secondary mt-3">Compare This Vape</a>
    <a href="{{ url_for('home') }}" class="btn btn-primary mt-3">Back to Catalog</a>
</div>
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script>
</body>
</html>
'''

compare_template = '''
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Compare Vapes</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
    <a class="navbar-brand" href="{{ url_for('home') }}">Puffs Per Penny</a>
    <div class="collapse navbar-collapse">
        <ul class="navbar-nav ml-auto">
            {% if current_user.is_authenticated %}
                <li class="nav-item"><a class="nav-link" href="#">Hello, {{ current_user.username }}</a></li>
                <li class="nav-item"><a class="nav-link" href="{{ url_for('logout') }}">Logout</a></li>
            {% else %}
                <li class="nav-item"><a class="nav-link" href="{{ url_for('login') }}">Login</a></li>
                <li class="nav-item"><a class="nav-link" href="{{ url_for('register') }}">Register</a></li>
            {% endif %}
        </ul>
    </div>
</nav>
<div class="container mt-4">
    <h2>Compare Vapes</h2>
    <table class="table table-bordered">
        <thead>
            <tr>
                <th>Attribute</th>
                {% for vape in vapes %}
                    <th>{{ vape.brand }} {{ vape.model }}</th>
                {% endfor %}
            </tr>
        </thead>
        <tbody>
            <tr>
                <td>Flavor</td>
                {% for vape in vapes %}
                    <td>{{ vape.flavor }}</td>
                {% endfor %}
            </tr>
            <tr>
                <td>Nicotine Strength (mg)</td>
                {% for vape in vapes %}
                    <td>{{ vape.nicotine_strength }}</td>
                {% endfor %}
            </tr>
            <tr>
                <td>E Juice Capacity (ml)</td>
                {% for vape in vapes %}
                    <td>{{ vape.e_juice_capacity }}</td>
                {% endfor %}
            </tr>
            <tr>
                <td>Battery Capacity (mAh)</td>
                {% for vape in vapes %}
                    <td>{{ vape.battery_capacity }}</td>
                {% endfor %}
            </tr>
            <tr>
                <td>Watts</td>
                {% for vape in vapes %}
                    <td>{{ vape.watts }}</td>
                {% endfor %}
            </tr>
            <tr>
                <td>Coil Resistance (Ω)</td>
                {% for
"