Hospital Management system using Python and Flask

Rashmi Mishra
0

HOSPITAL MANAGEMENT SYSTEM 

USING PYTHON and FLASK


Here’s a step-by-step guide to help you get started from the ground up, focusing on building a patient registration feature with a user/customer and admin panel.

Step 1: Set Up Your Development Environment

  1. Install Python: Make sure you have Python installed. You can download it from the official website.
  2. Install Virtual Environment:

                                       pip install virtualenv

  1. Create a Virtual Environment:

                                       mkdir hospital_management_system

                                       cd hospital_management_system

                                       virtualenv venv

  1. Activate the Virtual Environment:
    • On Windows:

                                       venv\Scripts\activate

    • On macOS/Linux:

                                       source venv/bin/activate

Step 2: Install Required Packages

You will need to install several packages, including Flask and Flask-SQLAlchemy for database management.

pip install Flask Flask-WTF Flask-SQLAlchemy Flask-Migrate Flask-Login

Step 3: Set Up the Minimum Project Structure

Create the following project structure:

hospital_management_system/

── app/

   ── __init__.py

   ── models/

      └── __init__.py

   ── forms/

      └── __init__.py

   ── routes/

      └── __init__.py

   ── templates/

      ── base.html

      ── auth/

         └── register.html

   ── static/

      └── css/

   └── config.py

── run.py

└── venv/

Step 4: Initialize the Flask App

Create the __init__.py file inside the app/ directory:

__init__.py

# app/__init__.py

from flask import Flask

from flask_sqlalchemy import SQLAlchemy

from flask_migrate import Migrate

from config import Config

app = Flask(__name__)

app.config.from_object(Config)

db = SQLAlchemy(app)

migrate = Migrate(app, db)

 

from app.routes import *

Step 5: Create a Configuration File

Create a configuration file config.py in the app/ directory:

config.py

# app/config.py

import os

class Config:

    SECRET_KEY = os.environ.get('SECRET_KEY') or 'your_secret_key'

    SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL') or 'sqlite:///site.db'

    SQLALCHEMY_TRACK_MODIFICATIONS = False

Step 6: Define the Patient Model

Create the models.py file inside the models/ directory:

# app/models/__init__.py

from app import db

from datetime import datetime

class Patient(db.Model):

    id = db.Column(db.Integer, primary_key=True)

    full_name = db.Column(db.String(50), nullable=False)

    email = db.Column(db.String(120), unique=True, nullable=False)

    password = db.Column(db.String(60), nullable=False)

    date_of_birth = db.Column(db.Date, nullable=False)

    gender = db.Column(db.String(10), nullable=False)

    created_at = db.Column(db.DateTime, default=datetime.utcnow)

 

    def __repr__(self):

        return f"Patient('{self.full_name}', '{self.email}', '{self.date_of_birth}')"

Step 7: Create the Registration Form

Create the patient_form.py file inside the forms/ directory:

# app/forms/__init__.py

from flask_wtf import FlaskForm

from wtforms import StringField, PasswordField, EmailField, SubmitField, SelectField, DateField

from wtforms.validators import DataRequired, Email, Length, EqualTo

class PatientRegistrationForm(FlaskForm):

    full_name = StringField('Full Name', validators=[DataRequired(), Length(min=2, max=50)])

    email = EmailField('Email', validators=[DataRequired(), Email()])

    password = PasswordField('Password', validators=[DataRequired(), Length(min=6, max=30)])

    confirm_password = PasswordField('Confirm Password', validators=[DataRequired(), EqualTo('password')])

    date_of_birth = DateField('Date of Birth', format='%Y-%m-%d', validators=[DataRequired()])

    gender = SelectField('Gender', choices=[('Male', 'Male'), ('Female', 'Female'), ('Other', 'Other')], validators=[DataRequired()])

    submit = SubmitField('Register')

Step 8: Create Routes for Registration

Create the routes.py file inside the routes/ directory:

routes.py

# app/routes/__init__.py

from flask import render_template, redirect, url_for, flash

from app import app, db

from app.forms import PatientRegistrationForm

from app.models import Patient  # Import your Patient model

from werkzeug.security import generate_password_hash

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

def register():

    form = PatientRegistrationForm()

    if form.validate_on_submit():

        new_patient = Patient(

            full_name=form.full_name.data,

            email=form.email.data,

            password=generate_password_hash(form.password.data),  # Hash the password

            date_of_birth=form.date_of_birth.data,

            gender=form.gender.data

        )

        db.session.add(new_patient)

        db.session.commit()

        flash('Your account has been created! You can now log in.', 'success')

        return redirect(url_for('login'))  # Redirect to login page

     return render_template('auth/register.html', form=form)

Step 9: Create HTML Templates

Create the base template base.html in the templates/ directory:

<!-- app/templates/base.html -->

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

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

    <title>Hospital Management System</title>

</head>

