Update to support py venv

This commit is contained in:
Jonny Ervine 2025-09-29 12:21:58 +08:00
parent d3eb5567b6
commit 3d769837d4
11 changed files with 1215 additions and 0 deletions

150
motm_app/.gitignore vendored Normal file
View File

@ -0,0 +1,150 @@
# Virtual Environment
venv/
env/
ENV/
.venv/
.env/
# Python
__pycache__/
*.py[cod]
*$py.class
*.so
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
pip-wheel-metadata/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST
# PyInstaller
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
# Translations
*.mo
*.pot
# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal
# Flask stuff:
instance/
.webassets-cache
# Scrapy stuff:
.scrapy
# Sphinx documentation
docs/_build/
# PyBuilder
target/
# Jupyter Notebook
.ipynb_checkpoints
# IPython
profile_default/
ipython_config.py
# pyenv
.python-version
# pipenv
Pipfile.lock
# PEP 582
__pypackages__/
# Celery stuff
celerybeat-schedule
celerybeat.pid
# SageMath parsed files
*.sage.py
# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/
# Spyder project settings
.spyderproject
.spyproject
# Rope project settings
.ropeproject
# mkdocs documentation
/site
# mypy
.mypy_cache/
.dmypy.json
dmypy.json
# Pyre type checker
.pyre/
# IDE
.vscode/
.idea/
*.swp
*.swo
*~
# OS
.DS_Store
.DS_Store?
._*
.Spotlight-V100
.Trashes
ehthumbs.db
Thumbs.db
# Application specific
*.db
*.sqlite
config.py
.env.local
.env.production

View File

@ -18,6 +18,84 @@ This is a standalone Flask application for managing Man of the Match and Dick of
## Installation ## Installation
### Option 1: Using Virtual Environment (Recommended)
**Windows Setup:**
1. **Create virtual environment**:
```cmd
python -m venv venv
```
*If `python` doesn't work, try `py` or use the full path to python.exe*
2. **Activate virtual environment**:
```cmd
venv\Scripts\activate.bat
```
3. **Install dependencies**:
```cmd
pip install --upgrade pip
pip install -r requirements.txt
```
4. **Run the application**:
```cmd
python main.py
```
**Unix/Linux/Mac Setup:**
1. **Create virtual environment**:
```bash
python3 -m venv venv
```
2. **Activate virtual environment**:
```bash
source venv/bin/activate
```
3. **Install dependencies**:
```bash
pip install --upgrade pip
pip install -r requirements.txt
```
4. **Run the application**:
```bash
python main.py
```
**Convenience Scripts:**
- After setup, you can use `activate_motm.bat` (Windows) or `source activate_motm.sh` (Unix)
- Or use `run_motm.bat` (Windows) or `./run_motm.sh` (Unix) to start directly
### Option 2: Manual Virtual Environment Setup
1. **Create virtual environment**:
```bash
python -m venv venv
```
2. **Activate virtual environment**:
- **Windows**: `venv\Scripts\activate`
- **Unix/Linux/Mac**: `source venv/bin/activate`
3. **Install dependencies**:
```bash
pip install -r requirements.txt
```
4. **Configure database settings** in `db_config.py`
5. **Run the application**:
```bash
python main.py
```
### Option 3: Global Installation (Not Recommended)
1. Install dependencies: 1. Install dependencies:
```bash ```bash
pip install -r requirements.txt pip install -r requirements.txt
@ -100,3 +178,49 @@ Update the following in `db_config.py`:
- Local database settings - Local database settings
The application uses the same database as the main hockey results system, so ensure proper database access is configured. The application uses the same database as the main hockey results system, so ensure proper database access is configured.
## Virtual Environment Management
### Development Workflow
1. **Activate virtual environment** before making changes:
- Windows: `activate_motm.bat` or `venv\Scripts\activate`
- Unix/Linux/Mac: `source activate_motm.sh` or `source venv/bin/activate`
2. **Install new packages**:
```bash
pip install new-package-name
```
3. **Update requirements.txt** after adding packages:
```bash
pip freeze > requirements.txt
```
4. **Deactivate** when done:
```bash
deactivate
```
### Virtual Environment Benefits
- **Isolation**: Dependencies won't conflict with other Python projects
- **Version Control**: Pin specific package versions for reproducibility
- **Clean Environment**: Easy to recreate if corrupted
- **Deployment**: Same environment can be replicated in production
### Troubleshooting
**Virtual environment not activating?**
- Ensure Python 3.7+ is installed
- Check file permissions on activation scripts
- Try recreating: `python setup_venv.py`
**Dependencies not found?**
- Activate virtual environment first
- Check if packages are installed: `pip list`
- Reinstall requirements: `pip install -r requirements.txt`
**Permission errors on Unix/Linux/Mac?**
- Make scripts executable: `chmod +x *.sh`
- Run with proper permissions

