Spaces:
Sleeping
Sleeping
from flask import Flask, render_template, send_from_directory, request, jsonify | |
import requests | |
from dotenv import load_dotenv | |
import os | |
# Load environment variables from .env file | |
load_dotenv() | |
app = Flask(__name__, template_folder='templates', static_folder='static') | |
# Salesforce credentials from environment variables | |
SFDC_USERNAME = os.getenv('SFDC_USERNAME') | |
SFDC_PASSWORD = os.getenv('SFDC_PASSWORD') | |
SFDC_SECURITY_TOKEN = os.getenv('SFDC_SECURITY_TOKEN') | |
SFDC_INSTANCE_URL = os.getenv('SFDC_INSTANCE_URL', 'https://login.salesforce.com') | |
# Function to get Salesforce access token | |
def get_salesforce_access_token(): | |
auth_url = f"{SFDC_INSTANCE_URL}/services/oauth2/token" | |
data = { | |
'grant_type': 'password', | |
'client_id': 'your_client_id', # Replace with your Connected App Client ID | |
'client_secret': 'your_client_secret', # Replace with your Connected App Client Secret | |
'username': SFDC_USERNAME, | |
'password': f"{SFDC_PASSWORD}{SFDC_SECURITY_TOKEN}" | |
} | |
try: | |
response = requests.post(auth_url, data=data) | |
response.raise_for_status() | |
return response.json()['access_token'] | |
except requests.exceptions.RequestException as e: | |
print(f"Error getting access token: {e}") | |
return None | |
# Cache the access token | |
access_token = get_salesforce_access_token() | |
def index(): | |
return render_template('index.html') | |
def serve_static(filename): | |
return send_from_directory('static', filename) | |
def get_ingredients(): | |
if not access_token: | |
return jsonify({"error": "Failed to authenticate with Salesforce"}), 500 | |
dietary_preference = request.json.get('dietary_preference', '').lower() | |
# Salesforce SOQL query based on dietary preference | |
if dietary_preference == 'veg': | |
soql = "SELECT Sector_Detail_Name__c FROM Sector_Detail__c WHERE Category__c IN ('Veg', 'Both') LIMIT 100" | |
elif dietary_preference == 'non-vegetarian': | |
soql = "SELECT Sector_Detail_Name__c FROM Sector_Detail__c WHERE Category__c IN ('Non-Veg', 'Both') LIMIT 100" | |
else: | |
soql = "SELECT Sector_Detail_Name__c FROM Sector_Detail__c LIMIT 100" # Default case | |
headers = { | |
"Authorization": f"Bearer {access_token}", | |
"Content-Type": "application/json" | |
} | |
url = f"{SFDC_INSTANCE_URL}/services/data/v57.0/query/?q={soql}" | |
try: | |
response = requests.get(url, headers=headers) | |
response.raise_for_status() | |
data = response.json() | |
ingredients = [record['Sector_Detail_Name__c'] for record in data['records'] if 'Sector_Detail_Name__c' in record] | |
return jsonify({"ingredients": ingredients}) | |
except requests.exceptions.RequestException as e: | |
return jsonify({"error": str(e)}), 500 | |
if __name__ == '__main__': | |
app.run(debug=True, host='0.0.0.0', port=7860) |