0% found this document useful (0 votes)
5 views

Creating a more comprehensive disaster response app would involve adding various functionalities

The document outlines the creation of a disaster response app using Flask, SQLAlchemy, and Flask-WTF, detailing the project structure and necessary steps for setup. It includes code snippets for configuration, models, forms, and the main application logic, along with templates for user interaction. Key features include user authentication, alert management, and a user-friendly interface.

Uploaded by

moseslihbd
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Creating a more comprehensive disaster response app would involve adding various functionalities

The document outlines the creation of a disaster response app using Flask, SQLAlchemy, and Flask-WTF, detailing the project structure and necessary steps for setup. It includes code snippets for configuration, models, forms, and the main application logic, along with templates for user interaction. Key features include user authentication, alert management, and a user-friendly interface.

Uploaded by

moseslihbd
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 11

Creating a more comprehensive disaster response app would involve adding various functionalities, like

user authentication, a database for alerts and user information, and improved UI/UX. Below is a more
extensive example that spans around 10 pages of code, structured for clarity. We'll use Flask with
SQLAlchemy for the database and Flask-WTF for form handling.

### Project Structure

```

disaster_response_app/

├── app.py

├── config.py

├── models.py

├── forms.py

├── templates/

│ ├── base.html

│ ├── index.html

│ ├── alerts.html

│ ├── add_alert.html

│ ├── register.html

│ ├── login.html

│ ├── profile.html

│ └── styles.css

├── static/

│ └── styles.css

└── requirements.txt

```

### Step 1: Set Up Your Environment


1. **Create a virtual environment**:

```bash

python -m venv venv

source venv/bin/activate # On Windows use `venv\Scripts\activate`

```

2. **Install the necessary libraries**:

```bash

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

```

3. **Create a `requirements.txt` file**:

```plaintext

Flask

Flask-SQLAlchemy

Flask-WTF

Flask-Login

```

### Step 2: Configuration (`config.py`)

```python

import os

class Config:

SECRET_KEY = os.environ.get('SECRET_KEY') or 'you-will-never-guess'

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

SQLALCHEMY_TRACK_MODIFICATIONS = False

```
### Step 3: Models (`models.py`)

```python

from flask_sqlalchemy import SQLAlchemy

from flask_login import UserMixin

from app import app

db = SQLAlchemy(app)

class User(db.Model, UserMixin):

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

username = db.Column(db.String(150), unique=True, nullable=False)

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

class Alert(db.Model):

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

alert_type = db.Column(db.String(100), nullable=False)

message = db.Column(db.String(500), nullable=False)

```

### Step 4: Forms (`forms.py`)

```python

from flask_wtf import FlaskForm

from wtforms import StringField, PasswordField, SubmitField, TextAreaField

from wtforms.validators import DataRequired, Length

class RegistrationForm(FlaskForm):
username = StringField('Username', validators=[DataRequired(), Length(min=2, max=150)])

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

submit = SubmitField('Sign Up')

class LoginForm(FlaskForm):

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

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

submit = SubmitField('Login')

class AlertForm(FlaskForm):

alert_type = StringField('Alert Type', validators=[DataRequired()])

message = TextAreaField('Message', validators=[DataRequired()])

submit = SubmitField('Add Alert')

```

### Step 5: Main Application (`app.py`)

```python

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

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

from models import db, User, Alert

from forms import RegistrationForm, LoginForm, AlertForm

from config import Config

app = Flask(__name__)

app.config.from_object(Config)

db.init_app(app)

login_manager = LoginManager(app)

login_manager.login_view = 'login'
@login_manager.user_loader

def load_user(user_id):

return User.query.get(int(user_id))

@app.route('/')

def home():

return render_template('index.html')

@app.route('/alerts')

@login_required

def show_alerts():

alerts = Alert.query.all()

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

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

@login_required

def add_alert():

form = AlertForm()

if form.validate_on_submit():

new_alert = Alert(alert_type=form.alert_type.data, message=form.message.data)

db.session.add(new_alert)

db.session.commit()

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

return redirect(url_for('show_alerts'))

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

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

def register():
form = RegistrationForm()

if form.validate_on_submit():

new_user = User(username=form.username.data, password=form.password.data)

db.session.add(new_user)

db.session.commit()

flash('Registration successful! Please log in.', 'success')

return redirect(url_for('login'))

return render_template('register.html', 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 user.password == form.password.data:

login_user(user)

return redirect(url_for('show_alerts'))

else:

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

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

@app.route('/profile')

@login_required

def profile():

return render_template('profile.html', username=current_user.username)

@app.route('/logout')

@login_required

def logout():
logout_user()

return redirect(url_for('home'))

if __name__ == '__main__':

app.run(debug=True)

```

### Step 6: Base Template (`templates/base.html`)

```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='styles.css') }}">

<title>Disaster Response App</title>

</head>

<body>

<header>

<h1>Disaster Response App</h1>

<nav>

<a href="{{ url_for('home') }}">Home</a>

{% if current_user.is_authenticated %}

<a href="{{ url_for('show_alerts') }}">Alerts</a>

<a href="{{ url_for('add_alert') }}">Add Alert</a>

<a href="{{ url_for('profile') }}">Profile</a>

<a href="{{ url_for('logout') }}">Logout</a>

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

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

{% endif %}

</nav>

</header>

<main>

{% with messages = get_flashed_messages() %}

{% if messages %}

<ul>

{% for message in messages %}

<li>{{ message }}</li>

{% endfor %}

</ul>

{% endif %}

{% endwith %}

{% block content %}{% endblock %}

</main>

<footer>

<p>&copy; 2024 Disaster Response App</p>

</footer>

</body>

</html>

```

### Step 7: Other Templates

**`templates/index.html`**

```html
{% extends "base.html" %}

{% block content %}

<h2>Welcome!</h2>

<p>This app helps you stay informed during disasters.</p>

{% endblock %}

```

**`templates/alerts.html`**

```html

{% extends "base.html" %}

{% block content %}

<h2>Emergency Alerts</h2>

<ul>

{% for alert in alerts %}

<li><strong>{{ alert.alert_type }}:</strong> {{ alert.message }}</li>

{% endfor %}

</ul>

{% endblock %}

```

**`templates/add_alert.html`**

```html

{% extends "base.html" %}

{% block content %}
<h2>Add Emergency Alert</h2>

<form method="POST">

{{ form.hidden_tag() }}

<div>

{{ form.alert_type.label }}<br>

{{ form.alert_type(size=32) }}<br>

{% for error in form.alert_type.errors %}

<span style="color: red;">[{{ error }}]</span>

{% endfor %}

</div>

<div>

{{ form.message.label }}<br>

{{ form.message(rows=5) }}<br>

{% for error in form.message.errors %}

<span style="color: red;">[{{ error }}]</span>

{% endfor %}

</div>

<div>

{{ form.submit() }}

</div>

</form>

{% endblock %}

```

**`templates/register.html`**

```html

{% extends "base.html" %}
{% block content %}

<h2>Register</h2>

<form method="POST">

{{ form.hidden_tag() }}

<div>

{{ form.username.label }}<br>

{{ form.username(size=32) }}<br>

{% for error in form.username.errors %}

<span style="color: red;">[{{ error }}]</span>

{% endfor %}

</div>

<div>

{{ form.password.label }}<br>

{{ form.password(size=32) }}<

You might also like