Skip to content

Development Environment Setup Guide

Complete guide for setting up the Drone Operations application for local development using Anaconda and PyCharm.

Table of Contents


Prerequisites

Required Software

  • Anaconda or Miniconda (Python 3.12+)
  • Download: https://www.anaconda.com/download or https://docs.conda.io/en/latest/miniconda.html
  • MariaDB 10.6+ (12.x recommended)
  • PyCharm (Community or Professional)
  • Git (for version control)

System Requirements

  • macOS: 10.15+ (Catalina or newer)
  • Windows: Windows 10/11 (64-bit)
  • Linux: Ubuntu 20.04+, Debian 11+, or similar

MariaDB Installation

macOS (using Homebrew)

# Install MariaDB
brew install mariadb

# Start MariaDB service
brew services start mariadb

# Secure installation (optional but recommended)
mysql_secure_installation

Windows

  1. Download MariaDB from: https://mariadb.org/download/
  2. Run the installer (choose "Full" installation)
  3. During setup:
  4. Set root password
  5. Enable "UTF8" as default character set
  6. Install as Windows Service
  7. Start MariaDB service from Services panel

Linux (Ubuntu/Debian)

# Update package list
sudo apt update

# Install MariaDB
sudo apt install mariadb-server mariadb-client

# Start MariaDB service
sudo systemctl start mariadb
sudo systemctl enable mariadb

# Secure installation
sudo mysql_secure_installation

Verify Installation

# Check MariaDB version
mysql --version

# Test connection
mysql -u root -p
# Enter your root password when prompted
# You should see: MariaDB [(none)]>
# Type: EXIT

Anaconda Environment Setup

1. Create Conda Environment

Open your terminal (or Anaconda Prompt on Windows):

# Navigate to project directory
cd /path/to/drones

# Create conda environment with Python 3.12
conda create -n drones python=3.12 -y

# Activate environment
conda activate drones

2. Install Dependencies

# Install pip packages from requirements.txt
pip install -r requirements.txt

# Verify installations
python -c "import flask; print(f'Flask: {flask.__version__}')"
python -c "import pymysql; print(f'PyMySQL: {pymysql.__version__}')"
python -c "import flask_migrate; print('Flask-Migrate installed')"

3. Add Environment to PyCharm

  1. Open PyCharm
  2. Go to Settings/PreferencesProject: dronesPython Interpreter
  3. Click Add InterpreterConda Environment
  4. Select Existing environment
  5. Browse to your conda environment:
  6. macOS/Linux: ~/anaconda3/envs/drones/bin/python
  7. Windows: C:\Users\YourName\anaconda3\envs\drones\python.exe
  8. Click OK

Database Configuration

1. Create Development Database

# Connect to MariaDB as root
mysql -u root -p

Run these SQL commands:

-- Create database with UTF8MB4 character set
CREATE DATABASE drones_dev CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

-- Create application user
CREATE USER 'drones_user'@'localhost' IDENTIFIED BY 'dev_password';

-- Grant privileges
GRANT ALL PRIVILEGES ON drones_dev.* TO 'drones_user'@'localhost';

-- Apply changes
FLUSH PRIVILEGES;

-- Verify database creation
SHOW DATABASES;

-- Exit
EXIT;

2. Test Database Connection

# Connect as drones_user
mysql -u drones_user -p drones_dev
# Password: dev_password

# You should see: MariaDB [drones_dev]>
# Type: EXIT

Application Setup

1. Create Environment Configuration

# Copy the local development template
cp .env.local.example .env

# The .env file should contain:
# - SECRET_KEY (already generated)
# - DATABASE_URL pointing to local MariaDB
# - Flask development settings

Verify .env contents:

cat .env

Should show:

SECRET_KEY=dev-secret-key-not-for-production
FLASK_ENV=development
FLASK_DEBUG=True
FLASK_HOST=127.0.0.1
FLASK_PORT=5000

