CihanYakar commited on
Commit
b2034dc
·
1 Parent(s): e7ff532
Files changed (2) hide show
  1. app/main.py +37 -29
  2. requirements.txt +3 -3
app/main.py CHANGED
@@ -1,5 +1,4 @@
1
- # app/main.py
2
- from fastapi import FastAPI, HTTPException
3
  from fastapi.middleware.cors import CORSMiddleware
4
  import json
5
  from datetime import datetime
@@ -8,6 +7,7 @@ import requests
8
  import pytz
9
  from typing import Dict
10
  import traceback
 
11
 
12
  app = FastAPI()
13
 
@@ -20,24 +20,27 @@ app.add_middleware(
20
  allow_headers=["*"],
21
  )
22
 
23
- # Cache dosya yolu
24
  CACHE_FILE = "menu_cache.json"
25
-
26
- # Environment variable'dan API key'i al
27
  CLAUDE_API_KEY = os.getenv("CLAUDE_API_KEY")
 
28
  if not CLAUDE_API_KEY:
29
  raise Exception("CLAUDE_API_KEY environment variable is not set")
30
 
 
 
 
 
 
 
 
31
  def get_current_date() -> str:
32
  """Günün tarihini YYYY-MM-DD formatında döndürür"""
33
  tz = pytz.timezone('Europe/Istanbul')
34
  return datetime.now(tz).strftime("%Y-%m-%d")
35
 
 
36
  def get_current_date_and_season() -> tuple:
37
  """Günün tarihini ve mevsimini döndürür"""
38
- from datetime import datetime
39
- import pytz
40
-
41
  # Türkiye saat dilimini ayarla
42
  tz = pytz.timezone('Europe/Istanbul')
43
  current_date = datetime.now(tz)
@@ -62,7 +65,6 @@ def get_current_date_and_season() -> tuple:
62
 
63
  # Tarih stringini formatla
64
  date_str = f"{current_date.day} {months[current_date.month]} {current_date.year}"
65
-
66
  return date_str, season
67
 
68
 
@@ -71,11 +73,12 @@ def load_cache() -> Dict:
71
  try:
72
  if os.path.exists(CACHE_FILE):
73
  with open(CACHE_FILE, "r", encoding="utf-8") as f:
74
- return json.load(f)
 
 
 
75
  except Exception as e:
76
- error_detail = f"Cache okuma hatası: {str(e)}\nTrace: {traceback.format_exc()}"
77
- print(error_detail)
78
- return {}
79
  return {}
80
 
81
 
@@ -150,7 +153,7 @@ Lütfen mevsime uygun ve sağlıklı seçimler yap. Sadece menüyü liste olarak
150
 
151
  return {
152
  "date": get_current_date(),
153
- "menu": menu_json # Artık doğrudan JSON objesi olarak dönüyor
154
  }
155
  else:
156
  error_msg = f"API hata kodu: {response.status_code}, Yanıt: {response.text}"
@@ -164,36 +167,41 @@ Lütfen mevsime uygun ve sağlıklı seçimler yap. Sadece menüyü liste olarak
164
 
165
 
166
  @app.get("/menu")
167
- async def get_menu():
168
  """Günün menüsünü getirir, yoksa oluşturur"""
169
  try:
170
  cache = load_cache()
171
- current_date = get_current_date()
172
 
173
- print(f"Cache kontrolü yapılıyor... Tarih: {current_date}")
 
 
 
 
 
 
 
 
174
 
175
- # Cache kontrolü
176
- if current_date in cache:
177
- print("Cache'den menü döndürülüyor")
178
- return cache[current_date]
179
 
 
180
  print("Yeni menü oluşturuluyor...")
181
- # Yeni menü oluştur
182
  menu_data = await generate_menu()
183
 
184
- # Cache'e kaydet
185
  try:
186
  print("Cache'e kaydediliyor...")
187
- cache[current_date] = menu_data
188
- save_cache(cache)
189
  print("Cache güncellendi")
 
 
 
 
 
190
  except Exception as e:
191
- error_detail = f"Cache kaydetme hatası: {str(e)}\nTrace: {traceback.format_exc()}"
192
- print(error_detail)
193
- # Cache hatası olsa bile menüyü döndür
194
- pass
195
 
196
  return menu_data
 
197
  except Exception as e:
198
  error_detail = f"Genel hata: {str(e)}\nTrace: {traceback.format_exc()}"
