Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -2,6 +2,7 @@ from flask import Flask, render_template, send_from_directory, request, jsonify
|
|
| 2 |
import requests
|
| 3 |
from dotenv import load_dotenv
|
| 4 |
import os
|
|
|
|
| 5 |
|
| 6 |
# Load environment variables from .env file
|
| 7 |
load_dotenv()
|
|
@@ -13,27 +14,41 @@ SFDC_USERNAME = os.getenv('SFDC_USERNAME')
|
|
| 13 |
SFDC_PASSWORD = os.getenv('SFDC_PASSWORD')
|
| 14 |
SFDC_SECURITY_TOKEN = os.getenv('SFDC_SECURITY_TOKEN')
|
| 15 |
SFDC_INSTANCE_URL = os.getenv('SFDC_INSTANCE_URL', 'https://login.salesforce.com')
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
|
| 17 |
# Function to get Salesforce access token
|
| 18 |
def get_salesforce_access_token():
|
|
|
|
|
|
|
|
|
|
|
|
|
| 19 |
auth_url = f"{SFDC_INSTANCE_URL}/services/oauth2/token"
|
| 20 |
data = {
|
| 21 |
'grant_type': 'password',
|
| 22 |
-
'client_id':
|
| 23 |
-
'client_secret':
|
| 24 |
'username': SFDC_USERNAME,
|
| 25 |
'password': f"{SFDC_PASSWORD}{SFDC_SECURITY_TOKEN}"
|
| 26 |
}
|
| 27 |
|
| 28 |
try:
|
| 29 |
-
response = requests.post(auth_url, data=data)
|
| 30 |
response.raise_for_status()
|
| 31 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 32 |
except requests.exceptions.RequestException as e:
|
| 33 |
-
print(f"
|
| 34 |
return None
|
| 35 |
|
| 36 |
-
#
|
| 37 |
access_token = get_salesforce_access_token()
|
| 38 |
|
| 39 |
@app.route('/')
|
|
@@ -46,18 +61,21 @@ def serve_static(filename):
|
|
| 46 |
|
| 47 |
@app.route('/get_ingredients', methods=['POST'])
|
| 48 |
def get_ingredients():
|
|
|
|
| 49 |
if not access_token:
|
| 50 |
-
|
|
|
|
|
|
|
| 51 |
|
| 52 |
dietary_preference = request.json.get('dietary_preference', '').lower()
|
| 53 |
|
| 54 |
# Salesforce SOQL query based on dietary preference
|
| 55 |
if dietary_preference == 'veg':
|
| 56 |
-
soql = "SELECT Sector_Detail_Name__c FROM Sector_Detail__c WHERE Category__c IN ('Veg', 'Both') LIMIT
|
| 57 |
elif dietary_preference == 'non-vegetarian':
|
| 58 |
-
soql = "SELECT Sector_Detail_Name__c FROM Sector_Detail__c WHERE Category__c IN ('Non-Veg', 'Both') LIMIT
|
| 59 |
else:
|
| 60 |
-
soql = "SELECT Sector_Detail_Name__c FROM Sector_Detail__c LIMIT
|
| 61 |
|
| 62 |
headers = {
|
| 63 |
"Authorization": f"Bearer {access_token}",
|
|
@@ -66,13 +84,18 @@ def get_ingredients():
|
|
| 66 |
url = f"{SFDC_INSTANCE_URL}/services/data/v57.0/query/?q={soql}"
|
| 67 |
|
| 68 |
try:
|
| 69 |
-
response = requests.get(url, headers=headers)
|
| 70 |
response.raise_for_status()
|
| 71 |
data = response.json()
|
| 72 |
ingredients = [record['Sector_Detail_Name__c'] for record in data['records'] if 'Sector_Detail_Name__c' in record]
|
| 73 |
return jsonify({"ingredients": ingredients})
|
| 74 |
except requests.exceptions.RequestException as e:
|
| 75 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 76 |
|
| 77 |
if __name__ == '__main__':
|
| 78 |
app.run(debug=True, host='0.0.0.0', port=7860)
|
|
|
|
| 2 |
import requests
|
| 3 |
from dotenv import load_dotenv
|
| 4 |
import os
|
| 5 |
+
import time
|
| 6 |
|
| 7 |
# Load environment variables from .env file
|
| 8 |
load_dotenv()
|
|
|
|
| 14 |
SFDC_PASSWORD = os.getenv('SFDC_PASSWORD')
|
| 15 |
SFDC_SECURITY_TOKEN = os.getenv('SFDC_SECURITY_TOKEN')
|
| 16 |
SFDC_INSTANCE_URL = os.getenv('SFDC_INSTANCE_URL', 'https://login.salesforce.com')
|
| 17 |
+
CLIENT_ID = os.getenv('SFDC_CLIENT_ID') # Add to .env
|
| 18 |
+
CLIENT_SECRET = os.getenv('SFDC_CLIENT_SECRET') # Add to .env
|
| 19 |
+
|
| 20 |
+
# Cache the access token and its expiration
|
| 21 |
+
access_token = None
|
| 22 |
+
token_expiry = 0
|
| 23 |
|
| 24 |
# Function to get Salesforce access token
|
| 25 |
def get_salesforce_access_token():
|
| 26 |
+
global access_token, token_expiry
|
| 27 |
+
if time.time() < token_expiry - 300: # Use cached token if valid (with 5-minute buffer)
|
| 28 |
+
return access_token
|
| 29 |
+
|
| 30 |
auth_url = f"{SFDC_INSTANCE_URL}/services/oauth2/token"
|
| 31 |
data = {
|
| 32 |
'grant_type': 'password',
|
| 33 |
+
'client_id': CLIENT_ID,
|
| 34 |
+
'client_secret': CLIENT_SECRET,
|
| 35 |
'username': SFDC_USERNAME,
|
| 36 |
'password': f"{SFDC_PASSWORD}{SFDC_SECURITY_TOKEN}"
|
| 37 |
}
|
| 38 |
|
| 39 |
try:
|
| 40 |
+
response = requests.post(auth_url, data=data, timeout=10)
|
| 41 |
response.raise_for_status()
|
| 42 |
+
token_data = response.json()
|
| 43 |
+
access_token = token_data['access_token']
|
| 44 |
+
token_expiry = time.time() + int(token_data.get('expires_in', 3600)) # Default 1 hour
|
| 45 |
+
print(f"New access token retrieved, expires at {time.ctime(token_expiry)}")
|
| 46 |
+
return access_token
|
| 47 |
except requests.exceptions.RequestException as e:
|
| 48 |
+
print(f"Authentication error: {e.response.text if 'response' in e.__dict__ else str(e)}")
|
| 49 |
return None
|
| 50 |
|
| 51 |
+
# Get initial token
|
| 52 |
access_token = get_salesforce_access_token()
|
| 53 |
|
| 54 |
@app.route('/')
|
|
|
|
| 61 |
|
| 62 |
@app.route('/get_ingredients', methods=['POST'])
|
| 63 |
def get_ingredients():
|
| 64 |
+
global access_token
|
| 65 |
if not access_token:
|
| 66 |
+
access_token = get_salesforce_access_token()
|
| 67 |
+
if not access_token:
|
| 68 |
+
return jsonify({"error": "Failed to authenticate with Salesforce"}), 500
|
| 69 |
|
| 70 |
dietary_preference = request.json.get('dietary_preference', '').lower()
|
| 71 |
|
| 72 |
# Salesforce SOQL query based on dietary preference
|
| 73 |
if dietary_preference == 'veg':
|
| 74 |
+
soql = "SELECT Sector_Detail_Name__c FROM Sector_Detail__c WHERE Category__c IN ('Veg', 'Both') LIMIT 200"
|
| 75 |
elif dietary_preference == 'non-vegetarian':
|
| 76 |
+
soql = "SELECT Sector_Detail_Name__c FROM Sector_Detail__c WHERE Category__c IN ('Non-Veg', 'Both') LIMIT 200"
|
| 77 |
else:
|
| 78 |
+
soql = "SELECT Sector_Detail_Name__c FROM Sector_Detail__c LIMIT 200" # Increased limit for 50+ ingredients
|
| 79 |
|
| 80 |
headers = {
|
| 81 |
"Authorization": f"Bearer {access_token}",
|
|
|
|
| 84 |
url = f"{SFDC_INSTANCE_URL}/services/data/v57.0/query/?q={soql}"
|
| 85 |
|
| 86 |
try:
|
| 87 |
+
response = requests.get(url, headers=headers, timeout=10)
|
| 88 |
response.raise_for_status()
|
| 89 |
data = response.json()
|
| 90 |
ingredients = [record['Sector_Detail_Name__c'] for record in data['records'] if 'Sector_Detail_Name__c' in record]
|
| 91 |
return jsonify({"ingredients": ingredients})
|
| 92 |
except requests.exceptions.RequestException as e:
|
| 93 |
+
error_msg = str(e)
|
| 94 |
+
if e.response and e.response.status_code == 401: # Unauthorized, try refreshing token
|
| 95 |
+
access_token = get_salesforce_access_token()
|
| 96 |
+
if access_token:
|
| 97 |
+
return get_ingredients() # Retry the request
|
| 98 |
+
return jsonify({"error": f"Failed to fetch ingredients: {error_msg}"}), 500
|
| 99 |
|
| 100 |
if __name__ == '__main__':
|
| 101 |
app.run(debug=True, host='0.0.0.0', port=7860)
|