DB_HOST=localhost
DB_PORT=3306
DB_USER=drones_user
DB_PASSWORD=dev_password
DB_NAME=drones_dev

DATABASE_URL=mysql+pymysql://drones_user:dev_password@localhost:3306/drones_dev?charset=utf8mb4

UPLOAD_FOLDER=./uploads
MAX_CONTENT_LENGTH=10485760

Note: If you changed the database password during setup, update DB_PASSWORD accordingly.

2. Initialise Database Schema

# Ensure conda environment is activated
conda activate drones

# Initialise Flask-Migrate (first time only)
flask db init

# Create initial migration
flask db migrate -m "Initial migration"

# Apply migration to database
flask db upgrade

Expected output:

INFO  [alembic.runtime.migration] Context impl MySQLImpl.
INFO  [alembic.runtime.migration] Will assume non-transactional DDL.
INFO  [alembic.runtime.migration] Running upgrade  -> abc123, Initial migration

3. Seed Database with Test Data

# Run the seeding script
python create_db.py

Expected output:

⚠️  Run 'flask db upgrade' before seeding!
This script seeds data to MariaDB only.
Adding roles...
Roles added.
Adding users...
Users added.
Project purposes added.
Adding drones...
Drones added.
Database seeding completed successfully.

4. Verify Database Setup

# Connect to database
mysql -u drones_user -p drones_dev

# Check tables
SHOW TABLES;

# Should show:
# +----------------------+
# | Tables_in_drones_dev |
# +----------------------+
# | alembic_version      |
# | audit_log           |
# | drone               |
# | project             |
# | project_access      |
# | project_file        |
# | project_purpose     |
# | role                |
# | user                |
# +----------------------+

# Check users
SELECT id, username, email FROM user;

# Should show admin, admin2, and user accounts
# EXIT

PyCharm Configuration

1. Set Up Run Configuration

  1. Open PyCharm and load the project
  2. Go to RunEdit Configurations
  3. Click +Python
  4. Configure:
  5. Name: Drones Dev Server
  6. Script path: Browse to run.py
  7. Python interpreter: Select the drones conda environment
  8. Working directory: Project root directory
  9. Environment variables:
    • Option A: Check "Load from .env file"
    • Option B: Manually add key variables if needed
  10. Click OK

2. Enable Environment File Support (PyCharm Professional)

If using PyCharm Professional with the .env plugin:

  1. Install EnvFile plugin:
  2. SettingsPlugins → Search "EnvFile" → Install
  3. In Run Configuration:
  4. Enable EnvFile tab
  5. Add .env file
  6. Check "Enable EnvFile"

3. Configure Database Tools (Optional)

PyCharm Professional includes database tools:

  1. Open Database tool window (View → Tool Windows → Database)
  2. Click +Data SourceMariaDB
  3. Configure:
  4. Host: localhost
  5. Port: 3306
  6. Database: drones_dev
  7. User: drones_user
  8. Password: dev_password
  9. Test connection → OK

Running the Application

  1. Select run configuration: "Drones Dev Server"
  2. Click Run button (green play icon) or press Shift+F10
  3. For debugging: Click Debug button (green bug icon) or press Shift+F9

Console output:

🔧 Development mode with MariaDB
⚠️  Ensure MariaDB is running locally
⚠️  Run 'flask db upgrade' before first run if needed

✅ Starting development server on http://127.0.0.1:5000
   Use PyCharm debugger for breakpoints
   For production, use: docker-compose up -d

 * Serving Flask app 'app'
 * Debug mode: on
 * Running on http://127.0.0.1:5000

Method 2: Terminal

# Activate conda environment
conda activate drones

# Run the application
python run.py

Method 3: Flask CLI

# Activate conda environment
conda activate drones

# Run with Flask CLI
flask run

# Or with custom host/port
flask run --host=0.0.0.0 --port=5000

Access the Application