213
motm_app/SETUP_GUIDE.md Normal file
View File

@ -0,0 +1,213 @@
# MOTM Application - Virtual Environment Setup Guide
This guide will help you set up a Python virtual environment for the MOTM Flask application.
## Prerequisites
1. **Python 3.7 or higher** must be installed on your system
2. **pip** package manager should be available
## Quick Setup (Windows)
### Step 1: Check Python Installation
Open Command Prompt or PowerShell and run:
```cmd
python --version
```
If Python is not found, you may need to:
- Install Python from [python.org](https://www.python.org/downloads/)
- Or use `py` command if you have Python Launcher installed
### Step 2: Create Virtual Environment
Navigate to the `motm_app` directory and run:
**Option A: Using `python` command**
```cmd
python -m venv venv
```
**Option B: Using `py` command (if available)**
```cmd
py -m venv venv
```
**Option C: Using full path (if needed)**
```cmd
C:\Python39\python.exe -m venv venv
```
### Step 3: Activate Virtual Environment
**Windows Command Prompt:**
```cmd
venv\Scripts\activate.bat
```
**Windows PowerShell:**
```powershell
venv\Scripts\Activate.ps1
```
### Step 4: Install Dependencies
With the virtual environment activated:
```cmd
pip install --upgrade pip
pip install -r requirements.txt
```
### Step 5: Run the Application
```cmd
python main.py
```
The application will be available at: http://localhost:5000
## Quick Setup (Unix/Linux/Mac)
### Step 1: Create Virtual Environment
```bash
python3 -m venv venv
```
### Step 2: Activate Virtual Environment
```bash
source venv/bin/activate
```
### Step 3: Install Dependencies
```bash
pip install --upgrade pip
pip install -r requirements.txt
```
### Step 4: Run the Application
```bash
python main.py
```
## Using the Convenience Scripts
After setting up the virtual environment, you can use the provided scripts:
### Windows
- **Setup**: `setup_venv_windows.bat`
- **Activate**: `activate_motm.bat`
- **Run**: `run_motm.bat`
### Unix/Linux/Mac
- **Activate**: `source activate_motm.sh`
- **Run**: `./run_motm.sh`
## Troubleshooting
### Python Not Found
**Windows:**
1. Install Python from [python.org](https://www.python.org/downloads/)
2. During installation, check "Add Python to PATH"
3. Restart your command prompt
**Alternative for Windows:**
1. Install Python from Microsoft Store
2. Use `py` command instead of `python`
### Virtual Environment Issues
**Permission Errors (Windows):**
```cmd
# Try running as Administrator
# Or use PowerShell with execution policy
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
```
**Virtual Environment Already Exists:**
```cmd
# Remove existing environment
rmdir /s venv
# Or on Unix/Linux/Mac
rm -rf venv
```
### Dependencies Not Installing
1. **Activate virtual environment first**
2. **Upgrade pip**: `pip install --upgrade pip`
3. **Install individually**: `pip install Flask`
4. **Check internet connection**
5. **Try using --user flag**: `pip install --user -r requirements.txt`
### Application Not Starting
1. **Check virtual environment is activated** (should see `(venv)` in prompt)
2. **Verify all dependencies installed**: `pip list`
3. **Check for import errors**: `python -c "import flask"`
4. **Review error messages** in console output
## Development Workflow
### Daily Usage
1. **Activate environment**: `venv\Scripts\activate.bat` (Windows) or `source venv/bin/activate` (Unix)
2. **Make changes** to your code
3. **Test application**: `python main.py`
4. **Deactivate when done**: `deactivate`
### Adding New Packages
1. **Activate environment**
2. **Install package**: `pip install new-package`
3. **Update requirements**: `pip freeze > requirements.txt`
4. **Commit changes** to version control
### Updating Dependencies
1. **Activate environment**
2. **Update packages**: `pip install --upgrade package-name`
3. **Update requirements**: `pip freeze > requirements.txt`
## Environment Variables
If you need to set environment variables for the application:
**Windows:**
```cmd
set DATABASE_URL=your_database_url
python main.py
```
**Unix/Linux/Mac:**
```bash
export DATABASE_URL=your_database_url
python main.py
```
## Database Configuration
Make sure to update `db_config.py` with your database connection details before running the application.
## Getting Help
If you encounter issues:
1. **Check Python version**: Should be 3.7 or higher
2. **Verify virtual environment**: Should be activated
3. **Check dependencies**: Run `pip list` to see installed packages
4. **Review error messages**: Look for specific error details
5. **Test imports**: `python -c "import flask, pymysql"`
## Production Deployment
For production deployment:
1. **Use same Python version** as development
2. **Install exact dependencies**: `pip install -r requirements.txt`
3. **Set environment variables** for production database
4. **Configure web server** (nginx, Apache, etc.)
5. **Use process manager** (systemd, supervisor, etc.)
---
**Note**: This application requires access to the existing hockey results database. Ensure proper database connectivity before running.

View File

@ -0,0 +1,254 @@
# MOTM Application - Virtual Environment Guide
## 🎯 Why Use Virtual Environments?
Virtual environments provide **isolated Python environments** for your projects, which means:
- ✅ **No conflicts** between different project dependencies
- ✅ **Reproducible environments** across different machines
- ✅ **Clean separation** of project requirements
- ✅ **Easy deployment** with exact dependency versions
## 🚀 Quick Start
### Windows Users
1. **Open Command Prompt** (not PowerShell initially)
2. **Navigate to motm_app directory**:
```cmd
cd path\to\motm_app
```
3. **Create virtual environment**:
```cmd
python -m venv venv
```
*If this fails, try `py -m venv venv` or find your Python installation*
4. **Activate virtual environment**:
```cmd
venv\Scripts\activate.bat
```
*You should see `(venv)` at the beginning of your command prompt*
5. **Install dependencies**:
```cmd
pip install --upgrade pip
pip install -r requirements.txt
```
6. **Run the application**:
```cmd
python main.py
```
### Mac/Linux Users
1. **Open Terminal**
2. **Navigate to motm_app directory**:
```bash
cd path/to/motm_app
```
3. **Create virtual environment**:
```bash
python3 -m venv venv
```
4. **Activate virtual environment**:
```bash
source venv/bin/activate
```
*You should see `(venv)` at the beginning of your command prompt*
5. **Install dependencies**:
```bash
pip install --upgrade pip
pip install -r requirements.txt
```
6. **Run the application**:
```bash
python main.py
```
## 📁 What Gets Created
When you create a virtual environment, you'll see a new `venv` folder:
```
motm_app/
├── venv/ # Virtual environment (don't edit this)
│ ├── Scripts/ # Windows activation scripts
│ ├── bin/ # Unix activation scripts
│ ├── Lib/ # Installed packages
│ └── pyvenv.cfg # Environment configuration
├── main.py # Your application
├── requirements.txt # Dependencies list
└── ... # Other files
```
## 🔧 Daily Usage
### Starting Your Work Session
1. **Activate the virtual environment**:
- Windows: `venv\Scripts\activate.bat`
- Mac/Linux: `source venv/bin/activate`
2. **Verify activation** - you should see `(venv)` in your prompt:
```cmd
(venv) C:\path\to\motm_app>
```
3. **Run your application**:
```cmd
python main.py
```
### Ending Your Work Session
**Deactivate when done**:
```cmd
deactivate
```
*The `(venv)` indicator will disappear*
## 📦 Managing Dependencies
### Installing New Packages
1. **Activate virtual environment first**
2. **Install the package**:
```cmd
pip install package-name
```
3. **Update requirements.txt**:
```cmd
pip freeze > requirements.txt
```
4. **Commit the updated requirements.txt** to version control
### Updating Existing Packages
```cmd
pip install --upgrade package-name
```
### Viewing Installed Packages
```cmd
pip list
```
### Removing Packages
```cmd
pip uninstall package-name
```
## 🛠️ Troubleshooting
### "Python not found" Error
**Windows:**
- Install Python from [python.org](https://www.python.org/downloads/)
- During installation, check "Add Python to PATH"
- Try using `py` command instead of `python`
**Mac/Linux:**
- Install Python 3: `brew install python3` (Mac) or use package manager
- Use `python3` instead of `python`
### Virtual Environment Won't Activate
**Windows:**
```cmd
# Try running Command Prompt as Administrator
# Or use PowerShell with:
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
```
**Permission Errors:**
```cmd
# Remove and recreate
rmdir /s venv # Windows
rm -rf venv # Mac/Linux
python -m venv venv # Recreate
```
### Packages Not Found After Installation
1. **Make sure virtual environment is activated** (look for `(venv)`)
2. **Check if packages are installed**: `pip list`
3. **Reinstall requirements**: `pip install -r requirements.txt`
### Application Won't Start
1. **Activate virtual environment**
2. **Check all dependencies**: `pip install -r requirements.txt`
3. **Test imports**: `python -c "import flask"`
4. **Check error messages** in the console
## 🔄 Working with Teams
### Sharing Your Environment
1. **Commit `requirements.txt`** to version control
2. **Don't commit the `venv` folder** (add to `.gitignore`)
### Setting Up on New Machine
1. **Clone the repository**
2. **Create virtual environment**: `python -m venv venv`
3. **Activate it**: `venv\Scripts\activate.bat` (Windows) or `source venv/bin/activate` (Unix)
4. **Install dependencies**: `pip install -r requirements.txt`
## 🚀 Deployment Considerations
### Production Environment
- Use the same Python version as development
- Install exact dependencies: `pip install -r requirements.txt`
- Set up environment variables for database connections
- Use a proper web server (nginx, Apache)
- Consider using Docker for containerization
### Docker Example
```dockerfile
FROM python:3.9-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install -r requirements.txt
COPY . .
CMD ["python", "main.py"]
```
## 💡 Best Practices
1. **Always use virtual environments** for Python projects
2. **Activate before working** on the project
3. **Keep requirements.txt updated** when adding packages
4. **Use descriptive commit messages** when updating dependencies
5. **Test your application** after installing new packages
6. **Document any special setup requirements**
## 🆘 Getting Help
If you're still having issues:
1. **Check Python version**: Should be 3.7 or higher
2. **Verify virtual environment**: Should be activated (see `(venv)` in prompt)
3. **Review error messages**: Look for specific error details
4. **Test step by step**: Create a simple test script to verify Python works
5. **Check internet connection**: Required for installing packages
---
**Remember**: The virtual environment isolates your project dependencies from your system Python installation, making your project more reliable and portable! 🎉

View File

@ -0,0 +1,10 @@
@echo off
echo 🐍 Activating MOTM Virtual Environment...
call venv\Scripts\activate.bat
echo ✅ Virtual environment activated!
echo.
echo 🚀 To start the MOTM application, run:
echo python.exe main.py
echo.
echo 🔧 To deactivate, run:
echo deactivate

11
motm_app/activate_motm.sh Normal file
View File

@ -0,0 +1,11 @@
#!/bin/bash
echo "🐍 Activating MOTM Virtual Environment..."
source venv/bin/activate
echo "✅ Virtual environment activated!"
echo ""
echo "🚀 To start the MOTM application, run:"
echo " python main.py"
echo ""
echo "🔧 To deactivate, run:"
echo " deactivate"

5
motm_app/run_motm.bat Normal file
View File

@ -0,0 +1,5 @@
@echo off
echo 🐍 Starting MOTM Application...
call venv\Scripts\activate.bat
python.exe main.py
pause

5
motm_app/run_motm.sh Normal file
View File

@ -0,0 +1,5 @@
#!/bin/bash
echo "🐍 Starting MOTM Application..."
source venv/bin/activate
python main.py

148
motm_app/setup_venv.ps1 Normal file
View File

@ -0,0 +1,148 @@
# MOTM Flask Application - Virtual Environment Setup (PowerShell)
# Run this script in PowerShell: .\setup_venv.ps1
Write-Host "MOTM Flask Application - Virtual Environment Setup" -ForegroundColor Green
Write-Host "=" * 60 -ForegroundColor Green
# Check Python installation
Write-Host "`n🐍 Checking Python installation..." -ForegroundColor Yellow
$pythonCommands = @('python', 'python3', 'py')
$pythonCmd = $null
foreach ($cmd in $pythonCommands) {
try {
$version = & $cmd --version 2>$null
if ($LASTEXITCODE -eq 0) {
$pythonCmd = $cmd
Write-Host "✅ Found Python: $version" -ForegroundColor Green
break
}
}
catch {
# Continue to next command
}
}
if (-not $pythonCmd) {
Write-Host "❌ Python not found. Please install Python 3.7+ from python.org" -ForegroundColor Red
Write-Host " Make sure to check 'Add Python to PATH' during installation" -ForegroundColor Yellow
Read-Host "Press Enter to exit"
exit 1
}
# Check if virtual environment already exists
$venvDir = "venv"
if (Test-Path $venvDir) {
Write-Host "`n⚠ Virtual environment '$venvDir' already exists" -ForegroundColor Yellow
$recreate = Read-Host "Do you want to recreate it? (y/N)"
if ($recreate -match '^[yY]') {
Write-Host "🗑️ Removing existing virtual environment..." -ForegroundColor Yellow
Remove-Item -Recurse -Force $venvDir
} else {
Write-Host "Using existing virtual environment..." -ForegroundColor Green
$skipCreation = $true
}
}
# Create virtual environment
if (-not $skipCreation) {
Write-Host "`n📦 Creating virtual environment in '$venvDir'..." -ForegroundColor Yellow
try {
& $pythonCmd -m venv $venvDir
if ($LASTEXITCODE -eq 0) {
Write-Host "✅ Virtual environment created successfully!" -ForegroundColor Green
} else {
throw "Virtual environment creation failed"
}
}
catch {
Write-Host "❌ Failed to create virtual environment: $_" -ForegroundColor Red
Read-Host "Press Enter to exit"
exit 1
}
}
# Install dependencies
Write-Host "`n📚 Installing dependencies..." -ForegroundColor Yellow
$pipCmd = Join-Path $venvDir "Scripts\pip.exe"
if (-not (Test-Path $pipCmd)) {
$pipCmd = Join-Path $venvDir "Scripts\pip"
}
try {
# Upgrade pip first
Write-Host "🔄 Upgrading pip..." -ForegroundColor Yellow
& $pipCmd install --upgrade pip
# Install requirements
Write-Host "📦 Installing application dependencies..." -ForegroundColor Yellow
& $pipCmd install -r requirements.txt
if ($LASTEXITCODE -eq 0) {
Write-Host "✅ Dependencies installed successfully!" -ForegroundColor Green
} else {
throw "Dependencies installation failed"
}
}
catch {
Write-Host "❌ Failed to install dependencies: $_" -ForegroundColor Red
Read-Host "Press Enter to exit"
exit 1
}
# Create convenience scripts
Write-Host "`n📝 Creating convenience scripts..." -ForegroundColor Yellow
# Update the batch files to use the correct Python command
$activateScript = @"
@echo off
echo 🐍 Activating MOTM Virtual Environment...
call venv\Scripts\activate.bat
echo Virtual environment activated!
echo.
echo 🚀 To start the MOTM application, run:
echo $pythonCmd main.py
echo.
echo 🔧 To deactivate, run:
echo deactivate
"@
$runScript = @"
@echo off
echo 🐍 Starting MOTM Application...
call venv\Scripts\activate.bat
$pythonCmd main.py
pause
"@
$activateScript | Out-File -FilePath "activate_motm.bat" -Encoding ASCII
$runScript | Out-File -FilePath "run_motm.bat" -Encoding ASCII
Write-Host "✅ Convenience scripts created!" -ForegroundColor Green
# Print completion message
Write-Host "`n" + "=" * 60 -ForegroundColor Green
Write-Host "🎉 MOTM Virtual Environment Setup Complete!" -ForegroundColor Green
Write-Host "=" * 60 -ForegroundColor Green
Write-Host "`n📋 To use the virtual environment:" -ForegroundColor Cyan
Write-Host " 1. Activate: .\activate_motm.bat" -ForegroundColor White
Write-Host " 2. Run app: .\run_motm.bat" -ForegroundColor White
Write-Host " 3. Deactivate: deactivate" -ForegroundColor White
Write-Host "`n🔧 Manual activation:" -ForegroundColor Cyan
Write-Host " venv\Scripts\activate.bat" -ForegroundColor White
Write-Host " $pythonCmd main.py" -ForegroundColor White
Write-Host "`n🌐 The application will be available at: http://localhost:5000" -ForegroundColor Cyan
Write-Host "`n📚 For development:" -ForegroundColor Cyan
Write-Host " - Activate the venv before installing new packages" -ForegroundColor White
Write-Host " - Use 'pip install <package>' to add dependencies" -ForegroundColor White
Write-Host " - Update requirements.txt with 'pip freeze > requirements.txt'" -ForegroundColor White
Write-Host "`n🚀 Ready to start! Run: .\run_motm.bat" -ForegroundColor Green
Read-Host "`nPress Enter to exit"

224
motm_app/setup_venv.py Normal file
View File

@ -0,0 +1,224 @@
#!/usr/bin/env python3
"""
Setup script to create and configure a Python virtual environment for the MOTM application.
"""
import os
import sys
import subprocess
import platform
def create_virtual_environment():
"""Create a Python virtual environment for the MOTM application."""
print("🐍 Setting up Python virtual environment for MOTM application...")
print("=" * 60)
# Check Python version
python_version = sys.version_info
print(f"✓ Python version: {python_version.major}.{python_version.minor}.{python_version.micro}")
if python_version < (3, 7):
print("❌ Python 3.7 or higher is required")
return False
# Determine the virtual environment directory name
venv_dir = "venv"
# Check if virtual environment already exists
if os.path.exists(venv_dir):
print(f"⚠ Virtual environment '{venv_dir}' already exists")
response = input("Do you want to recreate it? (y/N): ").strip().lower()
if response in ['y', 'yes']:
print(f"🗑️ Removing existing virtual environment...")
if platform.system() == "Windows":
subprocess.run(['rmdir', '/s', '/q', venv_dir], shell=True)
else:
subprocess.run(['rm', '-rf', venv_dir])
else:
print("Using existing virtual environment...")
return True
# Create virtual environment
print(f"📦 Creating virtual environment in '{venv_dir}'...")
try:
subprocess.run([sys.executable, '-m', 'venv', venv_dir], check=True)
print("✅ Virtual environment created successfully!")
except subprocess.CalledProcessError as e:
print(f"❌ Failed to create virtual environment: {e}")
return False
return True
def get_activation_script():
"""Get the appropriate activation script for the current platform."""
if platform.system() == "Windows":
return os.path.join("venv", "Scripts", "activate.bat")
else:
return os.path.join("venv", "bin", "activate")
def install_dependencies():
"""Install required dependencies in the virtual environment."""
print("\n📚 Installing dependencies...")
# Determine the pip command based on platform
if platform.system() == "Windows":
pip_cmd = os.path.join("venv", "Scripts", "pip")
else:
pip_cmd = os.path.join("venv", "bin", "pip")
# Check if requirements.txt exists
if not os.path.exists("requirements.txt"):
print("❌ requirements.txt not found")
return False
try:
# Upgrade pip first
print("🔄 Upgrading pip...")
subprocess.run([pip_cmd, "install", "--upgrade", "pip"], check=True)
# Install requirements
print("📦 Installing application dependencies...")
subprocess.run([pip_cmd, "install", "-r", "requirements.txt"], check=True)
print("✅ Dependencies installed successfully!")
return True
except subprocess.CalledProcessError as e:
print(f"❌ Failed to install dependencies: {e}")
return False
def create_activation_scripts():
"""Create convenient activation scripts."""
print("\n📝 Creating activation scripts...")
# Windows batch script
windows_script = """@echo off
echo 🐍 Activating MOTM Virtual Environment...
call venv\\Scripts\\activate.bat
echo Virtual environment activated!
echo.
echo 🚀 To start the MOTM application, run:
echo python main.py
echo.
echo 🔧 To deactivate, run:
echo deactivate
"""
# Unix shell script
unix_script = """#!/bin/bash
echo "🐍 Activating MOTM Virtual Environment..."
source venv/bin/activate
echo "✅ Virtual environment activated!"
echo ""
echo "🚀 To start the MOTM application, run:"
echo " python main.py"
echo ""
echo "🔧 To deactivate, run:"
echo " deactivate"
"""
# Write platform-specific scripts
if platform.system() == "Windows":
with open("activate_motm.bat", "w") as f:
f.write(windows_script)
print("✓ Created activate_motm.bat for Windows")
else:
with open("activate_motm.sh", "w") as f:
f.write(unix_script)
# Make it executable
os.chmod("activate_motm.sh", 0o755)
print("✓ Created activate_motm.sh for Unix/Linux")
return True
def create_run_script():
"""Create a script to run the application directly."""
print("📝 Creating run script...")
# Windows batch script
windows_run = """@echo off
echo 🐍 Starting MOTM Application...
call venv\\Scripts\\activate.bat
python main.py
pause
"""
# Unix shell script
unix_run = """#!/bin/bash
echo "🐍 Starting MOTM Application..."
source venv/bin/activate
python main.py
"""
if platform.system() == "Windows":
with open("run_motm.bat", "w") as f:
f.write(windows_run)
print("✓ Created run_motm.bat")
else:
with open("run_motm.sh", "w") as f:
f.write(unix_run)
os.chmod("run_motm.sh", 0o755)
print("✓ Created run_motm.sh")
def print_instructions():
"""Print setup completion instructions."""
print("\n" + "=" * 60)
print("🎉 MOTM Virtual Environment Setup Complete!")
print("=" * 60)
if platform.system() == "Windows":
print("\n📋 To use the virtual environment:")
print(" 1. Activate: activate_motm.bat")
print(" 2. Run app: run_motm.bat")
print(" 3. Deactivate: deactivate")
print("\n🔧 Manual activation:")
print(" venv\\Scripts\\activate.bat")
print(" python main.py")
else:
print("\n📋 To use the virtual environment:")
print(" 1. Activate: source activate_motm.sh")
print(" 2. Run app: ./run_motm.sh")
print(" 3. Deactivate: deactivate")
print("\n🔧 Manual activation:")
print(" source venv/bin/activate")
print(" python main.py")
print("\n🌐 The application will be available at: http://localhost:5000")
print("\n📚 For development:")
print(" - Activate the venv before installing new packages")
print(" - Use 'pip install <package>' to add dependencies")
print(" - Update requirements.txt with 'pip freeze > requirements.txt'")
def main():
"""Main setup function."""
# Change to the script's directory
script_dir = os.path.dirname(os.path.abspath(__file__))
os.chdir(script_dir)
print("MOTM Flask Application - Virtual Environment Setup")
print("=" * 60)
# Step 1: Create virtual environment
if not create_virtual_environment():
sys.exit(1)
# Step 2: Install dependencies
if not install_dependencies():
sys.exit(1)
# Step 3: Create convenience scripts
create_activation_scripts()
create_run_script()
# Step 4: Print instructions
print_instructions()
if __name__ == "__main__":
main()

View File

@ -0,0 +1,71 @@
@echo off
echo MOTM Flask Application - Virtual Environment Setup
echo ================================================
echo.
echo 🐍 Creating Python virtual environment...
REM Check if virtual environment already exists
if exist venv (
echo ⚠ Virtual environment 'venv' already exists
set /p recreate="Do you want to recreate it? (y/N): "
if /i "%recreate%"=="y" (
echo 🗑️ Removing existing virtual environment...
rmdir /s /q venv
) else (
echo Using existing virtual environment...
goto :install_deps
)
)
REM Create virtual environment
echo 📦 Creating virtual environment in 'venv'...
python.exe -m venv venv
if errorlevel 1 (
echo ❌ Failed to create virtual environment
pause
exit /b 1
)
echo ✅ Virtual environment created successfully!
:install_deps
echo.
echo 📚 Installing dependencies...
REM Upgrade pip first
echo 🔄 Upgrading pip...
venv\Scripts\pip install --upgrade pip
REM Install requirements
echo 📦 Installing application dependencies...
venv\Scripts\pip install -r requirements.txt
if errorlevel 1 (
echo ❌ Failed to install dependencies
pause
exit /b 1
)
echo ✅ Dependencies installed successfully!
echo.
echo ================================================
echo 🎉 MOTM Virtual Environment Setup Complete!
echo ================================================
echo.
echo 📋 To use the virtual environment:
echo 1. Activate: activate_motm.bat
echo 2. Run app: run_motm.bat
echo 3. Deactivate: deactivate
echo.
echo 🔧 Manual activation:
echo venv\Scripts\activate.bat
echo python main.py
echo.
echo 🌐 The application will be available at: http://localhost:5000
echo.
echo 📚 For development:
echo - Activate the venv before installing new packages
echo - Use 'pip install ^<package^>' to add dependencies
echo - Update requirements.txt with 'pip freeze ^> requirements.txt'
echo.
pause