<body>

    <nav>

        <ul>

            <li><a href="{{ url_for('register') }}">Register</a></li>

            <li><a href="{{ url_for('login') }}">Login</a></li>

        </ul>

    </nav>

   

    <div class="container">

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

            {% if messages %}

                <div class="alert alert-dismissible fade show" role="alert">

                    {% for category, message in messages %}

                        <div class="alert alert-{{ category }}">{{ message }}</div>

                    {% endfor %}

                </div>

            {% endif %}

        {% endwith %}

       

        {% block content %}{% endblock %}

    </div>

</body>

</html>

Create the registration template register.html in the templates/auth/ directory:

<!-- app/templates/auth/register.html -->

{% extends 'base.html' %}

{% block content %}

<h2>Patient Registration</h2>

<form method="POST" action="{{ url_for('register') }}">

    {{ form.hidden_tag() }}

    <div>

        {{ form.full_name.label() }}

        {{ form.full_name() }}

        {% if form.full_name.errors %}

            <div>{{ form.full_name.errors[0] }}</div>

        {% endif %}

    </div>

    <div>

        {{ form.email.label() }}

        {{ form.email() }}

        {% if form.email.errors %}

            <div>{{ form.email.errors[0] }}</div>

        {% endif %}

    </div>

    <div>

        {{ form.password.label() }}

        {{ form.password() }}

        {% if form.password.errors %}

            <div>{{ form.password.errors[0] }}</div>

        {% endif %}

    </div>

    <div>

        {{ form.confirm_password.label() }}

        {{ form.confirm_password() }}

        {% if form.confirm_password.errors %}

            <div>{{ form.confirm_password.errors[0] }}</div>

        {% endif %}

    </div>

    <div>

        {{ form.date_of_birth.label() }}

        {{ form.date_of_birth() }}

        {% if form.date_of_birth.errors %}

            <div>{{ form.date_of_birth.errors[0] }}</div>

        {% endif %}

    </div>

    <div>

        {{ form.gender.label() }}

        {{ form.gender() }}

        {% if form.gender.errors %}

            <div>{{ form.gender.errors[0] }}</div>

        {% endif %}

    </div>

 

    <div>

        {{ form.submit() }}

    </div>

</form>

{% endblock %}

Step 10: Set Up the Database

  1. Initialize the Database: Open a Python shell in your project directory and run:

from app import db

db.create_all()

Step 11: Create the Entry Point

Create the run.py file in the project root:

run.py

# run.py

from app import app

 

if __name__ == '__main__':

    app.run(debug=True)

Step 12: Run the Application

Start your Flask application by running:

python run.py

Step 13: Test the Registration

  1. Open your web browser and go to http://127.0.0.1:5000/register.
  2. Fill out the registration form and submit it.

Step 14: Next Steps

After successfully implementing the patient registration feature, you can expand the project by adding:

  1. Login and Authentication: Implement a login feature using Flask-Login.
  2. Admin Panel: Create an admin panel to manage patients.
  3. Appointment Scheduling: Allow patients to schedule appointments.
  4. Data Visualization: Implement data visualization for patient statistics.
  5. Testing: Write unit tests for your application.

Conclusion

 

 

Here's the final project structure for a Hospital Management System in Python using Flask. This structure includes user/customer and admin panels, along with various components for managing patients, appointments, and more.

Final Project Structure

hospital_management_system/

── app/

   ── __init__.py              # Initialize the Flask app

   ── config.py                # Configuration settings

   ── models/                   # Database models

      ── __init__.py

      ── patient.py            # Patient model

      ── admin.py              # Admin model (if needed)

      └── appointment.py        # Appointment model

   ── forms/                    # Forms for user input

      ── __init__.py

      ── registration_form.py   # Patient registration form

      ── login_form.py          # User login form

      └── appointment_form.py     # Appointment form

   ── routes/                   # Routes for the application

      ── __init__.py

      ── auth.py               # Authentication routes (register, login)

      ── patient.py            # Patient management routes

      └── admin.py              # Admin management routes

   ── templates/                # HTML templates

      ── base.html             # Base layout template

      ── auth/                 # Authentication templates

         ── register.html      # Registration page

         ── login.html         # Login page

      ── patient/              # Patient templates

         ── dashboard.html      # Patient dashboard

         ── view_appointments.html # View appointments

         └── book_appointment.html  # Book appointment page

      └── admin/                # Admin templates

          ── dashboard.html      # Admin dashboard

          └── manage_patients.html # Manage patients page

   ── static/                   # Static files (CSS, JS, images)

      ── css/                  # CSS files

      ── js/                   # JavaScript files

      └── images/               # Images

   └── utils/                    # Utility functions (if any)

       └── __init__.py

── migrations/                   # Database migration files (created by Flask-Migrate)

── venv/                         # Virtual environment directory

── run.py                        # Entry point to run the application

└── requirements.txt              # List of dependencies

