davidtran999 commited on
Commit
f13ce96
·
verified ·
1 Parent(s): 4fdd1ce

Upload backend/hue_portal/hue-portal-backendDocker/hue_portal/hue_portal/settings.py with huggingface_hub

Browse files
backend/hue_portal/hue-portal-backendDocker/hue_portal/hue_portal/settings.py ADDED
@@ -0,0 +1,223 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import time
3
+ from datetime import timedelta
4
+ from pathlib import Path
5
+ import environ
6
+
7
+ BASE_DIR = Path(__file__).resolve().parent.parent
8
+ env = environ.Env()
9
+ environ.Env.read_env(os.path.join(BASE_DIR, "..", ".env"))
10
+
11
+ SECRET_KEY = env("DJANGO_SECRET_KEY", default="change-me")
12
+ DEBUG = env.bool("DJANGO_DEBUG", default=False)
13
+ ALLOWED_HOSTS = env.list("DJANGO_ALLOWED_HOSTS", default=["*"])
14
+
15
+ INSTALLED_APPS = [
16
+ "django.contrib.admin",
17
+ "django.contrib.auth",
18
+ "django.contrib.contenttypes",
19
+ "django.contrib.sessions",
20
+ "django.contrib.messages",
21
+ "django.contrib.staticfiles",
22
+ "django.contrib.postgres",
23
+ "corsheaders",
24
+ "rest_framework",
25
+ "rest_framework_simplejwt.token_blacklist",
26
+ "hue_portal.core",
27
+ "hue_portal.chatbot",
28
+ ]
29
+
30
+ MIDDLEWARE = [
31
+ "django.middleware.security.SecurityMiddleware",
32
+ "whitenoise.middleware.WhiteNoiseMiddleware",
33
+ "django.middleware.gzip.GZipMiddleware",
34
+ "corsheaders.middleware.CorsMiddleware",
35
+ "django.middleware.common.CommonMiddleware",
36
+ "django.middleware.csrf.CsrfViewMiddleware",
37
+ "django.contrib.sessions.middleware.SessionMiddleware",
38
+ "django.contrib.auth.middleware.AuthenticationMiddleware",
39
+ "django.contrib.messages.middleware.MessageMiddleware",
40
+ "django.middleware.clickjacking.XFrameOptionsMiddleware",
41
+ "hue_portal.core.middleware.SecurityHeadersMiddleware",
42
+ "hue_portal.core.middleware.AuditLogMiddleware",
43
+ ]
44
+
45
+ ROOT_URLCONF = "hue_portal.hue_portal.urls"
46
+
47
+ TEMPLATES = [
48
+ {
49
+ "BACKEND": "django.template.backends.django.DjangoTemplates",
50
+ "DIRS": [],
51
+ "APP_DIRS": True,
52
+ "OPTIONS": {
53
+ "context_processors": [
54
+ "django.template.context_processors.debug",
55
+ "django.template.context_processors.request",
56
+ "django.contrib.auth.context_processors.auth",
57
+ "django.contrib.messages.context_processors.messages",
58
+ ],
59
+ },
60
+ },
61
+ ]
62
+
63
+ WSGI_APPLICATION = "hue_portal.hue_portal.wsgi.application"
64
+
65
+ def _mask(value: str) -> str:
66
+ if not value:
67
+ return ""
68
+ return value[:4] + "***"
69
+
70
+ database_url = env("DATABASE_URL", default=None)
71
+
72
+ if database_url:
73
+ DATABASES = {"default": env.db("DATABASE_URL")}
74
+ masked = database_url.replace(env("POSTGRES_PASSWORD", default=""), "***")
75
+ print(f"[DB] Using DATABASE_URL: {masked}", flush=True)
76
+ else:
77
+ print("[DB] DATABASE_URL not provided – thử kết nối qua POSTGRES_* / tunnel.", flush=True)
78
+ try:
79
+ import psycopg2
80
+
81
+ host = env("POSTGRES_HOST", default="localhost")
82
+ port = env("POSTGRES_PORT", default="5543")
83
+ user = env("POSTGRES_USER", default="hue")
84
+ password = env("POSTGRES_PASSWORD", default="huepass123")
85
+ database = env("POSTGRES_DB", default="hue_portal")
86
+
87
+ last_error = None
88
+ for attempt in range(1, 4):
89
+ try:
90
+ test_conn = psycopg2.connect(
91
+ host=host,
92
+ port=port,
93
+ user=user,
94
+ password=password,
95
+ database=database,
96
+ connect_timeout=3,
97
+ )
98
+ test_conn.close()
99
+ last_error = None
100
+ break
101
+ except psycopg2.OperationalError as exc:
102
+ last_error = exc
103
+ print(
104
+ f"[DB] Attempt {attempt}/3 failed to reach PostgreSQL ({exc}).",
105
+ flush=True,
106
+ )
107
+ time.sleep(1)
108
+
109
+ if last_error:
110
+ raise last_error
111
+
112
+ DATABASES = {
113
+ "default": {
114
+ "ENGINE": "django.db.backends.postgresql",
115
+ "NAME": database,
116
+ "USER": user,
117
+ "PASSWORD": password,
118
+ "HOST": host,
119
+ "PORT": port,
120
+ }
121
+ }
122
+ print(
123
+ f"[DB] Connected to PostgreSQL at {host}:{port} as {_mask(user)}",
124
+ flush=True,
125
+ )
126
+ except Exception as db_error:
127
+ print(
128
+ f"[DB] ⚠️ Falling back to SQLite because PostgreSQL is unavailable ({db_error})",
129
+ flush=True,
130
+ )
131
+ DATABASES = {
132
+ "default": {
133
+ "ENGINE": "django.db.backends.sqlite3",
134
+ "NAME": BASE_DIR / "db.sqlite3",
135
+ }
136
+ }
137
+
138
+ # Cache configuration: opt-in Redis, otherwise safe local cache
139
+ USE_REDIS_CACHE = env.bool("ENABLE_REDIS_CACHE", default=False)
140
+ _redis_configured = False
141
+
142
+ if USE_REDIS_CACHE:
143
+ try:
144
+ import redis
145
+ from urllib.parse import urlparse
146
+
147
+ redis_url = env("REDIS_URL", default="redis://localhost:6380/0")
148
+ parsed = urlparse(redis_url)
149
+ test_client = redis.Redis(
150
+ host=parsed.hostname or "localhost",
151
+ port=parsed.port or 6380,
152
+ username=parsed.username,
153
+ password=parsed.password,
154
+ db=int(parsed.path.lstrip("/") or 0),
155
+ socket_connect_timeout=1,
156
+ )
157
+ test_client.ping()
158
+ test_client.close()
159
+
160
+ CACHES = {
161
+ "default": {
162
+ "BACKEND": "django.core.cache.backends.redis.RedisCache",
163
+ "LOCATION": redis_url,
164
+ }
165
+ }
166
+ _redis_configured = True
167
+ print(f"[CACHE] ✅ Using Redis cache at {redis_url}", flush=True)
168
+ except Exception as redis_error:
169
+ print(f"[CACHE] ⚠️ Redis unavailable ({redis_error}), falling back to local cache.", flush=True)
170
+
171
+ if not _redis_configured:
172
+ # LocMemCache keeps throttling functional without external services
173
+ CACHES = {
174
+ "default": {
175
+ "BACKEND": "django.core.cache.backends.locmem.LocMemCache",
176
+ "LOCATION": "hue-portal-default-cache",
177
+ }
178
+ }
179
+ # Reduce throttling aggressiveness failures by ensuring predictable cache
180
+ print("[CACHE] ℹ️ Using in-memory cache (LocMemCache).", flush=True)
181
+
182
+ REST_FRAMEWORK = {
183
+ "DEFAULT_RENDERER_CLASSES": ["rest_framework.renderers.JSONRenderer"],
184
+ "DEFAULT_PARSER_CLASSES": ["rest_framework.parsers.JSONParser"],
185
+ "DEFAULT_PAGINATION_CLASS": "rest_framework.pagination.PageNumberPagination",
186
+ "PAGE_SIZE": 20,
187
+ "DEFAULT_THROTTLE_CLASSES": [
188
+ "rest_framework.throttling.AnonRateThrottle",
189
+ ],
190
+ "DEFAULT_THROTTLE_RATES": {
191
+ "anon": "60/minute",
192
+ },
193
+ "DEFAULT_AUTHENTICATION_CLASSES": (
194
+ "rest_framework_simplejwt.authentication.JWTAuthentication",
195
+ ),
196
+ }
197
+
198
+ SIMPLE_JWT = {
199
+ "ACCESS_TOKEN_LIFETIME": timedelta(minutes=60),
200
+ "REFRESH_TOKEN_LIFETIME": timedelta(days=7),
201
+ "ROTATE_REFRESH_TOKENS": True,
202
+ "BLACKLIST_AFTER_ROTATION": True,
203
+ "AUTH_HEADER_TYPES": ("Bearer",),
204
+ }
205
+
206
+ STATIC_URL = "/static/"
207
+ STATIC_ROOT = BASE_DIR / "static"
208
+
209
+ CORS_ALLOW_ALL_ORIGINS = env.bool("CORS_ALLOW_ALL_ORIGINS", default=True) # Allow all in dev
210
+ CORS_ALLOWED_ORIGINS = env.list("CORS_ALLOWED_ORIGINS", default=["http://localhost:3000", "http://127.0.0.1:3000", "http://localhost:5173", "http://127.0.0.1:5173"])
211
+ CORS_ALLOW_CREDENTIALS = True
212
+ CORS_ALLOW_METHODS = ["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"]
213
+ CORS_ALLOW_HEADERS = ["*"]
214
+
215
+ SECURE_HSTS_SECONDS = 31536000
216
+ SECURE_SSL_REDIRECT = False
217
+ SESSION_COOKIE_SECURE = True
218
+ CSRF_COOKIE_SECURE = True
219
+ SECURE_CONTENT_TYPE_NOSNIFF = True
220
+ SECURE_BROWSER_XSS_FILTER = True
221
+
222
+ DEFAULT_AUTO_FIELD = "django.db.models.AutoField"
223
+