DmitrMakeev commited on
Commit
738b34b
·
verified ·
1 Parent(s): aef6b00

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +75 -50
app.py CHANGED
@@ -982,77 +982,102 @@ if __name__ == "__main__":
982
  @app.route('/calculation', methods=['POST'])
983
  def handle_calculation():
984
  try:
985
- # Получаем данные как есть, без преобразований
986
- data = request.get_json()
987
-
988
- # Проверяем только самое необходимое
989
- if not data or 'fertilizerConstants' not in data or 'profileSettings' not in data:
990
- return jsonify({"error": "Требуются fertilizerConstants и profileSettings"}), 400
991
 
992
- # Берем глобальные переменные (они уже объявлены выше)
993
- global NO3_RATIO, NH4_RATIO, TOTAL_NITROGEN, VOLUME_LITERS
994
-
995
- # Обновляем глобальные переменные из запроса (если переданы)
996
- NO3_RATIO = float(data.get('NO3_RATIO', NO3_RATIO))
997
- NH4_RATIO = float(data.get('NH4_RATIO', NH4_RATIO))
998
- TOTAL_NITROGEN = float(data['profileSettings'].get('N', TOTAL_NITROGEN))
999
- VOLUME_LITERS = int(data['profileSettings'].get('liters', VOLUME_LITERS))
1000
 
1001
- # Создаем калькулятор
1002
- calculator = NutrientCalculator(volume_liters=VOLUME_LITERS)
1003
-
1004
- # Обновляем профиль из полученных данных
1005
- calculator.target_profile.update({
1006
- 'P': float(data['profileSettings']['P']),
1007
- 'K': float(data['profileSettings']['K']),
1008
- 'Mg': float(data['profileSettings']['Mg']),
1009
- 'Ca': float(data['profileSettings']['Ca']),
1010
- 'S': float(data['profileSettings']['S']),
1011
- 'N (NO3-)': float(data['profileSettings']['NO3']),
1012
- 'N (NH4+)': float(data['profileSettings']['NH4'])
1013
- })
1014
-
1015
- # Конвертируем удобрения (используем твой формат как есть)
1016
- converted_fertilizers = {
1017
  "Кальциевая селитра": {
1018
- "N (NO3-)": data['fertilizerConstants']['CaN2O6']['NO3'] / 100,
1019
- "Ca": data['fertilizerConstants']['CaN2O6']['Ca'] / 100
1020
  },
1021
  "Калий азотнокислый": {
1022
- "N (NO3-)": data['fertilizerConstants']['KNO3']['NO3'] / 100,
1023
- "K": data['fertilizerConstants']['KNO3']['K'] / 100
1024
  },
1025
  "Аммоний азотнокислый": {
1026
- "N (NO3-)": data['fertilizerConstants']['NH4NO3']['NO3'] / 100,
1027
- "N (NH4+)": data['fertilizerConstants']['NH4NO3']['NH4'] / 100
1028
  },
1029
  "Сульфат магния": {
1030
- "Mg": data['fertilizerConstants']['MgSO4']['Mg'] / 100,
1031
- "S": data['fertilizerConstants']['MgSO4']['S'] / 100
1032
  },
1033
  "Монофосфат калия": {
1034
- "P": data['fertilizerConstants']['KH2PO4']['P'] / 100,
1035
- "K": data['fertilizerConstants']['KH2PO4']['K'] / 100
1036
  },
1037
  "Калий сернокислый": {
1038
- "K": data['fertilizerConstants']['K2SO4']['K'] / 100,
1039
- "S": data['fertilizerConstants']['K2SO4']['S'] / 100
1040
  }
1041
  }
 
 
 
 
1042
 
1043
- calculator.fertilizers = converted_fertilizers
 
 
1044
 
1045
- # Запускаем расчет
 
 
 
 
 
 
 
 
 
 
 
1046
  calculator.calculate()
1047
 
1048
- # Возвращаем результаты в том же формате, что и раньше
1049
- return jsonify(calculator.get_web_results())
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1050
 
1051
  except Exception as e:
1052
- return jsonify({
1053
- "error": "Ошибка расчета",
1054
- "details": str(e)
1055
- }), 500
1056
 
1057
 
1058
  if __name__ == '__main__':
 
982
  @app.route('/calculation', methods=['POST'])
983
  def handle_calculation():
984
  try:
985
+ # Получаем сырые данные
986
+ raw_data = request.get_json()
987
+ print("Получены данные:", raw_data) # Логируем входящие данные
 
 
 
988
 