Open your browser and navigate to:

  • Homepage: http://127.0.0.1:5000
  • Login: http://127.0.0.1:5000/login
  • Health Check: http://127.0.0.1:5000/health

Test Login Credentials

Username Password Role
admin adminpass Responsible Officer
admin2 adminpass2 Responsible Officer
user userpass Pilot

Database Migrations

Creating New Migrations

When you modify app/models.py:

# Activate environment
conda activate drones

# Generate migration script
flask db migrate -m "Description of changes"

# Review the generated migration file
# Located in: migrations/versions/xxxx_description_of_changes.py

# Apply migration
flask db upgrade

Migration Commands Reference

# Initialise migrations (first time only)
flask db init

# Create a new migration
flask db migrate -m "Add new column to user table"

# Apply pending migrations
flask db upgrade

# Revert last migration
flask db downgrade

# Show current migration version
flask db current

# Show migration history
flask db history

# Show pending migrations
flask db heads

Example: Adding a New Column

  1. Edit model:
# In app/models.py
class User(db.Model, UserMixin):
    # ... existing fields ...
    phone_number = db.Column(db.String(20), nullable=True)  # New field
  1. Create migration:
flask db migrate -m "Add phone number to user"
  1. Review migration file in migrations/versions/

  2. Apply migration:

flask db upgrade
  1. Verify in database:
mysql -u drones_user -p drones_dev
DESCRIBE user;
# Should show phone_number column
EXIT

Troubleshooting

MariaDB Connection Issues

Error: Can't connect to MySQL server on 'localhost'

Solutions:

  1. Check if MariaDB is running:
# macOS
brew services list | grep mariadb

# Linux
sudo systemctl status mariadb

# Windows
# Check Services panel for MariaDB service
  1. Start MariaDB:
# macOS
brew services start mariadb

# Linux
sudo systemctl start mariadb

# Windows
# Start from Services panel
  1. Test connection:
mysql -u drones_user -p drones_dev

Authentication Errors

Error: Access denied for user 'drones_user'@'localhost'

Solutions:

  1. Reset user password:
mysql -u root -p
DROP USER 'drones_user'@'localhost';
CREATE USER 'drones_user'@'localhost' IDENTIFIED BY 'dev_password';
GRANT ALL PRIVILEGES ON drones_dev.* TO 'drones_user'@'localhost';
FLUSH PRIVILEGES;
EXIT;
  1. Update .env file with correct password

Migration Errors

Error: Target database is not up to date

Solution:

# Check current version
flask db current

# Apply all pending migrations
flask db upgrade

Error: Can't locate revision identified by 'xxxxx'

Solution:

# Remove migrations directory
rm -rf migrations/

# Re-initialise
flask db init
flask db migrate -m "Initial migration"
flask db upgrade

Port Already in Use

Error: Address already in use: Port 5000

Solutions:

  1. Find process using port:
# macOS/Linux
lsof -i :5000

# Windows
netstat -ano | findstr :5000
  1. Kill the process:
# macOS/Linux
kill -9 <PID>

# Windows
taskkill /PID <PID> /F
  1. Or use a different port:

Edit .env:

FLASK_PORT=5001

Conda Environment Issues

Error: conda: command not found

Solution:

Initialise conda in your shell:

# bash
echo '. ~/anaconda3/etc/profile.d/conda.sh' >> ~/.bashrc
source ~/.bashrc

# zsh
echo '. ~/anaconda3/etc/profile.d/conda.sh' >> ~/.zshrc
source ~/.zshrc

Error: Environment not showing in PyCharm

Solution:

  1. Restart PyCharm
  2. Manually point to conda executable:
  3. Settings → Python Interpreter → Add
  4. System Interpreter → Browse to conda python

Module Import Errors

Error: ModuleNotFoundError: No module named 'flask_migrate'

Solution:

# Ensure environment is activated
conda activate drones

# Reinstall requirements
pip install -r requirements.txt

# Verify installation
pip list | grep Flask-Migrate

Database Connection Timeout