Description of Each Component

  • app/: This is the main application directory that contains all the application logic.
    • __init__.py: Initializes the Flask application, database, and other configurations.
    • config.py: Configuration settings for the application, including database URI and secret keys.
    • models/: Contains the database models representing different entities in the system.
      • patient.py: Defines the Patient model with attributes like full_name, email, password, etc.
      • admin.py: Defines the Admin model if you have separate admin functionalities.
      • appointment.py: Defines the Appointment model with details about appointments.
    • forms/: Contains the forms used for user input and data submission.
      • registration_form.py: The form used for patient registration.
      • login_form.py: The form used for patient login.
      • appointment_form.py: The form used to book appointments.
    • routes/: Contains the route handlers for different functionalities.
      • auth.py: Handles routes for authentication like registration and login.
      • patient.py: Handles routes related to patient management, such as viewing and booking appointments.
      • admin.py: Handles routes for admin functionalities like managing patients.
    • templates/: Contains HTML templates for rendering views.
      • base.html: A base template that can be extended by other templates.
      • auth/: Templates related to authentication.
      • patient/: Templates for patient-related functionalities.
      • admin/: Templates for admin-related functionalities.
    • static/: Contains static files like CSS, JavaScript, and images.
    • utils/: Contains utility functions that can be reused across the application.
  • migrations/: Directory created by Flask-Migrate to handle database migrations.
  • venv/: The virtual environment directory where your project dependencies are installed.
  • run.py: The main entry point to run the Flask application.
  • requirements.txt: A file listing all the dependencies required for the project. You can create this file by running:

pip freeze > requirements.txt

Next Steps

With this structure in place, you can start implementing features such as:

  1. User Authentication: Implement login/logout functionality using Flask-Login.
  2. Patient Management: Allow patients to view and manage their profiles.
  3. Appointment Management: Implement functionalities for patients to book and view their appointments.
  4. Admin Panel: Create functionalities for the admin to manage patients and appointments.

Final Notes

This project structure is a starting point and can be further modified based on your specific requirements or additional features you wish to implement. Good luck with your Hospital Management System project!


app/__init__.py


Here’s a basic implementation of the __init__.py file for the app folder in your Hospital Management System project using Flask. This file is crucial for initializing the Flask application, setting up the database, and registering the blueprints for different modules.

app/__init__.py

from flask import Flask

from flask_sqlalchemy import SQLAlchemy

from flask_migrate import Migrate

from flask_login import LoginManager

from app.config import Config

 

# Initialize extensions

db = SQLAlchemy()

migrate = Migrate()

login_manager = LoginManager()

 

def create_app():

    # Create the Flask app

    app = Flask(__name__)

    app.config.from_object(Config)

 

    # Initialize extensions

    db.init_app(app)

    migrate.init_app(app, db)

    login_manager.init_app(app)

 

    # Register blueprints

    from app.routes.auth import auth as auth_blueprint

    from app.routes.patient import patient as patient_blueprint

    from app.routes.admin import admin as admin_blueprint

 

    app.register_blueprint(auth_blueprint)

    app.register_blueprint(patient_blueprint)

    app.register_blueprint(admin_blueprint)

 

    # Set the login_view for the LoginManager

    login_manager.login_view = 'auth.login'

 

    return app

Explanation of the Code

  • Imports: The necessary modules and classes are imported:
    • Flask: The core Flask class for creating the application.
    • SQLAlchemy: An ORM for database operations.
    • Migrate: A tool for handling database migrations.
    • LoginManager: A Flask extension for managing user sessions and authentication.
    • Config: A custom configuration class that contains application settings.
  • Extension Initialization:
    • db: Initialized for handling database interactions.
    • migrate: Initialized for managing database migrations.
    • login_manager: Initialized for managing user authentication.
  • create_app() Function:
    • Creates a new Flask application instance.
    • Loads the configuration from the Config class.
    • Initializes the database and migration manager with the app.
    • Registers the blueprints for authentication, patient management, and admin functionalities.
  • Blueprint Registration:
    • The auth, patient, and admin blueprints are imported and registered with the app, allowing for modular organization of routes.
  • Login View Configuration:
    • Sets the login_view to the login route, which will redirect users to the login page when they attempt to access protected views.

Conclusion

This __init__.py file is a foundational part of your Flask application, allowing you to structure your code effectively and keep your project organized. As you implement more features, you may need to modify this file to accommodate additional extensions or configurations.

 

app/config.py

import os

