Noel-Teens commited on
Commit
5528998
·
1 Parent(s): ffedc01

implemented Aiven(MySQL) and BackBlaze B2.

Browse files
Files changed (6) hide show
  1. README.md +1 -1
  2. admin_app/views.py +27 -25
  3. api/views.py +39 -53
  4. app.py +2 -9
  5. pms_server/settings.py +51 -2
  6. requirements.txt +6 -1
README.md CHANGED
@@ -1,5 +1,5 @@
1
  ---
2
- title: Pms Backend Server
3
  emoji: 🐠
4
  colorFrom: pink
5
  colorTo: gray
 
1
  ---
2
+ title: PMS Backend Server
3
  emoji: 🐠
4
  colorFrom: pink
5
  colorTo: gray
admin_app/views.py CHANGED
@@ -28,6 +28,8 @@ import requests
28
  import resend
29
  import zipfile
30
  import base64
 
 
31
  from django.http import FileResponse, Http404, JsonResponse, HttpResponseNotFound
32
 
33
  def _auth_from_query_token(request):
@@ -63,7 +65,7 @@ import logging
63
  logger = logging.getLogger(__name__)
64
 
65
  def _send_invite_email(email: str, invite_link: str, inviter: str = None):
66
- """Send an invitation email using Resend API (works on Hugging Face)."""
67
  subject = "You're invited to join Project Management System"
68
  html_content = render_to_string(
69
  "emails/invite.html", {"invite_link": invite_link, "inviter": inviter}
@@ -74,35 +76,35 @@ def _send_invite_email(email: str, invite_link: str, inviter: str = None):
74
  )
75
 
76
  try:
77
- api_key = os.getenv("RESEND_API_KEY")
78
  if not api_key:
79
- raise Exception("RESEND_API_KEY not set in environment.")
80
-
81
- from_email = os.getenv("RESEND_FROM_EMAIL", "onboarding@resend.dev")
82
-
83
- response = requests.post(
84
- "https://api.resend.com/emails",
85
- headers={
86
- "Authorization": f"Bearer {api_key}",
87
- "Content-Type": "application/json",
88
- },
89
- json={
90
- "from": from_email,
91
- "to": [email],
92
- "subject": subject,
93
- "text": text_content,
94
- "html": html_content,
95
- },
96
- timeout=10,
97
  )
98
 
99
- resp_data = response.json()
100
- if response.status_code != 200:
101
- logger.error(f"Resend API error {response.status_code}: {resp_data}")
102
- raise Exception(f"Resend API error {response.status_code}: {resp_data}")
 
 
103
 
104
  logger.info(f"Invitation email sent successfully to {email}")
105
- return resp_data
 
 
 
 
106
 
107
  except Exception as e:
108
  logger.error(f"Failed to send email to {email}: {str(e)}")
 
28
  import resend
29
  import zipfile
30
  import base64
31
+ from sendgrid import SendGridAPIClient
32
+ from sendgrid.helpers.mail import Mail
33
  from django.http import FileResponse, Http404, JsonResponse, HttpResponseNotFound
34
 
35
  def _auth_from_query_token(request):
 
65
  logger = logging.getLogger(__name__)
66
 
67
  def _send_invite_email(email: str, invite_link: str, inviter: str = None):
68
+ """Send an invitation email using SendGrid (works on Hugging Face)."""
69
  subject = "You're invited to join Project Management System"
70
  html_content = render_to_string(
71
  "emails/invite.html", {"invite_link": invite_link, "inviter": inviter}
 
76
  )
77
 
78
  try:
79
+ api_key = os.getenv("SENDGRID_API_KEY")
80
  if not api_key:
81
+ raise Exception("SENDGRID_API_KEY not set in environment.")
82
+
83
+ from_email = os.getenv("FROM_EMAIL")
84
+ if not from_email:
85
+ raise Exception("FROM_EMAIL not set in environment.")
86
+
87
+ message = Mail(
88
+ from_email=from_email,
89
+ to_emails=email,
90
+ subject=subject,
91
+ plain_text_content=text_content,
92
+ html_content=html_content
 
 
 
 
 
 
93
  )
94
 
95
+ sg = SendGridAPIClient(api_key)
96
+ response = sg.send(message)
97
+
98
+ if response.status_code not in (200, 202):
99
+ logger.error(f"SendGrid API error {response.status_code}: {response.body}")
100
+ raise Exception(f"SendGrid API error {response.status_code}: {response.body}")
101
 
