-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtap_fullstack.py
More file actions
3674 lines (2961 loc) · 110 KB
/
tap_fullstack.py
File metadata and controls
3674 lines (2961 loc) · 110 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
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
import sys
import subprocess
from pathlib import Path
import secrets
import string
import shutil
import json
import textwrap
# ------------------------
# Config
# ------------------------
PROJECT_REQUIREMENTS = [
"django>=4.2",
"djangorestframework",
"djangorestframework-simplejwt",
"django-cors-headers",
"python-dotenv",
"django-jet-reboot",
"drf-yasg",
"gunicorn",
"whitenoise",
"psycopg2-binary", # PostgreSQL support
"dj-database-url", # Database URL parsing
]
API_APP = "api"
# ------------------------
# Helpers
# ------------------------
def run(cmd, cwd=None):
print(f"→ Running: {cmd}")
result = subprocess.run(cmd, shell=True, cwd=cwd)
if result.returncode != 0:
print(f"❌ Command failed: {cmd}")
sys.exit(1)
def generate_secret_key():
chars = string.ascii_letters + string.digits + "!@#$%^&*(-_=+)"
return "".join(secrets.choice(chars) for _ in range(50))
def write_file(path, content):
path.write_text(content.strip() + "\n")
def get_system_python():
python = shutil.which("python3") or shutil.which("python")
if not python:
raise RuntimeError("Python not found! Install python3 or add python to PATH.")
return python
def get_venv_python(base):
"""Detect correct venv python executable"""
if os.name == "nt":
venv_python = base / "venv" / "Scripts" / "python.exe"
else:
venv_python = base / "venv" / "bin" / "python3"
if not venv_python.exists():
venv_python = base / "venv" / "bin" / "python"
if not venv_python.exists():
raise RuntimeError(f"Python executable not found in venv: {venv_python}")
return venv_python
# ------------------------
# Deployment Config Generators
# ------------------------
def generate_google_cloud_config(base, project_name):
"""Generate Google Cloud Run/App Engine configurations"""
gcloud_dir = base / "deploy" / "google-cloud"
gcloud_dir.mkdir(parents=True, exist_ok=True)
# App Engine app.yaml
write_file(gcloud_dir / "app.yaml", textwrap.dedent(f"""
runtime: python311
entrypoint: gunicorn {project_name}.wsgi:application --bind 0.0.0.0:$PORT
env_variables:
DJANGO_SETTINGS_MODULE: "{project_name}.settings"
SECRET_KEY: "${{SECRET_KEY}}"
DEBUG: "False"
ALLOWED_HOSTS: ".your-app.appspot.com,.run.app"
CSRF_TRUSTED_ORIGINS: "https://*.appspot.com,https://*.run.app"
# Database (Cloud SQL)
DB_ENGINE: "django.db.backends.postgresql"
DB_HOST: "/cloudsql/YOUR_PROJECT:REGION:INSTANCE_NAME"
DB_NAME: "YOUR_DB_NAME"
DB_USER: "YOUR_DB_USER"
DB_PASSWORD: "${{DB_PASSWORD}}"
# Enable App Engine bundled services
beta_settings:
cloud_sql_instances: "YOUR_PROJECT:REGION:INSTANCE_NAME"
automatic_scaling:
min_instances: 1
max_instances: 3
target_cpu_utilization: 0.65
handlers:
- url: /static
static_dir: staticfiles/
- url: /.*
script: auto
"""))
# Cloud Run Dockerfile
write_file(gcloud_dir / "Dockerfile.cloudrun", textwrap.dedent(f"""
# Use the official Python image
FROM python:3.11-slim
# Install Node.js for frontend build
RUN apt-get update && apt-get install -y curl gnupg
RUN curl -fsSL https://deb.nodesource.com/setup_18.x | bash -
RUN apt-get install -y nodejs build-essential
# Create and set working directory
WORKDIR /app
# Copy requirements and install dependencies
COPY requirements.txt .
RUN pip install --upgrade pip && pip install -r requirements.txt
RUN pip install gunicorn
# Copy frontend and build
COPY frontend/ ./frontend/
WORKDIR /app/frontend
RUN npm install && npm run build
WORKDIR /app
# Copy application code
COPY . .
# Collect static files
RUN python manage.py collectstatic --noinput
# Run migrations (in production, this should be handled separately)
# RUN python manage.py migrate --noinput
# Run the web service on container startup
CMD exec gunicorn --bind :$PORT --workers 2 --threads 8 --timeout 0 {project_name}.wsgi:application
"""))
# Cloud Build configuration
write_file(gcloud_dir / "cloudbuild.yaml", textwrap.dedent("""
steps:
# Build the container image
- name: 'gcr.io/cloud-builders/docker'
args: ['build', '-t', 'gcr.io/$PROJECT_ID/$REPO_NAME:$COMMIT_SHA', '-f', 'deploy/google-cloud/Dockerfile.cloudrun', '.']
# Push the container image to Container Registry
- name: 'gcr.io/cloud-builders/docker'
args: ['push', 'gcr.io/$PROJECT_ID/$REPO_NAME:$COMMIT_SHA']
# Deploy to Cloud Run
- name: 'gcr.io/google.com/cloudsdktool/cloud-sdk'
entrypoint: gcloud
args:
- 'run'
- 'deploy'
- '$REPO_NAME'
- '--image'
- 'gcr.io/$PROJECT_ID/$REPO_NAME:$COMMIT_SHA'
- '--region'
- 'us-central1'
- '--platform'
- 'managed'
- '--allow-unauthenticated'
- '--set-env-vars'
- 'SECRET_KEY=$_SECRET_KEY,DEBUG=$_DEBUG,ALLOWED_HOSTS=$_ALLOWED_HOSTS'
images:
- 'gcr.io/$PROJECT_ID/$REPO_NAME:$COMMIT_SHA'
"""))
# Deployment script
write_file(gcloud_dir / "deploy.sh", textwrap.dedent("""#!/bin/bash
# Google Cloud Deployment Script
set -e
echo "🔧 Setting up Google Cloud deployment..."
# Check if gcloud is installed
if ! command -v gcloud &> /dev/null; then
echo "❌ Google Cloud SDK not found. Please install: https://cloud.google.com/sdk/docs/install"
exit 1
fi
# Authenticate
echo "🔐 Authenticating with Google Cloud..."
gcloud auth login
# Set project
read -p "Enter your Google Cloud Project ID: " PROJECT_ID
gcloud config set project $PROJECT_ID
# Enable required APIs
echo "🔄 Enabling required APIs..."
gcloud services enable \
cloudbuild.googleapis.com \
run.googleapis.com \
sqladmin.googleapis.com
# Build and deploy
echo "🚀 Building and deploying to Cloud Run..."
# Set environment variables
export SECRET_KEY=$(openssl rand -hex 32)
export DEBUG=False
export ALLOWED_HOSTS=".run.app"
# Submit build
gcloud builds submit \
--config deploy/google-cloud/cloudbuild.yaml \
--substitutions _SECRET_KEY=$SECRET_KEY,_DEBUG=$DEBUG,_ALLOWED_HOSTS=$ALLOWED_HOSTS
echo "✅ Deployment complete!"
echo "📦 Your app is now running on Cloud Run"
"""))
os.chmod(gcloud_dir / "deploy.sh", 0o755)
# README
write_file(gcloud_dir / "README.md", textwrap.dedent(f"""
# Google Cloud Deployment
## Prerequisites
1. Install [Google Cloud SDK](https://cloud.google.com/sdk/docs/install)
2. Create a Google Cloud Project
3. Enable billing for your project
## Deployment Options
### Option 1: Cloud Run (Recommended)
```bash
# Make deployment script executable
chmod +x deploy/google-cloud/deploy.sh
# Run deployment
./deploy/google-cloud/deploy.sh
```
### Option 2: App Engine
```bash
# Deploy to App Engine
gcloud app deploy deploy/google-cloud/app.yaml
# View deployment
gcloud app browse
```
### Option 3: Google Kubernetes Engine (GKE)
See `deploy/google-cloud/` for Kubernetes manifests.
## Environment Variables
Required environment variables for production:
```bash
SECRET_KEY=your-secure-secret-key
DEBUG=False
ALLOWED_HOSTS=.run.app,.appspot.com
DB_HOST=/cloudsql/PROJECT:REGION:INSTANCE_NAME
DB_NAME=your_db_name
DB_USER=your_db_user
DB_PASSWORD=your_db_password
```
## Database Setup (Cloud SQL)
1. Create Cloud SQL instance:
```bash
gcloud sql instances create [INSTANCE_NAME] \\
--database-version=POSTGRES_14 \\
--cpu=1 --memory=3840MB \\
--region=[REGION]
```
2. Create database and user:
```bash
gcloud sql databases create [DATABASE_NAME] --instance=[INSTANCE_NAME]
gcloud sql users create [USER_NAME] --instance=[INSTANCE_NAME] --password=[PASSWORD]
```
## Monitoring
- View logs: `gcloud app logs tail -s default`
- Monitor metrics in Google Cloud Console
- Set up alerts in Cloud Monitoring
"""))
def generate_aws_config(base, project_name):
"""Generate AWS Elastic Beanstalk/ECS configurations"""
aws_dir = base / "deploy" / "aws"
aws_dir.mkdir(parents=True, exist_ok=True)
# Elastic Beanstalk
write_file(aws_dir / "Dockerrun.aws.json", json.dumps({
"AWSEBDockerrunVersion": "1",
"Image": {
"Name": "<YOUR_ECR_REPOSITORY_URI>:latest",
"Update": "true"
},
"Ports": [{
"ContainerPort": "8000",
"HostPort": "8000"
}],
"Logging": "/var/log/django",
"Volumes": [{
"HostDirectory": "/var/app",
"ContainerDirectory": "/var/app"
}]
}, indent=2))
# ECS Task Definition
write_file(aws_dir / "task-definition.json", json.dumps({
"family": f"{project_name}-task",
"networkMode": "awsvpc",
"executionRoleArn": "arn:aws:iam::ACCOUNT_ID:role/ecsTaskExecutionRole",
"taskRoleArn": "arn:aws:iam::ACCOUNT_ID:role/ecsTaskRole",
"cpu": "512",
"memory": "1024",
"requiresCompatibilities": ["FARGATE"],
"containerDefinitions": [{
"name": f"{project_name}-container",
"image": "<YOUR_ECR_REPOSITORY_URI>:latest",
"portMappings": [{
"containerPort": 8000,
"hostPort": 8000,
"protocol": "tcp"
}],
"environment": [
{"name": "DJANGO_SETTINGS_MODULE", "value": f"{project_name}.settings"},
{"name": "SECRET_KEY", "value": "from-parameter-store"},
{"name": "DEBUG", "value": "False"},
{"name": "ALLOWED_HOSTS", "value": ".elasticbeanstalk.com,.amazonaws.com"},
{"name": "DATABASE_URL", "value": "from-secrets-manager"}
],
"secrets": [
{"name": "SECRET_KEY", "valueFrom": "arn:aws:ssm:REGION:ACCOUNT_ID:parameter/SECRET_KEY"},
{"name": "DATABASE_URL", "valueFrom": "arn:aws:secretsmanager:REGION:ACCOUNT_ID:secret:DATABASE_URL"}
],
"logConfiguration": {
"logDriver": "awslogs",
"options": {
"awslogs-group": f"/ecs/{project_name}",
"awslogs-region": "us-east-1",
"awslogs-stream-prefix": "ecs"
}
}
}]
}, indent=2))
# Elastic Beanstalk .ebextensions
ebext_dir = aws_dir / ".ebextensions"
ebext_dir.mkdir(exist_ok=True)
write_file(ebext_dir / "01_packages.config", textwrap.dedent("""
packages:
yum:
nodejs18: []
postgresql15-devel: []
commands:
01_install_node:
command: "curl -fsSL https://rpm.nodesource.com/setup_18.x | bash -"
02_update_node:
command: "yum install -y nodejs"
"""))
write_file(ebext_dir / "02_python.config", textwrap.dedent(f"""
option_settings:
aws:elasticbeanstalk:container:python:
WSGIPath: {project_name}.wsgi:application
NumProcesses: 3
NumThreads: 20
aws:elasticbeanstalk:application:environment:
DJANGO_SETTINGS_MODULE: "{project_name}.settings"
PYTHONPATH: "/var/app/current:$PYTHONPATH"
aws:elasticbeanstalk:environment:proxy:staticfiles:
/static: staticfiles/
"""))
# RDS database setup
write_file(ebext_dir / "03_rds.config", textwrap.dedent("""
option_settings:
aws:elasticbeanstalk:application:environment:
RDS_HOSTNAME: "`{ \"Ref\" : \"AWSEBRDSDatabase\" }`"
RDS_PORT: "`{ \"Fn::GetAtt\" : [ \"AWSEBRDSDatabase\", \"Endpoint.Port\" ] }`"
RDS_DB_NAME: "`{ \"Ref\" : \"AWSEBRDSDatabase\" }`"
RDS_USERNAME: "`{ \"Ref\" : \"AWSEBRDSDatabaseUsername\" }`"
RDS_PASSWORD: "`{ \"Ref\" : \"AWSEBRDSDatabasePassword\" }`"
Resources:
AWSEBRDSDatabase:
Type: AWS::RDS::DBInstance
Properties:
AllocatedStorage: 10
DBInstanceClass: db.t3.micro
Engine: postgres
EngineVersion: "15.2"
MasterUsername:
Ref: AWSEBRDSDatabaseUsername
MasterUserPassword:
Ref: AWSEBRDSDatabasePassword
DBName:
Ref: AWSEBRDSDatabase
"""))
# Deployment scripts
write_file(aws_dir / "deploy-eb.sh", textwrap.dedent(f"""#!/bin/bash
# AWS Elastic Beanstalk Deployment
set -e
echo "🔧 Setting up AWS Elastic Beanstalk deployment..."
# Check prerequisites
if ! command -v aws &> /dev/null; then
echo "❌ AWS CLI not found. Please install: https://aws.amazon.com/cli/"
exit 1
fi
if ! command -v eb &> /dev/null; then
echo "❌ Elastic Beanstalk CLI not found. Please install: https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/eb-cli3-install.html"
exit 1
fi
# Initialize EB application
echo "🚀 Initializing Elastic Beanstalk application..."
eb init -p "python-3.11" {project_name} --region us-east-1
# Create environment
echo "🌱 Creating Elastic Beanstalk environment..."
eb create {project_name}-env \
--instance_type t3.small \
--database \
--database.username django \
--database.password $(openssl rand -hex 16) \
--database.engine postgres \
--database.version 15.2 \
--single \
--envvars SECRET_KEY=$(openssl rand -hex 32),DEBUG=False,ALLOWED_HOSTS=.elasticbeanstalk.com
# Deploy
echo "📦 Deploying application..."
eb deploy
echo "✅ Deployment complete!"
echo "🌐 Your app is running at: $(eb status | grep CNAME | awk '{{print $2}}')"
"""))
os.chmod(aws_dir / "deploy-eb.sh", 0o755)
write_file(aws_dir / "deploy-ecs.sh", textwrap.dedent(f"""#!/bin/bash
# AWS ECS Deployment
set -e
echo "🔧 Setting up AWS ECS deployment..."
# Variables
REGION="us-east-1"
REPOSITORY_NAME="{project_name}"
CLUSTER_NAME="{project_name}-cluster"
SERVICE_NAME="{project_name}-service"
TASK_DEFINITION="deploy/aws/task-definition.json"
# Check AWS CLI
if ! command -v aws &> /dev/null; then
echo "❌ AWS CLI not found. Please install: https://aws.amazon.com/cli/"
exit 1
fi
# Login to ECR
echo "🔐 Logging into ECR..."
aws ecr get-login-password --region $REGION | docker login --username AWS --password-stdin $(aws sts get-caller-identity --query 'Account' --output text).dkr.ecr.$REGION.amazonaws.com
# Create ECR repository
echo "📦 Creating ECR repository..."
aws ecr create-repository --repository-name $REPOSITORY_NAME --region $REGION || true
# Build and push image
echo "🏗️ Building Docker image..."
docker build -t $REPOSITORY_NAME:latest .
# Tag and push
REPOSITORY_URI=$(aws ecr describe-repositories --repository-names $REPOSITORY_NAME --query 'repositories[0].repositoryUri' --output text --region $REGION)
docker tag $REPOSITORY_NAME:latest $REPOSITORY_URI:latest
docker push $REPOSITORY_URI:latest
# Update task definition with image URI
echo "🔄 Updating task definition..."
sed -i.bak "s|<YOUR_ECR_REPOSITORY_URI>|$REPOSITORY_URI|g" $TASK_DEFINITION
# Register task definition
echo "📝 Registering task definition..."
aws ecs register-task-definition --cli-input-json file://$TASK_DEFINITION --region $REGION
# Create cluster (if not exists)
echo "🏗️ Creating ECS cluster..."
aws ecs create-cluster --cluster-name $CLUSTER_NAME --region $REGION || true
# Create service
echo "🚀 Creating ECS service..."
aws ecs create-service \
--cluster $CLUSTER_NAME \
--service-name $SERVICE_NAME \
--task-definition {project_name}-task \
--desired-count 1 \
--launch-type FARGATE \
--network-configuration "awsvpcConfiguration={{subnets=[subnet-xxxxxx],securityGroups=[sg-xxxxxx],assignPublicIp=ENABLED}}" \
--region $REGION
echo "✅ Deployment complete!"
"""))
os.chmod(aws_dir / "deploy-ecs.sh", 0o755)
# README
write_file(aws_dir / "README.md", textwrap.dedent(f"""
# AWS Deployment
## Deployment Options
### Option 1: Elastic Beanstalk (Easiest)
```bash
# Install EB CLI first
pip install awsebcli
# Run Elastic Beanstalk deployment
chmod +x deploy/aws/deploy-eb.sh
./deploy/aws/deploy-eb.sh
```
### Option 2: ECS with Fargate (More Control)
```bash
# Run ECS deployment
chmod +x deploy/aws/deploy-ecs.sh
./deploy/aws/deploy-ecs.sh
```
### Option 3: EC2 Manual Deployment
1. Launch EC2 instance with Amazon Linux 2
2. SSH into instance and run:
```bash
# Install dependencies
sudo yum update -y
sudo yum install -y python3-pip nodejs postgresql-devel gcc
# Clone your repository
git clone <your-repo>
cd {project_name}
# Install and setup
pip3 install -r requirements.txt
npm install --prefix frontend
npm run build --prefix frontend
# Collect static files
python3 manage.py collectstatic --noinput
python3 manage.py migrate
# Run with gunicorn
gunicorn {project_name}.wsgi:application --bind 0.0.0.0:8000
```
## Database Setup (RDS)
### Automatic (with Elastic Beanstalk):
- Database is automatically created with EB deployment
### Manual RDS Creation:
```bash
aws rds create-db-instance \\
--db-instance-identifier {project_name}-db \\
--db-instance-class db.t3.micro \\
--engine postgres \\
--allocated-storage 20 \\
--master-username django \\
--master-user-password $(openssl rand -hex 16) \\
--backup-retention-period 7 \\
--multi-az false \\
--publicly-accessible true \\
--storage-type gp2
```
## Environment Variables
Store sensitive data in AWS Systems Manager Parameter Store:
```bash
aws ssm put-parameter \\
--name "/{project_name}/SECRET_KEY" \\
--value "$(openssl rand -hex 32)" \\
--type SecureString
aws ssm put-parameter \\
--name "/{project_name}/DATABASE_URL" \\
--value "postgres://user:pass@host:5432/dbname" \\
--type SecureString
```
## Monitoring
- CloudWatch Logs: View application logs
- CloudWatch Metrics: Monitor performance
- AWS X-Ray: Enable distributed tracing
- Health Checks: Configure in Load Balancer
"""))
def generate_heroku_config(base, project_name):
"""Generate Heroku configurations"""
heroku_dir = base / "deploy" / "heroku"
heroku_dir.mkdir(parents=True, exist_ok=True)
# Procfile
write_file(base / "Procfile", f"web: gunicorn {project_name}.wsgi:application --bind 0.0.0.0:$PORT")
# runtime.txt
write_file(base / "runtime.txt", "python-3.11.6")
# Heroku app.json
write_file(heroku_dir / "app.json", json.dumps({
"name": project_name,
"description": f"{project_name} - Django REST API with React Frontend",
"keywords": ["django", "rest", "react", "postgresql"],
"scripts": {
"postdeploy": "python manage.py migrate --noinput"
},
"env": {
"SECRET_KEY": {
"description": "Django secret key",
"generator": "secret"
},
"DEBUG": {
"description": "Disable debug mode in production",
"value": "False"
},
"ALLOWED_HOSTS": {
"description": "Comma-separated list of allowed hosts",
"value": ".herokuapp.com"
},
"DISABLE_COLLECTSTATIC": {
"description": "Disable collectstatic during build",
"value": "0"
}
},
"addons": [
{
"plan": "heroku-postgresql:hobby-dev",
"options": {
"version": "15"
}
}
],
"buildpacks": [
{
"url": "heroku/python"
},
{
"url": "heroku/nodejs"
}
],
"formation": {
"web": {
"quantity": 1,
"size": "eco"
}
}
}, indent=2))
# Heroku deployment script
write_file(heroku_dir / "deploy.sh", textwrap.dedent(f"""#!/bin/bash
# Heroku Deployment Script
set -e
echo "🔧 Setting up Heroku deployment..."
# Check if Heroku CLI is installed
if ! command -v heroku &> /dev/null; then
echo "❌ Heroku CLI not found. Please install: https://devcenter.heroku.com/articles/heroku-cli"
exit 1
fi
# Login to Heroku
echo "🔐 Logging into Heroku..."
heroku login
# Create Heroku app
echo "🚀 Creating Heroku app..."
heroku create {project_name}-$(date +%s) || true
# Set buildpacks (Python first, then Node.js)
echo "🏗️ Setting buildpacks..."
heroku buildpacks:clear
heroku buildpacks:add heroku/python
heroku buildpacks:add heroku/nodejs
# Add PostgreSQL addon
echo "💾 Adding PostgreSQL..."
heroku addons:create heroku-postgresql:hobby-dev
# Set environment variables
echo "⚙️ Setting environment variables..."
heroku config:set SECRET_KEY=$(openssl rand -hex 32)
heroku config:set DEBUG=False
heroku config:set ALLOWED_HOSTS=.herokuapp.com
heroku config:set DISABLE_COLLECTSTATIC=0
# Configure for Django
echo "🔧 Configuring Django..."
heroku config:set DJANGO_SETTINGS_MODULE={project_name}.settings
heroku config:set PYTHONPATH="/app"
# Deploy
echo "📦 Deploying to Heroku..."
git push heroku main
# Run migrations
echo "🔄 Running migrations..."
heroku run python manage.py migrate --noinput
# Create superuser (optional)
read -p "Create superuser? (y/n): " -n 1 -r
echo
if [[ $REPLY =~ ^[Yy]$ ]]; then
heroku run python manage.py createsuperuser
fi
# Open app
echo "🌐 Opening application..."
heroku open
echo "✅ Deployment complete!"
echo "📊 View logs: heroku logs --tail"
"""))
os.chmod(heroku_dir / "deploy.sh", 0o755)
# Heroku-specific Django settings
write_file(heroku_dir / "heroku_settings.py", textwrap.dedent(f"""
# Heroku-specific Django settings
import os
import dj_database_url
# Configure Django for Heroku
SECRET_KEY = os.environ.get('SECRET_KEY')
DEBUG = os.environ.get('DEBUG', 'False') == 'True'
ALLOWED_HOSTS = os.environ.get('ALLOWED_HOSTS', '.herokuapp.com').split(',')
# Database configuration
DATABASES = {{
'default': dj_database_url.config(
default=os.environ.get('DATABASE_URL'),
conn_max_age=600,
conn_health_checks=True,
)
}}
# Static files
STATIC_ROOT = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'staticfiles')
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
# HTTPS settings
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
SECURE_SSL_REDIRECT = not DEBUG
SESSION_COOKIE_SECURE = not DEBUG
CSRF_COOKIE_SECURE = not DEBUG
# HSTS settings
SECURE_HSTS_SECONDS = 31536000 if not DEBUG else 0
SECURE_HSTS_INCLUDE_SUBDOMAINS = not DEBUG
SECURE_HSTS_PRELOAD = not DEBUG
# Logging
LOGGING = {{
'version': 1,
'disable_existing_loggers': False,
'handlers': {{
'console': {{
'class': 'logging.StreamHandler',
}},
}},
'loggers': {{
'django': {{
'handlers': ['console'],
'level': os.getenv('DJANGO_LOG_LEVEL', 'INFO'),
}},
}},
}}
"""))
# README
write_file(heroku_dir / "README.md", textwrap.dedent(f"""
# Heroku Deployment
## Quick Deployment
```bash
# Make script executable
chmod +x deploy/heroku/deploy.sh
# Run deployment
./deploy/heroku/deploy.sh
```
## Manual Deployment
1. **Install Heroku CLI:**
```bash
# macOS
brew tap heroku/brew && brew install heroku
# Ubuntu
curl https://cli-assets.heroku.com/install.sh | sh
# Windows: Download from https://devcenter.heroku.com/articles/heroku-cli
```
2. **Login to Heroku:**
```bash
heroku login
```
3. **Create Heroku app:**
```bash
heroku create {project_name}-unique-name
```
4. **Add buildpacks:**
```bash
heroku buildpacks:add heroku/python
heroku buildpacks:add heroku/nodejs
```
5. **Add PostgreSQL:**
```bash
heroku addons:create heroku-postgresql:hobby-dev
```
6. **Configure environment:**
```bash
heroku config:set SECRET_KEY=$(openssl rand -hex 32)
heroku config:set DEBUG=False
heroku config:set ALLOWED_HOSTS=.herokuapp.com
heroku config:set DJANGO_SETTINGS_MODULE={project_name}.settings
```
7. **Deploy:**
```bash
git push heroku main
# Run migrations
heroku run python manage.py migrate
# Create superuser
heroku run python manage.py createsuperuser
# Open app
heroku open
```
## Database Management
Access PostgreSQL console:
```bash
heroku pg:psql
```
Backup database:
```bash
heroku pg:backups:capture
heroku pg:backups:download
```
## Monitoring
View logs:
```bash
heroku logs --tail
```
Monitor dynos:
```bash
heroku ps
```
View metrics:
```bash
heroku metrics
```
## Scaling
Scale web dynos:
```bash
heroku ps:scale web=2
```
Enable auto-scaling:
```bash
heroku features:enable autoscaling
heroku autoscaling:set web --min=1 --max=3 --p95-response-time=2000
```
## Custom Domains
Add custom domain:
```bash
heroku domains:add www.example.com
```
Configure SSL:
```bash
heroku certs:auto:enable
```
"""))
def generate_digitalocean_config(base, project_name):
"""Generate DigitalOcean App Platform configurations"""
do_dir = base / "deploy" / "digitalocean"
do_dir.mkdir(parents=True, exist_ok=True)
# DigitalOcean App Platform spec
write_file(do_dir / "do-app-spec.yaml", textwrap.dedent(f"""
name: {project_name}
region: nyc
services:
- name: web
github:
branch: main
deploy_on_push: true
repo: YOUR_GITHUB_USER/YOUR_REPO_NAME
dockerfile_path: Dockerfile.do
instance_count: 1
instance_size_slug: basic-xxs
http_port: 8000
health_check:
http_path: /api/v1/health/
initial_delay_seconds: 10
period_seconds: 10
timeout_seconds: 5
success_threshold: 1
failure_threshold: 3
envs:
- key: SECRET_KEY
scope: RUN_TIME
value: $(openssl rand -hex 32)
- key: DEBUG
scope: RUN_TIME
value: "False"
- key: ALLOWED_HOSTS
scope: RUN_TIME
value: ".ondigitalocean.app"
- key: DATABASE_URL
scope: RUN_TIME
type: SECRET
value: do-db-url
databases:
- name: {project_name}-db
engine: PG
version: "15"
production: false
cluster_name: {project_name}-cluster
db_name: {project_name}
db_user: django
envs:
- key: DATABASE_URL
scope: RUN_AND_BUILD_TIME
type: SECRET
value: do-db-url
"""))
# DigitalOcean Dockerfile
write_file(base / "Dockerfile.do", textwrap.dedent(f"""
FROM python:3.11-slim