class Config:
    # General configurations
    SECRET_KEY = os.environ.get('SECRET_KEY') or 'a_very_secret_key'

    # Database configuration for MySQL
    MYSQL_USER = os.environ.get('MYSQL_USER') or 'your_mysql_username'
    MYSQL_PASSWORD = os.environ.get('MYSQL_PASSWORD') or 'your_mysql_password'
    MYSQL_HOST = os.environ.get('MYSQL_HOST') or 'localhost'
    MYSQL_DB = os.environ.get('MYSQL_DB') or 'hospital_management'

    SQLALCHEMY_DATABASE_URI = f'mysql+pymysql://{MYSQL_USER}:{MYSQL_PASSWORD}@{MYSQL_HOST}/{MYSQL_DB}'
    SQLALCHEMY_TRACK_MODIFICATIONS = False

    # Flask-Login configurations
    LOGIN_MANAGER_LOGIN_VIEW = 'auth.login'
    LOGIN_MANAGER_LOGIN_MESSAGE = 'Please log in to access this page.'

 

app/

── models/

│   ── __init__.py

│   ── user.py

│   ── patient.py

│   ── appointment.py

│   ── doctor.py

│   └── admin.py

 

app/models/__init__.py

from flask_sqlalchemy import SQLAlchemy

# Initialize the SQLAlchemy instance
db = SQLAlchemy()

# Import models here to ensure they are registered with SQLAlchemy
from app.models.user import User
from app.models.patient import Patient
from app.models.appointment import Appointment
from app.models.doctor import Doctor
from app.models.admin import Admin
# Add more models as needed

def init_app(app):
    """Initialize the app with the SQLAlchemy instance."""
    db.init_app(app)


app/models/user.py

from app.models import db
from flask_login import UserMixin

class User(db.Model, UserMixin):
    __tablename__ = 'users'

    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(150), unique=True, nullable=False)
    email = db.Column(db.String(150), unique=True, nullable=False)
    password = db.Column(db.String(150), nullable=False)

    # Add additional fields and relationships as needed


app/models/patient.py

from app.models import db

class Patient(db.Model):
    __tablename__ = 'patients'

    id = db.Column(db.Integer, primary_key=True)
    first_name = db.Column(db.String(50), nullable=False)
    last_name = db.Column(db.String(50), nullable=False)
    email = db.Column(db.String(150), unique=True, nullable=False)
    phone = db.Column(db.String(15), nullable=False)
    address = db.Column(db.String(250), nullable=True)
    date_of_birth = db.Column(db.Date, nullable=False)
    gender = db.Column(db.String(10), nullable=False)
    medical_history = db.Column(db.Text, nullable=True)
    created_at = db.Column(db.DateTime, default=db.func.current_timestamp())
    updated_at = db.Column(db.DateTime, default=db.func.current_timestamp(), onupdate=db.func.current_timestamp())

    def __repr__(self):
        return f'<Patient {self.first_name} {self.last_name}>'


app/models/appointment.py


from app.models import db
from datetime import datetime

class Appointment(db.Model):
    __tablename__ = 'appointments'

    id = db.Column(db.Integer, primary_key=True)
    patient_id = db.Column(db.Integer, db.ForeignKey('patients.id'), nullable=False)
    doctor_id = db.Column(db.Integer, db.ForeignKey('doctors.id'), nullable=False)
    appointment_date = db.Column(db.DateTime, nullable=False)
    reason = db.Column(db.String(250), nullable=True)
    status = db.Column(db.String(20), default='Scheduled')  # e.g., Scheduled, Completed, Canceled
    created_at = db.Column(db.DateTime, default=db.func.current_timestamp())
    updated_at = db.Column(db.DateTime, default=db.func.current_timestamp(), onupdate=db.func.current_timestamp())

    # Relationships
    patient = db.relationship('Patient', backref='appointments')
    doctor = db.relationship('Doctor', backref='appointments')

    def __repr__(self):
        return f'<Appointment {self.id} | Patient: {self.patient_id} | Doctor: {self.doctor_id} | Date: {self.appointment_date}>'

app/models/doctor.py

from app.models import db

class Doctor(db.Model):
    __tablename__ = 'doctors'

    id = db.Column(db.Integer, primary_key=True)
    first_name = db.Column(db.String(50), nullable=False)
    last_name = db.Column(db.String(50), nullable=False)
    email = db.Column(db.String(150), unique=True, nullable=False)
    phone = db.Column(db.String(15), nullable=False)
    specialization = db.Column(db.String(100), nullable=False)
    experience_years = db.Column(db.Integer, nullable=False)
    created_at = db.Column(db.DateTime, default=db.func.current_timestamp())
    updated_at = db.Column(db.DateTime, default=db.func.current_timestamp(), onupdate=db.func.current_timestamp())

    # Relationships
    appointments = db.relationship('Appointment', backref='doctor')

    def __repr__(self):
        return f'<Doctor {self.first_name} {self.last_name} | Specialization: {self.specialization}>'

app/models/admin.py


from app.models import db

class Admin(db.Model):
    __tablename__ = 'admins'

    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(50), unique=True, nullable=False)
    password_hash = db.Column(db.String(128), nullable=False)
    email = db.Column(db.String(150), unique=True, nullable=False)
    created_at = db.Column(db.DateTime, default=db.func.current_timestamp())
    updated_at = db.Column(db.DateTime, default=db.func.current_timestamp(), onupdate=db.func.current_timestamp())

    def __repr__(self):
        return f'<Admin {self.username}>'