102
  logger.info(f"Invitation email sent successfully to {email}")
103
+ return {
104
+ "status_code": response.status_code,
105
+ "body": response.body.decode() if response.body else "",
106
+ "headers": dict(response.headers)
107
+ }
108
 
109
  except Exception as e:
110
  logger.error(f"Failed to send email to {email}: {str(e)}")
api/views.py CHANGED
@@ -8,6 +8,8 @@ from auth_app.utils import IsAdmin, IsNotFrozen
8
  from django.db.models import Count, Avg
9
  from django.http import HttpResponse
10
  from django.conf import settings
 
 
11
  import csv
12
  import os
13
 
@@ -86,50 +88,34 @@ def versions_list(request, id):
86
  if not paper_pdf or not latex_tex or not python_zip:
87
  return Response({'error': 'PDF, LaTeX, and Python ZIP files are required'}, status=status.HTTP_400_BAD_REQUEST)
88
 
89
- # Save files to media storage
90
  pdf_path = None
91
  latex_path = None
92
  python_path = None
93
  docx_path = None
94
 
95
- # Create directory structures if they don't exist
96
- pdf_folder = os.path.join(settings.PDF_STORAGE_PATH, paper_id, version_str)
97
- latex_folder = os.path.join(settings.LATEX_STORAGE_PATH, paper_id, version_str)
98
- python_folder = os.path.join(settings.PYTHON_STORAGE_PATH, paper_id, version_str)
99
- docx_folder = os.path.join(settings.DOCX_STORAGE_PATH, paper_id, version_str)
100
-
101
- # Ensure all directories exist
102
- for folder in [pdf_folder, latex_folder, python_folder, docx_folder]:
103
- full_path = os.path.join(settings.MEDIA_ROOT, folder)
104
- os.makedirs(full_path, exist_ok=True)
105
 
 
106
  if paper_pdf:
107
- pdf_path = f"{pdf_folder}/paper.pdf"
108
- full_pdf_path = os.path.join(settings.MEDIA_ROOT, pdf_path)
109
- with open(full_pdf_path, 'wb+') as destination:
110
- for chunk in paper_pdf.chunks():
111
- destination.write(chunk)
112
 
113
  if latex_tex:
114
- latex_path = f"{latex_folder}/latex.tex"
115
- full_latex_path = os.path.join(settings.MEDIA_ROOT, latex_path)
116
- with open(full_latex_path, 'wb+') as destination:
117
- for chunk in latex_tex.chunks():
118
- destination.write(chunk)
119
 
120
  if python_zip:
121
- python_path = f"{python_folder}/code.zip"
122
- full_python_path = os.path.join(settings.MEDIA_ROOT, python_path)
123
- with open(full_python_path, 'wb+') as destination:
124
- for chunk in python_zip.chunks():
125
- destination.write(chunk)
126
 
127
  if docx_file:
128
- docx_path = f"{docx_folder}/paper.docx"
129
- full_docx_path = os.path.join(settings.MEDIA_ROOT, docx_path)
130
- with open(full_docx_path, 'wb+') as destination:
131
- for chunk in docx_file.chunks():
132
- destination.write(chunk)
133
 
134
  # Create version with file paths
