sikeaditya commited on
Commit
a4f944b
·
verified ·
1 Parent(s): c7d939b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +45 -16
app.py CHANGED
@@ -4,7 +4,7 @@ import re
4
  import time
5
  import logging
6
  from datetime import datetime
7
- from flask import Flask, render_template, request, jsonify, session
8
  from google import genai
9
  from dotenv import load_dotenv
10
  from cachelib import SimpleCache
@@ -27,12 +27,13 @@ client = genai.Client(api_key=api_key)
27
  cache = SimpleCache(threshold=50, default_timeout=60*60*24*7)
28
 
29
  app = Flask(__name__)
30
- # At the top of app.py after initializing the app
31
- app.config['SESSION_TYPE'] = 'filesystem'
32
- app.config['SESSION_PERMANENT'] = True
33
- app.config['PERMANENT_SESSION_LIFETIME'] = timedelta(days=7)
34
  # Use secret key from environment or a default for development
35
  app.secret_key = os.getenv("SECRET_KEY", "dev_secret_key")
 
 
 
 
 
36
 
37
  # Supported languages
38
  LANGUAGES = {
@@ -49,7 +50,7 @@ LANGUAGES = {
49
  "ml": "മലയാളം (Malayalam)"
50
  }
51
 
52
- # List of pests and diseases (truncated for brevity)
53
  PESTS_DISEASES = [
54
  {
55
  "id": 1,
@@ -142,22 +143,33 @@ def index():
142
  # Set default language if not set
143
  if 'language' not in session:
144
  session['language'] = 'en'
145
- logger.info("Default language 'en' set in session")
146
- else:
147
- logger.info(f"Using existing session language: {session['language']}")
 
 
 
 
 
148
 
149
  @app.route('/set_language', methods=['POST'])
150
  def set_language():
151
  language = request.form.get('language')
152
  if language in LANGUAGES:
 
153
  session['language'] = language
154
- logger.info(f"Language set to {language} in session")
155
- return jsonify({"success": True})
 
 
 
 
 
 
 
 
156
  return jsonify({"success": False}), 400
157
 
158
-
159
-
160
-
161
  def extract_json_from_response(content):
162
  """Extract and parse JSON from API response."""
163
  try:
@@ -182,8 +194,8 @@ def extract_json_from_response(content):
182
 
183
  @app.route('/get_details/<int:pest_id>')
184
  def get_details(pest_id):
185
- # Get current language
186
- language = session.get('language', 'en')
187
 
188
  # Find the pest/disease by ID
189
  pest_disease = next((item for item in PESTS_DISEASES if item["id"] == pest_id), None)
@@ -326,6 +338,23 @@ def clear_specific_cache(pest_id):
326
  cache.delete(cache_key)
327
  return jsonify({"success": True, "message": f"Cache cleared for pest ID {pest_id}"})
328
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
329
  if __name__ == '__main__':
330
  # Use PORT environment variable if available (for Hugging Face Spaces)
331
  port = int(os.environ.get("PORT", 7860))
 
4
  import time
5
  import logging
6
  from datetime import datetime
7
+ from flask import Flask, render_template, request, jsonify, session, make_response
8
  from google import genai
9
  from dotenv import load_dotenv
10
  from cachelib import SimpleCache
 
27
  cache = SimpleCache(threshold=50, default_timeout=60*60*24*7)
28
 
29
  app = Flask(__name__)
 
 
 
 
30
  # Use secret key from environment or a default for development
31
  app.secret_key = os.getenv("SECRET_KEY", "dev_secret_key")
32
+ # Set session cookie settings to be more persistent
33
+ app.config['SESSION_COOKIE_SECURE'] = False # Set to True in HTTPS environments
34
+ app.config['SESSION_COOKIE_HTTPONLY'] = True
35
+ app.config['SESSION_COOKIE_SAMESITE'] = 'Lax'
36
+ app.config['PERMANENT_SESSION_LIFETIME'] = 60*60*24*7 # 7 days
37
 
38
  # Supported languages
39
  LANGUAGES = {
 
50
  "ml": "മലയാളം (Malayalam)"
51
  }
52
 
53
+ # List of pests and diseases
54
  PESTS_DISEASES = [
55
  {
56
  "id": 1,
 
143
  # Set default language if not set
144
  if 'language' not in session:
145
  session['language'] = 'en'
146
+
147
+ # Make session persistent
148
+ session.permanent = True
149
+
150
+ return render_template('index.html',
151
+ pests_diseases=PESTS_DISEASES,
152
+ languages=LANGUAGES,
153
+ current_language=session['language'])
154
 
155
  @app.route('/set_language', methods=['POST'])
156
  def set_language():
157
  language = request.form.get('language')
158
  if language in LANGUAGES:
159
+ session.permanent = True
160
  session['language'] = language
161
+ # Log the language change
162
+ logger.info(f"Language changed to {language}")
163
+
164
+ # Create a response with success message
165
+ response = make_response(jsonify({"success": True}))
166
+
167
+ # Set a cookie to ensure the language persists even if session fails
168
+ response.set_cookie('user_language', language, max_age=60*60*24*30) # 30 days
169
+
170
+ return response
171
  return jsonify({"success": False}), 400
172
 
 
 
 
173
  def extract_json_from_response(content):
174
  """Extract and parse JSON from API response."""
175
  try:
 
194
 
195
  @app.route('/get_details/<int:pest_id>')
196
  def get_details(pest_id):
197
+ # Get current language from session or cookie fallback
198
+ language = session.get('language', request.cookies.get('user_language', 'en'))
199
 
200
  # Find the pest/disease by ID
201
  pest_disease = next((item for item in PESTS_DISEASES if item["id"] == pest_id), None)
 
338
  cache.delete(cache_key)
339
  return jsonify({"success": True, "message": f"Cache cleared for pest ID {pest_id}"})
340
 
341
+ # Add a diagnostics endpoint to help debug session issues
342
+ @app.route('/debug/session')
343
+ def debug_session():
344
+ # Only enable in development
345
+ if os.getenv("FLASK_ENV") == "production":
346
+ return jsonify({"error": "Not available in production"}), 403
347
+
348
+ return jsonify({
349
+ "session_data": dict(session),
350
+ "cookies": dict(request.cookies),
351
+ "session_cookie_name": app.session_cookie_name,
352
+ "session_cookie_secure": app.config.get('SESSION_COOKIE_SECURE'),
353
+ "session_cookie_httponly": app.config.get('SESSION_COOKIE_HTTPONLY'),
354
+ "session_cookie_samesite": app.config.get('SESSION_COOKIE_SAMESITE'),
355
+ "permanent_session_lifetime": str(app.config.get('PERMANENT_SESSION_LIFETIME'))
356
+ })
357
+
358
  if __name__ == '__main__':
359
  # Use PORT environment variable if available (for Hugging Face Spaces)
360
  port = int(os.environ.get("PORT", 7860))