forms directory in your Hospital Management System project

app/forms/__init__.py

from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, IntegerField, DateTimeField, SelectField, TextAreaField
from wtforms.validators import DataRequired, Email, Length, Optional

# Importing specific forms
from .registration_form import RegistrationForm
from .login_form import LoginForm
from .appointment_form import AppointmentForm
from .doctor_form import DoctorForm
from .admin_form import AdminForm

__all__ = [
    'RegistrationForm',
    'LoginForm',
    'AppointmentForm',
    'DoctorForm',
    'AdminForm'
]



Below are basic structures for some of the form classes that might be included in your forms folder:

Registration Form (registration_form.py)

from flask_wtf import FlaskForm

from wtforms import StringField, PasswordField, EmailField

from wtforms.validators import DataRequired, Email, Length

 

class RegistrationForm(FlaskForm):

    username = StringField('Username', validators=[DataRequired(), Length(min=4, max=25)])

    email = EmailField('Email', validators=[DataRequired(), Email()])

    password = PasswordField('Password', validators=[DataRequired(), Length(min=6, max=35)])

Login Form (login_form.py)

from flask_wtf import FlaskForm

from wtforms import StringField, PasswordField

from wtforms.validators import DataRequired

 

class LoginForm(FlaskForm):

    username = StringField('Username', validators=[DataRequired()])

    password = PasswordField('Password', validators=[DataRequired()])

Appointment Form (appointment_form.py)

from flask_wtf import FlaskForm

from wtforms import DateTimeField, SelectField, TextAreaField

from wtforms.validators import DataRequired, Optional

 

class AppointmentForm(FlaskForm):

    patient_id = SelectField('Patient ID', coerce=int, validators=[DataRequired()])

    doctor_id = SelectField('Doctor ID', coerce=int, validators=[DataRequired()])

    appointment_date = DateTimeField('Appointment Date', validators=[DataRequired()])

    reason = TextAreaField('Reason', validators=[Optional()])

Doctor Form (doctor_form.py)

from flask_wtf import FlaskForm

from wtforms import StringField, IntegerField

from wtforms.validators import DataRequired, Length

 

class DoctorForm(FlaskForm):

    first_name = StringField('First Name', validators=[DataRequired(), Length(max=50)])

    last_name = StringField('Last Name', validators=[DataRequired(), Length(max=50)])

    specialization = StringField('Specialization', validators=[DataRequired(), Length(max=100)])

    experience_years = IntegerField('Years of Experience', validators=[DataRequired()])

Admin Form (admin_form.py)

from flask_wtf import FlaskForm

from wtforms import StringField, PasswordField, EmailField

from wtforms.validators import DataRequired, Email, Length

 

class AdminForm(FlaskForm):

    username = StringField('Username', validators=[DataRequired(), Length(max=50)])

    password = PasswordField('Password', validators=[DataRequired()])

    email = EmailField('Email', validators=[DataRequired(), Email()])

Conclusion

With this structure, the __init__.py file in your forms folder provides a clean way to manage and access various forms in your Hospital Management System. Each form can be easily imported from the forms package, promoting better organization and maintainability in your project.


routes directory in your Hospital Management System project

Here's the implementation of the __init__.py, auth.py, patient.py, and admin.py files for the routes directory in your Hospital Management System project.

1. __init__.py

The __init__.py file initializes the routes module and sets up the routes for your Flask application.

from flask import Blueprint

# Create a Blueprint for routes

routes = Blueprint('routes', __name__)

# Import the individual route modules

from .auth import *

from .patient import *

from .admin import *

2. auth.py

The auth.py file handles the authentication routes for user registration and login.

from flask import render_template, redirect, url_for, flash

from flask_login import login_user, logout_user, login_required

from app.forms import RegistrationForm, LoginForm

from app.models import User  # Assuming you have a User model defined

from app import db

from . import routes

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

def register():

    form = RegistrationForm()

    if form.validate_on_submit():

        # Create a new user and add to the database

        new_user = User(

            username=form.username.data,

            email=form.email.data,

            password_hash=generate_password_hash(form.password.data)

        )

        db.session.add(new_user)

        db.session.commit()

        flash('Registration successful! You can now log in.', 'success')

        return redirect(url_for('routes.login'))

    return render_template('register.html', form=form)

@routes.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_hash, form.password.data):

            login_user(user)

            flash('Login successful!', 'success')

            return redirect(url_for('routes.home'))  # Redirect to the home page

        else:

            flash('Login failed. Check your username and password.', 'danger')

    return render_template('login.html', form=form)

@routes.route('/logout')

@login_required

def logout():

    logout_user()

    flash('You have been logged out.', 'success')

    return redirect(url_for('routes.login'))

3. patient.py

The patient.py file manages routes related to patient operations, such as viewing patient details and adding new patients.

