DmitrMakeev commited on
Commit
497313b
·
verified ·
1 Parent(s): 24c29c0

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +63 -50
app.py CHANGED
@@ -856,76 +856,89 @@ print(calculator.generate_report(results))
856
 
857
  @app.route('/calculation', methods=['POST'])
858
  def handle_calculation():
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
859
  try:
860
  data = request.get_json()
861
 
862
- # Проверка обязательных полей
863
- if not data or 'profileSettings' not in data or 'fertilizerConstants' not in data:
864
- return jsonify({'error': 'Неверный формат данных'}), 400
 
865
 
866
  # Инициализация калькулятора
867
  calculator = PrecisionNutrientCalculator()
868
- calculator.volume = float(data['profileSettings'].get('liters', 100))
869
-
870
- # Базовый профиль (начальные значения)
871
- BASE_PROFILE = {
872
- "P": 50, # Фосфор
873
- "K": 210, # Калий
874
- "Mg": 120, # Магний
875
- "Ca": 150, # Кальций
876
- "S": 100, # Сера
877
- "N (NO3-)": 0, # Рассчитывается автоматически
878
- "N (NH4+)": 0 # Рассчитывается автоматически
 
 
879
  }
880
 
881
- # Обновление базового профиля данными из запроса
882
- for element in BASE_PROFILE:
883
- if element in data['profileSettings']:
884
- BASE_PROFILE[element] = float(data['profileSettings'][element])
885
-
886
- # Расчет соотношения азотов
887
- total_n = float(data['profileSettings'].get('TOTAL_NITROG', 125.0))
888
- no3_ratio = float(data['profileSettings'].get('NO3_RAT', 8.35)) # Берем значение из запроса
889
- nh4_ratio = 1.0 # Фиксированное значение для NH4
890
 
891
  total_parts = no3_ratio + nh4_ratio
892
- BASE_PROFILE['N (NO3-)'] = total_n * (no3_ratio / total_parts)
893
- BASE_PROFILE['N (NH4+)'] = total_n * (nh4_ratio / total_parts)
894
-
895
- # Настройка целевого профиля
896
- calculator.target = BASE_PROFILE
897
-
898
- # Установка констант удобрений из запроса
899
- calculator.fertilizers = data['fertilizerConstants']
900
-
901
- # Выполнение расчета
902
- results = calculator.calculate()
903
-
904
- # Подготовка ответа
905
- response = {
906
- "actual_profile": calculator.actual, # Возвращаем сырые данные
907
- "fertilizers": calculator.results, # Возвращаем сырые данные
 
908
  "nitrogen_ratios": {
909
  "NH4_RATIO": nh4_ratio,
910
  "NO3_RATIO": no3_ratio,
911
  "TOTAL_NITROGEN": total_n
912
  },
913
- "total_ppm": sum(calculator.actual.values()), # Сырое значение
914
  "deficits": results.get('deficits', {})
915
- }
916
 
917
- # Логирование проблем
918
- if any(value is None or value < 0 for value in calculator.actual.values()):
919
- print("ВНИМАНИЕ: В расчетах обнаружены некорректные значения!")
920
- print(f"Фактический профиль: {calculator.actual}")
921
 
922
- return jsonify(response)
923
 
924
  except Exception as e:
925
- # Логирование ошибки
926
- print(f"Ошибка при обработке запроса: {str(e)}")
927
- return jsonify({'error': str(e)}), 500
928
-
929
 
930
 
931
 
 
856
 
857
  @app.route('/calculation', methods=['POST'])
858
  def handle_calculation():
859
+ # Создаем базовый ответ с дефолтными значениями
860
+ response = {
861
+ "actual_profile": {},
862
+ "fertilizers": {},
863
+ "nitrogen_ratios": {
864
+ "NH4_RATIO": 1.0,
865
+ "NO3_RATIO": 8.35,
866
+ "TOTAL_NITROGEN": 125.0
867
+ },
868
+ "total_ppm": 0,
869
+ "deficits": {},
870
+ "warnings": [],
871
+ "errors": None
872
+ }
873
+
874
  try:
875
  data = request.get_json()
876
 
877
+ # Проверка данных
878
+ if not data:
879
+ response['errors'] = "Отсутствуют данные в запросе"
880
+ return jsonify(response), 200 # Все равно возвращаем 200 OK
881
 
882
  # Инициализация калькулятора
883
  calculator = PrecisionNutrientCalculator()
884
+
885
+ # Устанавливаем объем
886
+ calculator.volume = float(data.get('profileSettings', {}).get('liters', 100))
887
+
888
+ # Базовый профиль с защитой от отсутствия значений
889
+ base_profile = {
890
+ "P": float(data.get('profileSettings', {}).get('P', 50)),
891
+ "K": float(data.get('profileSettings', {}).get('K', 210)),
892
+ "Mg": float(data.get('profileSettings', {}).get('Mg', 120)),
893
+ "Ca": float(data.get('profileSettings', {}).get('Ca', 150)),
894
+ "S": float(data.get('profileSettings', {}).get('S', 100)),
895
+ "N (NO3-)": 0,
896
+ "N (NH4+)": 0
897
  }
898
 
899
+ # Расчет азота
900
+ total_n = float(data.get('profileSettings', {}).get('TOTAL_NITROG', 125.0))
901
+ no3_ratio = float(data.get('profileSettings', {}).get('NO3_RAT', 8.35))
902
+ nh4_ratio = 1.0
 
 
 
 
 
903
 
904
  total_parts = no3_ratio + nh4_ratio
905
+ base_profile['N (NO3-)'] = total_n * (no3_ratio / total_parts)
906
+ base_profile['N (NH4+)'] = total_n * (nh4_ratio / total_parts)
907
+
908
+ calculator.target = base_profile
909
+ calculator.fertilizers = data.get('fertilizerConstants', NUTRIENT_CONTENT_IN_FERTILIZERS)
910
+
911
+ # Защищенный расчет
912
+ try:
913
+ results = calculator.calculate()
914
+ except Exception as calc_error:
915
+ response['warnings'].append(f"Ошибка расчета: {str(calc_error)}")
916
+ results = {'deficits': {}}
917
+
918
+ # Формируем ответ
919
+ response.update({
920
+ "actual_profile": {k: round(v, 3) for k, v in calculator.actual.items()},
921
+ "fertilizers": {k: round(v['граммы'], 3) for k, v in calculator.results.items()},
922
  "nitrogen_ratios": {
923
  "NH4_RATIO": nh4_ratio,
924
  "NO3_RATIO": no3_ratio,
925
  "TOTAL_NITROGEN": total_n
926
  },
927
+ "total_ppm": round(sum(calculator.actual.values()), 3),
928
  "deficits": results.get('deficits', {})
929
+ })
930
 
931
+ # Проверка на отрицательные значения
932
+ if any(v < 0 for v in calculator.actual.values()):
933
+ response['warnings'].append("Обнаружены отрицательные значения в профиле")
 
934
 
935
+ return jsonify(response), 200
936
 
937
  except Exception as e:
938
+ # Логируем ошибку, но все равно возвращаем ответ
939
+ print(f"Критическая ошибка: {str(e)}")
940
+ response['errors'] = str(e)
941
+ return jsonify(response), 200 # Все равно 200 OK
942
 
943
 
944