199
  print(error_detail)
 
1
+ from fastapi import FastAPI, HTTPException, Request, Response
 
2
  from fastapi.middleware.cors import CORSMiddleware
3
  import json
4
  from datetime import datetime
 
7
  import pytz
8
  from typing import Dict
9
  import traceback
10
+ import hashlib
11
 
12
  app = FastAPI()
13
 
 
20
  allow_headers=["*"],
21
  )
22
 
 
23
  CACHE_FILE = "menu_cache.json"
 
 
24
  CLAUDE_API_KEY = os.getenv("CLAUDE_API_KEY")
25
+
26
  if not CLAUDE_API_KEY:
27
  raise Exception("CLAUDE_API_KEY environment variable is not set")
28
 
29
+
30
+ def calculate_etag(data: Dict) -> str:
31
+ """Verilen data için ETag hesaplar"""
32
+ data_str = json.dumps(data, sort_keys=True)
33
+ return hashlib.md5(data_str.encode()).hexdigest()
34
+
35
+
36
  def get_current_date() -> str:
37
  """Günün tarihini YYYY-MM-DD formatında döndürür"""
38
  tz = pytz.timezone('Europe/Istanbul')
39
  return datetime.now(tz).strftime("%Y-%m-%d")
40
 
41
+
42
  def get_current_date_and_season() -> tuple:
43
  """Günün tarihini ve mevsimini döndürür"""
 
 
 
44
  # Türkiye saat dilimini ayarla
45
  tz = pytz.timezone('Europe/Istanbul')
46
  current_date = datetime.now(tz)
 
65
 
66
  # Tarih stringini formatla
67
  date_str = f"{current_date.day} {months[current_date.month]} {current_date.year}"
 
68
  return date_str, season
69
 
70
 
 
73
  try:
74
  if os.path.exists(CACHE_FILE):
75
  with open(CACHE_FILE, "r", encoding="utf-8") as f:
76
+ cache_data = json.load(f)
77
+ # Tarihi kontrol et
78
+ if cache_data.get("date") == get_current_date():
79
+ return cache_data
80
  except Exception as e:
81
+ print(f"Cache okuma hatası: {str(e)}\nTrace: {traceback.format_exc()}")
 
 
82
  return {}
83
 
84
 
 
153
 
154
  return {
155
  "date": get_current_date(),
156
+ "menu": menu_json
157
  }
158
  else:
159
  error_msg = f"API hata kodu: {response.status_code}, Yanıt: {response.text}"
 
167
 
168
 
169
  @app.get("/menu")
170
+ async def get_menu(request: Request, response: Response):
171
  """Günün menüsünü getirir, yoksa oluşturur"""
172
  try:
173
  cache = load_cache()
 
174
 
175
+ if cache:
176
+ # ETag hesapla
177
+ etag = calculate_etag(cache)
178
+ response.headers["ETag"] = etag
179
+
180
+ # If-None-Match header'ı kontrol et
181
+ if_none_match = request.headers.get("if-none-match")
182
+ if if_none_match and if_none_match == etag:
183
+ return Response(status_code=304) # Not Modified
184
 
185
+ return cache
 
 
 
186
 
187
+ # Cache yoksa veya geçersizse yeni menü oluştur
188
  print("Yeni menü oluşturuluyor...")
 
189
  menu_data = await generate_menu()
190
 
 
191
  try:
192
  print("Cache'e kaydediliyor...")
193
+ save_cache(menu_data)
 
194
  print("Cache güncellendi")
195
+
196
+ # Yeni ETag hesapla
197
+ etag = calculate_etag(menu_data)
198
+ response.headers["ETag"] = etag
199
+
200
  except Exception as e:
201
+ print(f"Cache kaydetme hatası: {str(e)}\nTrace: {traceback.format_exc()}")
 
 
 
202
 
203
  return menu_data
204
+
205
  except Exception as e:
206
  error_detail = f"Genel hata: {str(e)}\nTrace: {traceback.format_exc()}"
207
  print(error_detail)
requirements.txt CHANGED
@@ -1,5 +1,5 @@
1
  fastapi
2
- uvicorn
 
3
  requests
4
- python-dotenv
5
- pytz
 
1
  fastapi
2
+ uvicorn>=0.27.0
3
+ python-dotenv>=1.0.0
4
  requests
5
+ pytz>=2024.1