135
  version = Version.objects.create(
@@ -153,18 +139,18 @@ def versions_list(request, id):
153
  versions_to_delete = versions[5:]
154
 
155
  for old_version in versions_to_delete:
156
- # Delete files associated with this version
157
- if old_version.pdf_path and os.path.exists(os.path.join(settings.MEDIA_ROOT, old_version.pdf_path)):
158
- os.remove(os.path.join(settings.MEDIA_ROOT, old_version.pdf_path))
159
 
160
- if old_version.latex_path and os.path.exists(os.path.join(settings.MEDIA_ROOT, old_version.latex_path)):
161
- os.remove(os.path.join(settings.MEDIA_ROOT, old_version.latex_path))
162
 
163
- if old_version.python_path and os.path.exists(os.path.join(settings.MEDIA_ROOT, old_version.python_path)):
164
- os.remove(os.path.join(settings.MEDIA_ROOT, old_version.python_path))
165
 
166
- if old_version.docx_path and os.path.exists(os.path.join(settings.MEDIA_ROOT, old_version.docx_path)):
167
- os.remove(os.path.join(settings.MEDIA_ROOT, old_version.docx_path))
168
 
169
  # Delete the version record
170
  old_version.delete()
@@ -190,14 +176,14 @@ def version_detail(request, id, ver):
190
  version = get_object_or_404(Version, paperwork=paperwork, version_no=ver)
191
  serializer = VersionSerializer(version)
192
 
193
- # Add full URLs for file downloads
194
  data = serializer.data
195
  if version.pdf_path:
196
- data['pdf_url'] = request.build_absolute_uri(settings.MEDIA_URL + version.pdf_path)
197
  if version.latex_path:
198
- data['latex_url'] = request.build_absolute_uri(settings.MEDIA_URL + version.latex_path)
199
  if version.python_path:
200
- data['python_url'] = request.build_absolute_uri(settings.MEDIA_URL + version.python_path)
201
 
202
  return Response(data)
203
 
@@ -360,21 +346,21 @@ def delete_paperwork(request, id):
360
 
361
  # Delete all files associated with this paperwork
362
  for version in versions:
363
- # Delete PDF file if exists
364
- if version.pdf_path and os.path.exists(os.path.join(settings.MEDIA_ROOT, version.pdf_path)):
365
- os.remove(os.path.join(settings.MEDIA_ROOT, version.pdf_path))
366
 
367
  # Delete LaTeX file if exists
368
- if version.latex_path and os.path.exists(os.path.join(settings.MEDIA_ROOT, version.latex_path)):
369
- os.remove(os.path.join(settings.MEDIA_ROOT, version.latex_path))
370
 
371
  # Delete Python ZIP file if exists
372
- if version.python_path and os.path.exists(os.path.join(settings.MEDIA_ROOT, version.python_path)):
373
- os.remove(os.path.join(settings.MEDIA_ROOT, version.python_path))
374
 
375
  # Delete DOCX file if exists
376
- if version.docx_path and os.path.exists(os.path.join(settings.MEDIA_ROOT, version.docx_path)):
377
- os.remove(os.path.join(settings.MEDIA_ROOT, version.docx_path))
378
 
379
  # Delete the paperwork (this will cascade delete versions and notifications)
380
  paperwork.delete()
 
8
  from django.db.models import Count, Avg
9
  from django.http import HttpResponse
10
  from django.conf import settings
11
+ from django.core.files.storage import default_storage
12
+ from django.core.files.base import ContentFile
13
  import csv
14
  import os
15
 
 
88
  if not paper_pdf or not latex_tex or not python_zip:
89
  return Response({'error': 'PDF, LaTeX, and Python ZIP files are required'}, status=status.HTTP_400_BAD_REQUEST)
90
 
91
+ # Save files using Django's storage system (Backblaze B2)
92
  pdf_path = None
93
  latex_path = None
94
  python_path = None
95
  docx_path = None
96
 
97
+ # Create storage paths
98
+ pdf_folder = f"{settings.PDF_STORAGE_PATH}/{paper_id}/{version_str}"
99
+ latex_folder = f"{settings.LATEX_STORAGE_PATH}/{paper_id}/{version_str}"
100
+ python_folder = f"{settings.PYTHON_STORAGE_PATH}/{paper_id}/{version_str}"
101
+ docx_folder = f"{settings.DOCX_STORAGE_PATH}/{paper_id}/{version_str}"
 
 
 
 
 
102
 
103
+ # Save files using default storage (configured for Backblaze B2)
104
  if paper_pdf:
105
+ pdf_file_path = f"{pdf_folder}/paper.pdf"
106
+ pdf_path = default_storage.save(pdf_file_path, paper_pdf)
 
 
 
107
 
108
  if latex_tex:
109
+ latex_file_path = f"{latex_folder}/latex.tex"
110
+ latex_path = default_storage.save(latex_file_path, latex_tex)
 
 
 
111
 
112
  if python_zip:
113
+ python_file_path = f"{python_folder}/code.zip"
114
+ python_path = default_storage.save(python_file_path, python_zip)
 
 
 
115
 
116
  if docx_file:
117
+ docx_file_path = f"{docx_folder}/paper.docx"
118
+ docx_path = default_storage.save(docx_file_path, docx_file)
 
 
 
119
 
120
  # Create version with file paths
121
  version = Version.objects.create(
 
139
  versions_to_delete = versions[5:]
140
 
141
  for old_version in versions_to_delete:
142
+ # Delete files from storage (Backblaze B2)
143
+ if old_version.pdf_path and default_storage.exists(old_version.pdf_path):
144
+ default_storage.delete(old_version.pdf_path)
145
 
146
+ if old_version.latex_path and default_storage.exists(old_version.latex_path):
147
+ default_storage.delete(old_version.latex_path)
148
 
149
+ if old_version.python_path and default_storage.exists(old_version.python_path):
150
+ default_storage.delete(old_version.python_path)
151
 
152
+ if old_version.docx_path and default_storage.exists(old_version.docx_path):
153
+ default_storage.delete(old_version.docx_path)
154
 
155
  # Delete the version record
156
  old_version.delete()
 
176
  version = get_object_or_404(Version, paperwork=paperwork, version_no=ver)
177
  serializer = VersionSerializer(version)
178
 
179
+ # Add full URLs for file downloads from storage
180
  data = serializer.data
181
  if version.pdf_path:
182
+ data['pdf_url'] = default_storage.url(version.pdf_path)
183
  if version.latex_path:
184
+ data['latex_url'] = default_storage.url(version.latex_path)
185
  if version.python_path:
186
+ data['python_url'] = default_storage.url(version.python_path)
187
 
188
  return Response(data)
189
 
 
346
 
347
  # Delete all files associated with this paperwork
348
  for version in versions:
349
+ # Delete files from storage (Backblaze B2)
350
+ if version.pdf_path and default_storage.exists(version.pdf_path):
351
+ default_storage.delete(version.pdf_path)
352
 
353
  # Delete LaTeX file if exists
354
+ if version.latex_path and default_storage.exists(version.latex_path):
355
+ default_storage.delete(version.latex_path)
356
 
357
  # Delete Python ZIP file if exists
358
+ if version.python_path and default_storage.exists(version.python_path):
359
+ default_storage.delete(version.python_path)
360
 
361
  # Delete DOCX file if exists
362
+ if version.docx_path and default_storage.exists(version.docx_path):
363
+ default_storage.delete(version.docx_path)
364
 
365
  # Delete the paperwork (this will cascade delete versions and notifications)
366
  paperwork.delete()
app.py CHANGED
@@ -1,16 +1,9 @@
1
  import os
2
 
3
- # ---- STEP 2: Create db.sqlite3 if missing (to avoid SQLite open errors)
4
- db_path = os.path.join(os.getcwd(), "db.sqlite3")
5
- if not os.path.exists(db_path):
6
- with open(db_path, 'w') as f:
7
- f.write("") # just create an empty file
8
-
9
- # ---- STEP 3: Run migrations to initialize database
10
  os.system("python manage.py makemigrations")
11
  os.system("python manage.py migrate")
12
  os.system("python manage.py createsuperadmin --username=Admin --email=admin@gmail.com --password=adminpassword")
13
 
14
-
15
- # ---- STEP 4: Start Django dev server on required Hugging Face port
16
  os.system("uvicorn pms_server.asgi:application --host 0.0.0.0 --port 7860")
 
1
  import os
2
 
3
+ # ---- STEP 2: Run migrations to initialize database
 
 
 
 
 
 
4
  os.system("python manage.py makemigrations")
5
  os.system("python manage.py migrate")
6
  os.system("python manage.py createsuperadmin --username=Admin --email=admin@gmail.com --password=adminpassword")
7
 
8
+ # ---- STEP 3: Start Django dev server on required Hugging Face port
 
9
  os.system("uvicorn pms_server.asgi:application --host 0.0.0.0 --port 7860")
pms_server/settings.py CHANGED
@@ -15,6 +15,7 @@ import os
15
  from datetime import timedelta
16
  import resend
17
  from dotenv import load_dotenv
 
18
 
19
  load_dotenv()
20
 
@@ -52,6 +53,7 @@ INSTALLED_APPS = [
52
  "auth_app.apps.AuthAppConfig",
53
  "admin_app",
54
  "api",
 
55
  ]
56
 
57
  MIDDLEWARE = [
@@ -128,10 +130,28 @@ db_path = BASE_DIR / "db.sqlite3"
128
  # if os.getenv("SPACE_ID"):
129
  # db_path = Path("/data/db.sqlite3")
130
 
 
 
 
 
 
 
 
 
 
 
 
131
  DATABASES = {
132
  "default": {
133
- "ENGINE": "django.db.backends.sqlite3",
134
- "NAME": db_path,
 
 
 
 
 
 
 
135
  }
136
  }
137
 
@@ -165,6 +185,35 @@ USE_I18N = True
165
 
166
  USE_TZ = True
167
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
168
 
169
  # Static files (CSS, JavaScript, Images)
170
  # https://docs.djangoproject.com/en/5.2/howto/static-files/
 
15
  from datetime import timedelta
16
  import resend
17
  from dotenv import load_dotenv
18
+ import tempfile
19
 
20
  load_dotenv()
21
 
 
53
  "auth_app.apps.AuthAppConfig",
54
  "admin_app",
55
  "api",
56
+ "storages",
57
  ]
58
 
59
  MIDDLEWARE = [
 
130
  # if os.getenv("SPACE_ID"):
131
  # db_path = Path("/data/db.sqlite3")
132
 
133
+ # Load from env
134
+ AIVEN_CA_CERT = os.getenv("AIVEN_CA_CERT")
135
+
136
+ ssl_options = {}
137
+ if AIVEN_CA_CERT:
138
+ # Write cert text to a temporary file at runtime
139
+ ca_file = tempfile.NamedTemporaryFile(delete=False, suffix=".pem")
140
+ ca_file.write(AIVEN_CA_CERT.encode())
141
+ ca_file.flush()
142
+ ssl_options["ca"] = ca_file.name
143
+
144
  DATABASES = {
145
  "default": {
146
+ "ENGINE": "django.db.backends.mysql",
147
+ "NAME": os.getenv("AIVEN_DB_NAME"),
148
+ "USER": os.getenv("AIVEN_DB_USER"),
149
+ "PASSWORD": os.getenv("AIVEN_DB_PASSWORD"),
150
+ "HOST": os.getenv("AIVEN_DB_HOST"),
151
+ "PORT": os.getenv("AIVEN_DB_PORT", "16000"),
152
+ "OPTIONS": {
153
+ "ssl": ssl_options,
154
+ },
155
  }
156
  }
157
 
 
185
 
186
  USE_TZ = True
187
 
188
+ # Use S3Boto3 backend for file storage (Backblaze B2)
189
+ DEFAULT_FILE_STORAGE = "storages.backends.s3boto3.S3Boto3Storage"
190
+ STATICFILES_STORAGE = "storages.backends.s3boto3.S3StaticStorage"
191
+
192
+ # Backblaze B2 credentials
193
+ AWS_ACCESS_KEY_ID = os.getenv("B2_KEY_ID") # from App Keys
194
+ AWS_SECRET_ACCESS_KEY = os.getenv("B2_APP_KEY") # from App Keys
195
+ AWS_STORAGE_BUCKET_NAME = os.getenv("B2_BUCKET_NAME")
196
+ AWS_S3_ENDPOINT_URL = os.getenv("B2_ENDPOINT_URL")
197
+
198
+ # S3 Configuration for Backblaze B2
199
+ AWS_S3_REGION_NAME = None # Backblaze B2 doesn't use regions
200
+ AWS_S3_USE_SSL = True
201
+ AWS_S3_VERIFY = True
202
+ AWS_QUERYSTRING_AUTH = False # cleaner public URLs
203
+ AWS_DEFAULT_ACL = None # Use bucket's default ACL
204
+ AWS_S3_SIGNATURE_VERSION = 's3v4'
205
+ AWS_S3_FILE_OVERWRITE = False # Don't overwrite files with same name
206
+
207
+ # Validate Backblaze B2 configuration
208
+ if not all([AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_STORAGE_BUCKET_NAME, AWS_S3_ENDPOINT_URL]):
209
+ import warnings
210
+ warnings.warn(
211
+ "Backblaze B2 configuration incomplete. Files will be stored locally. "
212
+ "Please set B2_KEY_ID, B2_APP_KEY, B2_BUCKET_NAME, and B2_ENDPOINT_URL environment variables.",
213
+ RuntimeWarning
214
+ )
215
+ # Fall back to local storage if B2 is not configured
216
+ DEFAULT_FILE_STORAGE = "django.core.files.storage.FileSystemStorage"
217
 
218
  # Static files (CSS, JavaScript, Images)
219
  # https://docs.djangoproject.com/en/5.2/howto/static-files/
requirements.txt CHANGED
@@ -6,4 +6,9 @@ djangorestframework-simplejwt
6
  uvicorn==0.34.0
7
  asgiref==3.8.1
8
  dotenv
9
- resend
 
 
 
 
 
 
6
  uvicorn==0.34.0
7
  asgiref==3.8.1
8
  dotenv
9
+ sendgrid
10
+ django-storages==1.14.3
11
+ boto3==1.35.40
12
+ botocore==1.35.40
13
+ mysqlclient==2.2.4
14
+ python-dotenv==1.0.1