989
+ # Проверяем минимально необходимую структуру
990
+ if not raw_data or 'fertilizerConstants' not in raw_data or 'profileSettings' not in raw_data:
991
+ return jsonify({"error": "Требуются fertilizerConstants и profileSettings"}), 400
 
 
 
 
 
992
 
993
+ # Парсим данные удобрений (переводим % в доли)
994
+ fertilizers = {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
995
  "Кальциевая селитра": {
996
+ "N (NO3-)": raw_data['fertilizerConstants']['CaN2O6']['NO3'] / 100,
997
+ "Ca": raw_data['fertilizerConstants']['CaN2O6']['Ca'] / 100
998
  },
999
  "Калий азотнокислый": {
1000
+ "N (NO3-)": raw_data['fertilizerConstants']['KNO3']['NO3'] / 100,
1001
+ "K": raw_data['fertilizerConstants']['KNO3']['K'] / 100
1002
  },
1003
  "Аммоний азотнокислый": {
1004
+ "N (NO3-)": raw_data['fertilizerConstants']['NH4NO3']['NO3'] / 100,
1005
+ "N (NH4+)": raw_data['fertilizerConstants']['NH4NO3']['NH4'] / 100
1006
  },
1007
  "Сульфат магния": {
1008
+ "Mg": raw_data['fertilizerConstants']['MgSO4']['Mg'] / 100,
1009
+ "S": raw_data['fertilizerConstants']['MgSO4']['S'] / 100
1010
  },
1011
  "Монофосфат калия": {
1012
+ "P": raw_data['fertilizerConstants']['KH2PO4']['P'] / 100,
1013
+ "K": raw_data['fertilizerConstants']['KH2PO4']['K'] / 100
1014
  },
1015
  "Калий сернокислый": {
1016
+ "K": raw_data['fertilizerConstants']['K2SO4']['K'] / 100,
1017
+ "S": raw_data['fertilizerConstants']['K2SO4']['S'] / 100
1018
  }
1019
  }
1020
+
1021
+ # Получаем настройки профиля
1022
+ profile = raw_data['profileSettings']
1023
+ liters = int(profile.get('liters', 100))
1024
 
1025
+ # Создаем калькулятор
1026
+ calculator = NutrientCalculator(volume_liters=liters)
1027
+ calculator.fertilizers = fertilizers
1028
 
1029
+ # Устанавливаем целевой профиль
1030
+ calculator.target_profile.update({
1031
+ 'P': float(profile['P']),
1032
+ 'K': float(profile['K']),
1033
+ 'Mg': float(profile['Mg']),
1034
+ 'Ca': float(profile['Ca']),
1035
+ 'S': float(profile['S']),
1036
+ 'N (NO3-)': float(profile['NO3']),
1037
+ 'N (NH4+)': float(profile['NH4'])
1038
+ })
1039
+
1040
+ # РАСЧЕТ (без изменения глобальных переменных)
1041
  calculator.calculate()
1042
 
1043
+ # Формируем ответ
1044
+ response = {
1045
+ "fertilizers": [],
1046
+ "profile": [],
1047
+ "ec": calculator.calculate_ec(),
1048
+ "deficits": calculator.calculate_deficits()
1049
+ }
1050
+
1051
+ # Заполняем удобрения
1052
+ fert_map = {
1053
+ "Кальциевая селитра": "calcium_nitrate",
1054
+ "Калий азотнокислый": "potassium_nitrate",
1055
+ "Аммоний азотнокислый": "ammonium_nitrate",
1056
+ "Сульфат магния": "magnesium_sulfate",
1057
+ "Монофосфат калия": "monopotassium_phosphate",
1058
+ "Калий сернокислый": "potassium_sulfate"
1059
+ }
1060
+
1061
+ for fert_name, result in calculator.results.items():
1062
+ if fert_name in fert_map:
1063
+ response["fertilizers"].append({
1064
+ "name": fert_map[fert_name],
1065
+ "grams": round(result['граммы'], 3)
1066
+ })
1067
+
1068
+ # Заполняем профиль
1069
+ for element, value in calculator.actual_profile.items():
1070
+ response["profile"].append({
1071
+ "element": element.replace(' (NO3-)', '-NO3').replace(' (NH4+)', '-NH4'),
1072
+ "ppm": round(value, 1)
1073
+ })
1074
+
1075
+ print("Результат расчета:", response) # Логируем результат
1076
+ return jsonify(response)
1077
 
1078
  except Exception as e:
1079
+ print("Ошибка расчета:", str(e)) # Логируем ошибку
1080
+ return jsonify({"error": str(e)}), 500
 
 
1081
 
1082
 
1083
  if __name__ == '__main__':