from flask import render_template, redirect, url_for, flash

from flask_login import login_required

from app.forms import PatientForm

from app.models import Patient  # Assuming you have a Patient model defined

from app import db

from . import routes

@routes.route('/patients', methods=['GET'])

@login_required

def view_patients():

    patients = Patient.query.all()

    return render_template('patients.html', patients=patients)

@routes.route('/patients/add', methods=['GET', 'POST'])

@login_required

def add_patient():

    form = PatientForm()

    if form.validate_on_submit():

        new_patient = Patient(

            name=form.name.data,

            age=form.age.data,

            gender=form.gender.data,

            contact=form.contact.data,

            address=form.address.data

        )

        db.session.add(new_patient)

        db.session.commit()

        flash('Patient added successfully!', 'success')

        return redirect(url_for('routes.view_patients'))

    return render_template('add_patient.html', form=form)

4. admin.py

The admin.py file contains routes for managing admin-related operations, such as viewing admin details and adding new admins.

from flask import render_template, redirect, url_for, flash

from flask_login import login_required

from app.forms import AdminForm

from app.models import Admin  # Assuming you have an Admin model defined

from app import db

from . import routes

 

@routes.route('/admins', methods=['GET'])

@login_required

def view_admins():

    admins = Admin.query.all()

    return render_template('admins.html', admins=admins)

 

@routes.route('/admins/add', methods=['GET', 'POST'])

@login_required

def add_admin():

    form = AdminForm()

    if form.validate_on_submit():

        new_admin = Admin(

            username=form.username.data,

            email=form.email.data,

            password_hash=generate_password_hash(form.password.data)

        )

        db.session.add(new_admin)

        db.session.commit()

        flash('Admin added successfully!', 'success')

        return redirect(url_for('routes.view_admins'))

    return render_template('add_admin.html', form=form)

Summary

  • __init__.py: Initializes the routes module and imports the specific route files.
  • auth.py: Contains routes for user authentication (registration, login, logout).
  • patient.py: Manages patient-related routes (viewing and adding patients).
  • admin.py: Handles admin-related routes (viewing and adding admins).

With this setup, you have a clear structure for handling different routes within your Hospital Management System project, allowing you to manage user authentication and patient/admin management efficiently.

 


tmplates


Here’s a detailed implementation of the HTML templates for your Hospital Management System project, organized under the specified directory structure. The templates include basic HTML structure and placeholders for dynamic content.

1. base.html

This file serves as the base layout for all other templates. It contains common elements such as the header, footer, and links to CSS files.

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>{% block title %}Hospital Management System{% endblock %}</title>

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

    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">

</head>

<body>

    <header>

        <nav class="navbar navbar-expand-lg navbar-light bg-light">

            <a class="navbar-brand" href="{{ url_for('routes.home') }}">HMS</a>

            <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">

                <span class="navbar-toggler-icon"></span>

            </button>

            <div class="collapse navbar-collapse" id="navbarNav">

                <ul class="navbar-nav">

                    <li class="nav-item">

                        <a class="nav-link" href="{{ url_for('routes.view_patients') }}">Patients</a>

                    </li>

                    <li class="nav-item">

                        <a class="nav-link" href="{{ url_for('routes.login') }}">Login</a>

                    </li>

                    <li class="nav-item">

                        <a class="nav-link" href="{{ url_for('routes.register') }}">Register</a>

                    </li>

                </ul>

            </div>

        </nav>

    </header>

 

    <main class="container mt-5">

        {% with messages = get_flashed_messages() %}

            {% if messages %}

                <div class="alert alert-warning">

                    {% for message in messages %}

                        <p>{{ message }}</p>

                    {% endfor %}

                </div>

            {% endif %}

        {% endwith %}

        {% block content %}{% endblock %}

    </main>

 

    <footer class="text-center mt-5">

        <p>&copy; 2024 Hospital Management System</p>

    </footer>

 

    <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>

    <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.9.3/dist/umd/popper.min.js"></script>

    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>

</body>

</html>

2. Authentication Templates

register.html

This template provides a registration form for new users.

{% extends 'base.html' %}

 

{% block title %}Register{% endblock %}

 

{% block content %}

<h2>Register</h2>

<form method="POST">

    {{ form.hidden_tag() }}

    <div class="form-group">

        <label for="username">Username</label>

        {{ form.username(class='form-control') }}

    </div>

    <div class="form-group">

        <label for="email">Email</label>

        {{ form.email(class='form-control') }}

    </div>

    <div class="form-group">

        <label for="password">Password</label>

        {{ form.password(class='form-control') }}

    </div>

    <button type="submit" class="btn btn-primary">Register</button>

</form>

{% endblock %}

login.html

This template provides a login form for users.

{% extends 'base.html' %}

 

{% block title %}Login{% endblock %}

 

{% block content %}

<h2>Login</h2>

