Spaces:
Build error
Build error
Update app.py
Browse files3 unmodified lines4567891011121314152 unmodified lines18192021222324252627286 unmodified lines35363738394041424344454647484950515253545556575859606162636465666768694 unmodified lines747576777879808182834 unmodified lines88899091929394953 unmodified linesimport osimport logginglogging.basicConfig(level=logging.DEBUG)load_dotenv()app = Flask(__name__, template_folder='templates', static_folder='static')def get_salesforce_connection():try:sf = Salesforce(2 unmodified linessecurity_token=os.getenv('SFDC_SECURITY_TOKEN'),domain=os.getenv('SFDC_DOMAIN', 'login'))return sfexcept Exception as e:print(f"Error connecting to Salesforce: {e}")return Nonesf = get_salesforce_connection()@app.route('/')6 unmodified lines@app.route('/get_ingredients', methods=['POST'])def get_ingredients():dietary_preference = request.json.get('dietary_preference', '').strip().lower()logging.debug(f"Received dietary preference: {dietary_preference}")if dietary_preference == 'vegetable':logging.debug("Fetching ingredients for Vegetables...")soql = "SELECT Name, Image_URL__c, Category__c FROM Sector_Detail__c WHERE Category__c = 'Veg' LIMIT 200"elif dietary_preference == 'non-vegetarian':logging.debug("Fetching ingredients for Non-Vegetarian...")soql = "SELECT Name, Image_URL__c, Category__c FROM Sector_Detail__c WHERE Category__c = 'Non-Veg' LIMIT 200"else:logging.debug("Invalid dietary preference received.")return jsonify({"error": "Invalid dietary preference."}), 400try:result = sf.query(soql)ingredients = [{"name": record['Name'], "image_url": record.get('Image_URL__c', ''), "category": record.get('Category__c', '')}for record in result['records'] if 'Name' in record]logging.debug(f"Fetched ingredients: {[ing['name'] + ' (' + ing['category'] + ')' for ing in ingredients]}")return jsonify({"ingredients": ingredients})except Exception as e:logging.error(f"Error while fetching ingredients: {str(e)}")return jsonify({"error": f"Failed to fetch ingredients: {str(e)}"}), 500@app.route('/get_menu_items_by_ingredients', methods=['POST'])def get_menu_items_by_ingredients():ingredients = request.json.get('ingredients', '').strip().lower()logging.debug(f"Received ingredients: {ingredients}")# Assuming Menu_Items__c object has an Ingredients__c field to match with selected ingredientssoql = f"SELECT Item_Name__c, Image_URL__c FROM Menu_Items__c WHERE Ingredients__c LIKE '%{ingredients}%' LIMIT 200"4 unmodified lines{"name": record['Item_Name__c'], "image_url": record.get('Image_URL__c', '')}for record in result['records'] if 'Item_Name__c' in record]logging.debug(f"Fetched {len(menu_items)} menu items.")return jsonify({"menu_items": menu_items})except Exception as e:logging.error(f"Error while fetching menu items: {str(e)}")return jsonify({"error": f"Failed to fetch menu items: {str(e)}"}), 500@app.route('/submit_ingredients', methods=['POST'])4 unmodified linesif not ingredients:return jsonify({'error': 'No ingredients selected'}), 400logging.debug(f"Ingredients submitted: {ingredients}")return jsonify({'success': True})if __name__ == '__main__':app.run(debug=True, host='0.0.0.0', port=7860)3 unmodified lines456789101112131415161718192 unmodified lines222324252627282930313233346 unmodified lines4142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990914 unmodified lines969798991001011021031041054 unmodified lines1101111121131141151161173 unmodified linesimport osimport logging# Load environment variables from .env fileload_dotenv()# Set up logginglogging.basicConfig(level=logging.INFO)logger = logging.getLogger(__name__)app = Flask(__name__, template_folder='templates', static_folder='static')# Function to get Salesforce connectiondef get_salesforce_connection():try:sf = Salesforce(2 unmodified linessecurity_token=os.getenv('SFDC_SECURITY_TOKEN'),domain=os.getenv('SFDC_DOMAIN', 'login'))logger.info("Successfully connected to Salesforce")return sfexcept Exception as e:logger.error(f"Error connecting to Salesforce: {e}")return None# Initialize Salesforce connectionsf = get_salesforce_connection()@app.route('/')6 unmodified lines@app.route('/get_ingredients', methods=['POST'])def get_ingredients():global sfif not sf:sf = get_salesforce_connection()if not sf:return jsonify({"error": "Failed to connect to Salesforce"}), 500dietary_preference = request.json.get('dietary_preference', '').lower()# Map dietary preference to SOQL conditionpreference_map = {'vegetarian': "Category__c = 'Veg'",'non-vegetarian': "Category__c = 'Non-Veg'",'both': None # No condition to fetch all records}condition = preference_map.get(dietary_preference)try:# Construct the base querysoql = "SELECT Name, Image_URL__c, Category__c FROM Sector_Detail__c"if condition:soql += f" WHERE {condition}"soql += " LIMIT 200"logger.info(f"Executing SOQL query: {soql}")result = sf.query(soql)ingredients = [{"name": record['Name'], "image_url": record.get('Image_URL__c', ''), "category": record.get('Category__c', '')}for record in result['records'] if 'Name' in record]logger.info(f"Fetched {len(ingredients)} ingredients: {[ing['name'] + ' (' + ing['category'] + ')' for ing in ingredients]}")return jsonify({"ingredients": ingredients})except Exception as e:logger.error(f"Failed to fetch ingredients: {str(e)}")return jsonify({"error": f"Failed to fetch ingredients: {str(e)}"}), 500@app.route('/get_menu_items_by_ingredients', methods=['POST'])def get_menu_items_by_ingredients():global sfif not sf:sf = get_salesforce_connection()if not sf:return jsonify({"error": "Failed to connect to Salesforce"}), 500ingredients = request.json.get('ingredients', '').strip().lower()logger.info(f"Received ingredients: {ingredients}")# Assuming Menu_Items__c object has an Ingredients__c field to match with selected ingredientssoql = f"SELECT Item_Name__c, Image_URL__c FROM Menu_Items__c WHERE Ingredients__c LIKE '%{ingredients}%' LIMIT 200"4 unmodified lines{"name": record['Item_Name__c'], "image_url": record.get('Image_URL__c', '')}for record in result['records'] if 'Item_Name__c' in record]logger.info(f"Fetched {len(menu_items)} menu items.")return jsonify({"menu_items": menu_items})except Exception as e:logger.error(f"Error while fetching menu items: {str(e)}")return jsonify({"error": f"Failed to fetch menu items: {str(e)}"}), 500@app.route('/submit_ingredients', methods=['POST'])4 unmodified linesif not ingredients:return jsonify({'error': 'No ingredients selected'}), 400logger.info(f"Ingredients submitted: {ingredients}")return jsonify({'success': True})if __name__ == '__main__':app.run(debug=True, host='0.0.0.0', port=7860)
app.py+44-22