Error: Lost connection to MySQL server during query

Solution:

MariaDB configuration may need adjustment. Edit MariaDB config:

# macOS/Linux
sudo nano /etc/my.cnf

# Add under [mysqld]:
wait_timeout = 28800
interactive_timeout = 28800
max_allowed_packet = 64M

Restart MariaDB after changes.


Development Workflow

Daily Development Routine

  1. Start MariaDB (if not auto-starting)
# macOS
brew services start mariadb

# Linux
sudo systemctl start mariadb
  1. Activate conda environment
conda activate drones
  1. Pull latest changes (if using git)
git pull
  1. Apply any new migrations
flask db upgrade
  1. Run the application from PyCharm or terminal

  2. Develop with debugging:

  3. Set breakpoints in PyCharm
  4. Use Debug mode (Shift+F9)
  5. Inspect variables, step through code

Code Changes That Require Migration

When you modify database models:

  1. Make changes to app/models.py
  2. Create migration: flask db migrate -m "Description"
  3. Review migration file
  4. Apply migration: flask db upgrade
  5. Test changes thoroughly

Testing Database Changes

# Backup development database before major changes
mysqldump -u drones_user -p drones_dev > backup_$(date +%Y%m%d).sql

# If something goes wrong, restore:
mysql -u drones_user -p drones_dev < backup_YYYYMMDD.sql

Additional Tools

Flask Shell

Access Flask application context for testing:

conda activate drones
flask shell
# Example commands in Flask shell
from app import db
from app.models import User, Project

# Query users
users = User.query.all()
for user in users:
    print(f"{user.username} - {user.email}")

# Create test user
new_user = User(username='testuser', email='test@example.com', role_id=2)
new_user.set_password('testpass')
db.session.add(new_user)
db.session.commit()

# Exit
exit()

Database GUI Tools

Recommended tools for MariaDB management:

  • DBeaver (Free, cross-platform): https://dbeaver.io/
  • MySQL Workbench: https://www.mysql.com/products/workbench/
  • TablePlus (macOS, paid): https://tableplus.com/
  • HeidiSQL (Windows, free): https://www.heidisql.com/

VS Code Alternative

If using VS Code instead of PyCharm:

  1. Install Python extension
  2. Select conda interpreter:
  3. Cmd/Ctrl + Shift + P
  4. "Python: Select Interpreter"
  5. Choose drones conda environment
  6. Create launch.json:
{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Flask Debug",
            "type": "python",
            "request": "launch",
            "program": "${workspaceFolder}/run.py",
            "console": "integratedTerminal",
            "envFile": "${workspaceFolder}/.env"
        }
    ]
}

Next Steps

Once your development environment is working:

  1. Explore the application structure
  2. Review database models in app/models.py
  3. Understand routing in app/routes*.py files
  4. Check templates in app/templates/
  5. Review forms in app/forms/

For production deployment, see PRODUCTION_SETUP.md.


Quick Reference

Essential Commands

# Activate environment
conda activate drones

# Run application
python run.py

# Create migration
flask db migrate -m "Description"

# Apply migrations
flask db upgrade

# Flask shell
flask shell

# Deactivate environment
conda deactivate

Important Files

  • Configuration: .env
  • Models: app/models.py
  • Routes: app/routes*.py
  • Migrations: migrations/versions/
  • Requirements: requirements.txt

Port and URLs

  • Development server: http://127.0.0.1:5000
  • Health check: http://127.0.0.1:5000/health
  • MariaDB: localhost:3306

Getting Help

  • Flask Documentation: https://flask.palletsprojects.com/
  • Flask-Migrate Documentation: https://flask-migrate.readthedocs.io/
  • SQLAlchemy Documentation: https://docs.sqlalchemy.org/
  • MariaDB Documentation: https://mariadb.com/kb/en/documentation/
  • Anaconda Documentation: https://docs.anaconda.com/

If you encounter issues not covered in this guide, check the application logs and error messages for specific details.