<form method="POST">

    {{ form.hidden_tag() }}

    <div class="form-group">

        <label for="username">Username</label>

        {{ form.username(class='form-control') }}

    </div>

    <div class="form-group">

        <label for="password">Password</label>

        {{ form.password(class='form-control') }}

    </div>

    <button type="submit" class="btn btn-primary">Login</button>

</form>

{% endblock %}

3. Patient Templates

dashboard.html

This template provides a dashboard for patients after they log in.

{% extends 'base.html' %}

 

{% block title %}Patient Dashboard{% endblock %}

 

{% block content %}

<h2>Welcome, {{ current_user.username }}!</h2>

<a href="{{ url_for('routes.book_appointment') }}" class="btn btn-primary">Book Appointment</a>

<a href="{{ url_for('routes.view_appointments') }}" class="btn btn-secondary">View Appointments</a>

{% endblock %}

view_appointments.html

This template lists all appointments for a patient.

{% extends 'base.html' %}

 

{% block title %}View Appointments{% endblock %}

 

{% block content %}

<h2>Your Appointments</h2>

<table class="table">

    <thead>

        <tr>

            <th>Date</th>

            <th>Doctor</th>

            <th>Status</th>

        </tr>

    </thead>

    <tbody>

        {% for appointment in appointments %}

        <tr>

            <td>{{ appointment.date }}</td>

            <td>{{ appointment.doctor_name }}</td>

            <td>{{ appointment.status }}</td>

        </tr>

        {% else %}

        <tr>

            <td colspan="3">No appointments found.</td>

        </tr>

        {% endfor %}

    </tbody>

</table>

{% endblock %}

book_appointment.html

This template provides a form to book a new appointment.

{% extends 'base.html' %}

 

{% block title %}Book Appointment{% endblock %}

 

{% block content %}

<h2>Book an Appointment</h2>

<form method="POST">

    {{ form.hidden_tag() }}

    <div class="form-group">

        <label for="date">Date</label>

        {{ form.date(class='form-control') }}

    </div>

    <div class="form-group">

        <label for="doctor_id">Select Doctor</label>

        {{ form.doctor_id(class='form-control') }}

    </div>

    <button type="submit" class="btn btn-primary">Book Appointment</button>

</form>

{% endblock %}

4. Admin Templates

dashboard.html

This template provides an admin dashboard.

{% extends 'base.html' %}

 

{% block title %}Admin Dashboard{% endblock %}

 

{% block content %}

<h2>Admin Dashboard</h2>

<a href="{{ url_for('routes.view_patients') }}" class="btn btn-primary">Manage Patients</a>

{% endblock %}

manage_patients.html

This template lists all patients and provides an option to manage them.

{% extends 'base.html' %}

 

{% block title %}Manage Patients{% endblock %}

 

{% block content %}

<h2>Manage Patients</h2>

<table class="table">

    <thead>

        <tr>

            <th>Name</th>

            <th>Age</th>

            <th>Gender</th>

            <th>Contact</th>

            <th>Actions</th>

        </tr>

    </thead>

    <tbody>

        {% for patient in patients %}

        <tr>

            <td>{{ patient.name }}</td>

            <td>{{ patient.age }}</td>

            <td>{{ patient.gender }}</td>

            <td>{{ patient.contact }}</td>

            <td>

                <a href="{{ url_for('routes.edit_patient', patient_id=patient.id) }}" class="btn btn-warning">Edit</a>

                <a href="{{ url_for('routes.delete_patient', patient_id=patient.id) }}" class="btn btn-danger">Delete</a>

            </td>

        </tr>

        {% else %}

        <tr>

            <td colspan="5">No patients found.</td>

        </tr>

        {% endfor %}

    </tbody>

</table>

{% endblock %}

Summary

The template files provided above create a foundational layout for your Hospital Management System. The base.html file is the foundation upon which other templates build. The authentication templates manage user registration and login, while the patient templates handle patient-related interactions such as viewing appointments and booking new ones. The admin templates provide functionality to manage patients effectively.

 



Directory Structure

utils/

── __init__.py

└── helpers.py

1. __init__.py

This file is used to mark the directory as a Python package. You can also import functions from helpers.py so they can be accessed easily.

# __init__.py

from .helpers import format_date, send_email

__all__ = ['format_date', 'send_email']

2. helpers.py

This file contains utility functions that can be reused throughout the project. Here are some examples of what you might include:

# helpers.py

from datetime import datetime

import smtplib

from email.mime.text import MIMEText

def format_date(date_str):

    """

    Converts a date string to a more readable format.

  

    Args:

    date_str (str): Date in 'YYYY-MM-DD' format.

 

   Returns:

    str: Formatted date string.

    """

    date_object = datetime.strptime(date_str, '%Y-%m-%d')

    return date_object.strftime('%B %d, %Y')  # E.g., 'October 07, 2024'

 

