-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdeploy.py
More file actions
350 lines (275 loc) Β· 8.86 KB
/
deploy.py
File metadata and controls
350 lines (275 loc) Β· 8.86 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
"""
Deployment script for Simple Project Management System
Handles production deployment setup
"""
import os
import sys
import subprocess
from app import app, db
from models import User, Project, Task, ActivityLog, init_db
from werkzeug.security import generate_password_hash
def check_requirements():
"""Check if all requirements are met"""
print("π Checking requirements...")
# Check Python version
if sys.version_info < (3, 7):
print("β Python 3.7+ is required")
return False
# Check if required packages are installed
required_packages = [
'flask', 'flask-sqlalchemy', 'flask-login',
'flask-wtf', 'wtforms', 'werkzeug'
]
missing_packages = []
for package in required_packages:
try:
__import__(package.replace('-', '_'))
except ImportError:
missing_packages.append(package)
if missing_packages:
print(f"β Missing packages: {', '.join(missing_packages)}")
print("Run: pip install -r requirements.txt")
return False
print("β
All requirements met")
return True
def setup_database():
"""Setup database for production"""
print("ποΈ Setting up database...")
with app.app_context():
# Initialize database
init_db(db)
db.create_all()
# Check if admin user exists
admin = User.query.filter_by(username='admin').first()
if not admin:
admin = User(
username='admin',
email='admin@spms.com',
password_hash=generate_password_hash('admin123'),
role='admin'
)
db.session.add(admin)
db.session.commit()
print("β
Admin user created: admin / admin123")
else:
print("β
Admin user already exists")
print("β
Database setup complete")
def create_production_config():
"""Create production configuration"""
print("βοΈ Creating production configuration...")
config_content = """# Production Configuration for SPMS
import os
class ProductionConfig:
SECRET_KEY = os.environ.get('SECRET_KEY') or 'your-production-secret-key-change-this'
SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL') or 'sqlite:///production.db'
SQLALCHEMY_TRACK_MODIFICATIONS = False
# Security settings
WTF_CSRF_ENABLED = True
WTF_CSRF_TIME_LIMIT = 3600
# Session settings
PERMANENT_SESSION_LIFETIME = 3600 # 1 hour
# Logging
LOG_LEVEL = 'INFO'
LOG_FILE = 'spms.log'
class DevelopmentConfig:
SECRET_KEY = 'dev-secret-key'
SQLALCHEMY_DATABASE_URI = 'sqlite:///development.db'
SQLALCHEMY_TRACK_MODIFICATIONS = True
DEBUG = True
# Configuration mapping
config = {
'development': DevelopmentConfig,
'production': ProductionConfig,
'default': DevelopmentConfig
}
"""
with open('config.py', 'w') as f:
f.write(config_content)
print("β
Production configuration created")
def create_wsgi_file():
"""Create WSGI file for production deployment"""
print("π Creating WSGI file...")
wsgi_content = """#!/usr/bin/env python3
\"\"\"
WSGI entry point for Simple Project Management System
\"\"\"
import os
import sys
# Add the project directory to Python path
project_dir = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, project_dir)
from app import app
if __name__ == "__main__":
app.run()
"""
with open('wsgi.py', 'w') as f:
f.write(wsgi_content)
# Make it executable
os.chmod('wsgi.py', 0o755)
print("β
WSGI file created")
def create_systemd_service():
"""Create systemd service file"""
print("π§ Creating systemd service...")
service_content = f"""[Unit]
Description=Simple Project Management System
After=network.target
[Service]
Type=simple
User=www-data
Group=www-data
WorkingDirectory={os.getcwd()}
Environment=PATH={os.getcwd()}/venv/bin
ExecStart={os.getcwd()}/venv/bin/gunicorn --bind 0.0.0.0:5000 wsgi:app
Restart=always
[Install]
WantedBy=multi-user.target
"""
with open('spms.service', 'w') as f:
f.write(service_content)
print("β
Systemd service file created")
print("To install: sudo cp spms.service /etc/systemd/system/")
print("To enable: sudo systemctl enable spms")
print("To start: sudo systemctl start spms")
def create_nginx_config():
"""Create Nginx configuration"""
print("π Creating Nginx configuration...")
nginx_content = """server {
listen 80;
server_name your-domain.com; # Change this to your domain
location / {
proxy_pass http://127.0.0.1:5000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
location /static {
alias /path/to/your/spms/static; # Change this path
expires 1y;
add_header Cache-Control "public, immutable";
}
}
"""
with open('nginx.conf', 'w') as f:
f.write(nginx_content)
print("β
Nginx configuration created")
print("Copy this to /etc/nginx/sites-available/spms")
print("Then: sudo ln -s /etc/nginx/sites-available/spms /etc/nginx/sites-enabled/")
def create_docker_files():
"""Create Docker configuration files"""
print("π³ Creating Docker configuration...")
# Dockerfile
dockerfile_content = """FROM python:3.9-slim
WORKDIR /app
# Install system dependencies
RUN apt-get update && apt-get install -y \\
gcc \\
&& rm -rf /var/lib/apt/lists/*
# Copy requirements and install Python dependencies
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
# Copy application code
COPY . .
# Create non-root user
RUN useradd --create-home --shell /bin/bash app
RUN chown -R app:app /app
USER app
# Expose port
EXPOSE 5000
# Run application
CMD ["gunicorn", "--bind", "0.0.0.0:5000", "wsgi:app"]
"""
with open('Dockerfile', 'w') as f:
f.write(dockerfile_content)
# docker-compose.yml
compose_content = """version: '3.8'
services:
spms:
build: .
ports:
- "5000:5000"
environment:
- FLASK_ENV=production
- SECRET_KEY=your-secret-key-change-this
volumes:
- ./data:/app/data
restart: unless-stopped
nginx:
image: nginx:alpine
ports:
- "80:80"
volumes:
- ./nginx.conf:/etc/nginx/conf.d/default.conf
depends_on:
- spms
restart: unless-stopped
"""
with open('docker-compose.yml', 'w') as f:
f.write(compose_content)
print("β
Docker configuration created")
print("To build: docker build -t spms .")
print("To run: docker-compose up -d")
def create_environment_file():
"""Create environment file template"""
print("π Creating environment file template...")
env_content = """# Environment Configuration for SPMS
# Copy this file to .env and update the values
# Flask Configuration
FLASK_ENV=production
SECRET_KEY=your-secret-key-change-this-in-production
DATABASE_URL=sqlite:///production.db
# Security
WTF_CSRF_ENABLED=True
WTF_CSRF_TIME_LIMIT=3600
# Logging
LOG_LEVEL=INFO
LOG_FILE=spms.log
# Email Configuration (for future notifications)
MAIL_SERVER=smtp.gmail.com
MAIL_PORT=587
MAIL_USE_TLS=True
MAIL_USERNAME=your-email@gmail.com
MAIL_PASSWORD=your-app-password
# Database Configuration
SQLALCHEMY_DATABASE_URI=sqlite:///production.db
SQLALCHEMY_TRACK_MODIFICATIONS=False
"""
with open('.env.template', 'w') as f:
f.write(env_content)
print("β
Environment file template created")
print("Copy .env.template to .env and update the values")
def main():
"""Main deployment function"""
print("π SPMS Deployment Setup")
print("=" * 50)
# Check requirements
if not check_requirements():
print("β Requirements check failed")
return False
# Setup database
setup_database()
# Create configuration files
create_production_config()
create_wsgi_file()
create_systemd_service()
create_nginx_config()
create_docker_files()
create_environment_file()
print("\n" + "=" * 50)
print("β
Deployment setup complete!")
print("\nπ Next Steps:")
print("1. Update configuration files with your settings")
print("2. Set up your web server (Nginx/Apache)")
print("3. Configure your domain and SSL certificate")
print("4. Set up monitoring and logging")
print("5. Test the deployment")
print("\nπ§ Production Commands:")
print("# Install Gunicorn for production")
print("pip install gunicorn")
print("\n# Run with Gunicorn")
print("gunicorn --bind 0.0.0.0:5000 wsgi:app")
print("\n# Or use Docker")
print("docker-compose up -d")
return True
if __name__ == '__main__':
main()