DmitrMakeev commited on
Commit
482d1c3
·
verified ·
1 Parent(s): c38a672

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +11 -22
app.py CHANGED
@@ -2025,6 +2025,15 @@ def from_shop_st3():
2025
  except Exception as e:
2026
  return json.dumps({"error": str(e)}), 500
2027
 
 
 
 
 
 
 
 
 
 
2028
  @app.route('/allow', methods=['GET'])
2029
  def from_allow():
2030
  try:
@@ -2044,8 +2053,7 @@ def from_allow():
2044
  if not email or not phone:
2045
  return json.dumps({"error": "Email and phone are required"}), 400
2046
 
2047
- # Очистка номера телефона
2048
- phone = clean_phone_number_ss(phone)
2049
 
2050
  conn = sqlite3.connect(DATABASE6)
2051
  cursor = conn.cursor()
@@ -2054,66 +2062,47 @@ def from_allow():
2054
  result = cursor.fetchone()
2055
 
2056
  if result:
2057
- # Если есть запись, загружаем текущий JSON из поля pr5
2058
  pr5 = result[21] if result[21] else '{}'
2059
  pr5_data = json.loads(pr5)
2060
  print(f"Existing record found. Loaded JSON: {pr5_data}")
2061
  else:
2062
- # Если записи нет, создаем пустой словарь
2063
  pr5_data = {}
2064
  print("No existing record found. Initialized new JSON.")
2065
 
2066
  if del_flag == '1':
2067
- # Удаление ключа из JSON
2068
  if module in pr5_data:
2069
  del pr5_data[module]
2070
  print(f"Key '{module}' found and deleted from JSON.")
2071
  else:
2072
  print(f"Key '{module}' not found in JSON.")
2073
  elif module and status:
2074
- # Обновление значения существующего ключа или добавление нового
2075
  pr5_data[module] = status
2076
  print(f"Updated JSON with key '{module}' and status '{status}'.")
2077
 
2078
  pr5_json = json.dumps(pr5_data)
2079
  print(f"Updated JSON to be saved: {pr5_json}")
2080
 
2081
- # Получение текущей даты и времени в Московском часовом поясе
2082
  utc_now = datetime.utcnow()
2083
  msk_tz = pytz.timezone('Europe/Moscow')
2084
  msk_now = utc_now.replace(tzinfo=pytz.utc).astimezone(msk_tz)
2085
  data_on = msk_now.strftime('%Y-%m-%d %H:%M:%S')
2086
 
2087
- # Исключаем все столбцы, кроме name, phone, email, pr5, n_con, data_on
2088
  columns_to_update = ['name', 'phone', 'email', 'pr5', 'n_con', 'data_on']
2089
  values_to_update = [name, phone, email, pr5_json, n_con_flag, data_on]
2090
 
2091
  if result:
2092
- # Обновляем только те поля, которые переданы в запросе
2093
  set_clause = ', '.join([f"{col} = ?" for col in columns_to_update])
2094
  query = f"UPDATE contacts SET {set_clause} WHERE email = ? OR phone = ?"
2095
  cursor.execute(query, values_to_update + [email, phone])
2096
  print("Record updated in database.")
2097
  else:
2098
- # Вставляем новые данные
2099
  query = f"INSERT INTO contacts ({', '.join(columns_to_update)}) VALUES ({', '.join(['?' for _ in columns_to_update])})"
2100
  cursor.execute(query, values_to_update)
2101
  print("New record inserted into database.")
2102
 
2103
  conn.commit()
2104
-
2105
- # Проверка что данные сохранились правильно
2106
- cursor.execute("SELECT * FROM contacts WHERE email = ? OR phone = ?", (email, phone))
2107
- result_check = cursor.fetchone()
2108
- if result_check:
2109
- pr5_check = result_check[21] if result_check[21] else '{}'
2110
- pr5_data_check = json.loads(pr5_check)
2111
- print(f"Post-commit check. Loaded JSON: {pr5_data_check}")
2112
- else:
2113
- print("Post-commit check failed. No record found.")
2114
 
2115
- # Замена NULL на пустые строки
2116
- replace_null_with_empty_string(conn)
2117
  print("NULL values replaced with empty strings if any.")
2118
 
2119
  conn.close()
 
2025
  except Exception as e:
2026
  return json.dumps({"error": str(e)}), 500
2027
 
2028
+ def clean_phone_number_1(phone):
2029
+ # Пример функции очистки номера телефона
2030
+ return ''.join(filter(str.isdigit, phone))
2031
+
2032
+ def replace_null_with_empty_1(conn):
2033
+ cursor = conn.cursor()
2034
+ cursor.execute("UPDATE contacts SET pr5 = '' WHERE pr5 IS NULL")
2035
+ conn.commit()
2036
+
2037
  @app.route('/allow', methods=['GET'])
2038
  def from_allow():
2039
  try:
 
2053
  if not email or not phone:
2054
  return json.dumps({"error": "Email and phone are required"}), 400
2055
 
2056
+ phone = clean_phone_number_1(phone)
 
2057
 
2058
  conn = sqlite3.connect(DATABASE6)
2059
  cursor = conn.cursor()
 
2062
  result = cursor.fetchone()
2063
 
2064
  if result:
 
2065
  pr5 = result[21] if result[21] else '{}'
2066
  pr5_data = json.loads(pr5)
2067
  print(f"Existing record found. Loaded JSON: {pr5_data}")
2068
  else:
 
2069
  pr5_data = {}
2070
  print("No existing record found. Initialized new JSON.")
2071
 
2072
  if del_flag == '1':
 
2073
  if module in pr5_data:
2074
  del pr5_data[module]
2075
  print(f"Key '{module}' found and deleted from JSON.")
2076
  else:
2077
  print(f"Key '{module}' not found in JSON.")
2078
  elif module and status:
 
2079
  pr5_data[module] = status
2080
  print(f"Updated JSON with key '{module}' and status '{status}'.")
2081
 
2082
  pr5_json = json.dumps(pr5_data)
2083
  print(f"Updated JSON to be saved: {pr5_json}")
2084
 
 
2085
  utc_now = datetime.utcnow()
2086
  msk_tz = pytz.timezone('Europe/Moscow')
2087
  msk_now = utc_now.replace(tzinfo=pytz.utc).astimezone(msk_tz)
2088
  data_on = msk_now.strftime('%Y-%m-%d %H:%M:%S')
2089
 
 
2090
  columns_to_update = ['name', 'phone', 'email', 'pr5', 'n_con', 'data_on']
2091
  values_to_update = [name, phone, email, pr5_json, n_con_flag, data_on]
2092
 
2093
  if result:
 
2094
  set_clause = ', '.join([f"{col} = ?" for col in columns_to_update])
2095
  query = f"UPDATE contacts SET {set_clause} WHERE email = ? OR phone = ?"
2096
  cursor.execute(query, values_to_update + [email, phone])
2097
  print("Record updated in database.")
2098
  else:
 
2099
  query = f"INSERT INTO contacts ({', '.join(columns_to_update)}) VALUES ({', '.join(['?' for _ in columns_to_update])})"
2100
  cursor.execute(query, values_to_update)
2101
  print("New record inserted into database.")
2102
 
2103
  conn.commit()
 
 
 
 
 
 
 
 
 
 
2104
 
2105
+ replace_null_with_empty_1(conn)
 
2106
  print("NULL values replaced with empty strings if any.")
2107
 
2108
  conn.close()