def send_email(to_email, subject, body):

    """

    Sends an email using SMTP.

 

    Args:

    to_email (str): Recipient's email address.

    subject (str): Subject of the email.

    body (str): Body of the email.

 

    Returns:

    None

    """

    from_email = "your_email@example.com"  # Replace with your email

    from_password = "your_password"  # Replace with your email password

   

    msg = MIMEText(body)

    msg['Subject'] = subject

    msg['From'] = from_email

    msg['To'] = to_email

 

    try:

        with smtplib.SMTP('smtp.example.com', 587) as server:  # Replace with your SMTP server

            server.starttls()

            server.login(from_email, from_password)

            server.send_message(msg)

    except Exception as e:

        print(f"Error sending email: {e}")

Summary of the Utility Functions

  1. format_date: Converts a date string from 'YYYY-MM-DD' format to a more human-readable format (e.g., 'October 07, 2024').
  2. send_email: Sends an email to a specified recipient using SMTP. You need to replace placeholder email credentials and the SMTP server with actual values to make it functional.

How to Use Utility Functions

In other parts of your application, you can use the utility functions like this:

from utils import format_date, send_email

# Example usage of format_date

formatted_date = format_date('2024-10-07')

print(formatted_date)  # Output: October 07, 2024

# Example usage of send_email

send_email('recipient@example.com', 'Test Subject', 'This is a test email body.')

The run.py file is typically the entry point of your Python application. In the context of a Hospital Management System, this file is responsible for starting the Flask application and initializing any required configurations. Below is an example of how you might set up run.py for your project.

run.py

# run.py

from app import create_app

def main():

    # Create an instance of the Flask application

    app = create_app()

    # Run the application

    if __name__ == "__main__":

        app.run(debug=True, host='0.0.0.0', port=5000)  # You can change the port if needed

if __name__ == "__main__":

    main()

Explanation

  1. Importing the Application Factory:
    • The create_app function is imported from the app package, which is typically where your Flask application instance is created. This function should be defined in app/__init__.py.
  2. Main Function:
    • The main() function creates an instance of your Flask application by calling create_app().
  3. Running the Application:
    • The application is run using app.run(), where:
      • debug=True: This enables debug mode, which is useful during development as it provides detailed error messages and automatically reloads the server when code changes.
      • host='0.0.0.0': This makes the server accessible externally. You can change this to 127.0.0.1 if you only want it accessible from your local machine.
      • port=5000: The port on which the application will run. You can change this to any other available port if needed.

Usage

To run your application, simply execute the following command in your terminal:

python run.py

This will start your Flask application, and you should be able to access it at http://localhost:5000 (or the specified host and port).

Important Note

Make sure that you have installed Flask and any other dependencies specified in your project. If you haven’t set up a virtual environment, it’s a good practice to do so and install the required packages. Here’s a quick command to install Flask if you haven't already:

pip install Flask

The requirements.txt file is used to specify the dependencies for your Python project. This file allows you to easily install all required packages using pip. Below is an example of what your requirements.txt file might look like for a Hospital Management System built with Flask, SQLAlchemy, and other commonly used libraries.

requirements.txt

Flask==2.2.3              # Flask framework for building web applications

Flask-SQLAlchemy==2.5.1   # SQLAlchemy support for Flask

Flask-Migrate==3.1.0      # Database migration tool for Flask

Flask-WTF==1.0.1          # WTForms integration with Flask for form handling

Flask-Login==0.6.2        # User session management for Flask

Flask-Mail==2.1.0         # Flask extension for sending email

gunicorn==20.1.0          # WSGI HTTP server for UNIX to serve your app in production

python-dotenv==0.20.0     # Read key-value pairs from .env files

Explanation of the Packages

  1. Flask: The main framework for building the web application.
  2. Flask-SQLAlchemy: Adds SQLAlchemy support to Flask, simplifying database operations.
  3. Flask-Migrate: A Flask extension that handles SQLAlchemy database migrations.
  4. Flask-WTF: Provides form handling capabilities, including validation and CSRF protection.
  5. Flask-Login: Manages user sessions and user authentication.
  6. Flask-Mail: Facilitates sending emails from your application.
  7. gunicorn: A production-grade WSGI server for running your Flask application.
  8. python-dotenv: Loads environment variables from a .env file, useful for managing configurations.

How to Create the requirements.txt

You can manually create the requirements.txt file in the root directory of your project and add the dependencies as shown above.

Installing the Requirements

To install the required packages, navigate to your project directory in the terminal and run:

pip install -r requirements.txt

This command will install all the dependencies listed in the requirements.txt file. Make sure to run this command in the virtual environment if you're using one.

Additional Notes

  • You can use pip freeze > requirements.txt to generate a requirements.txt file from your current environment, which will list all installed packages and their versions. However, it’s good practice to review this list and keep only the necessary packages for your project.
  • Adjust the package versions according to your needs and compatibility with your project.

 

Post a Comment

0Comments

Post a Comment (0)