DmitrMakeev
commited on
Commit
•
8c603ec
1
Parent(s):
8fd9446
Update app.py
Browse files
app.py
CHANGED
@@ -782,38 +782,55 @@ def send_request():
|
|
782 |
|
783 |
DATABASE_NAME = 'data_gc.db'
|
784 |
def update_or_insert_user(db_name, user_data, mapping_template):
|
|
|
785 |
conn = sqlite3.connect(db_name)
|
786 |
cursor = conn.cursor()
|
787 |
|
|
|
788 |
email = user_data.get('email')
|
789 |
if not email:
|
|
|
790 |
return
|
791 |
|
|
|
|
|
|
|
792 |
cursor.execute("SELECT web_st FROM contacts WHERE email = ?", (email,))
|
793 |
user = cursor.fetchone()
|
|
|
794 |
|
795 |
-
|
|
|
796 |
if user:
|
|
|
797 |
current_web_st = user[0] if user[0] is not None and user[0] != "" else 0
|
798 |
web_st_value = int(current_web_st) + 1
|
|
|
799 |
|
|
|
800 |
cursor.execute("UPDATE contacts SET web_st = ? WHERE email = ?", (web_st_value, email))
|
801 |
conn.commit()
|
802 |
conn.close()
|
|
|
803 |
else:
|
804 |
conn.close()
|
|
|
805 |
|
|
|
806 |
conn = sqlite3.connect(db_name)
|
807 |
cursor = conn.cursor()
|
808 |
|
|
|
809 |
transformed_data = {}
|
810 |
for json_key, db_column in mapping_template.items():
|
811 |
value = user_data.get(json_key, "")
|
812 |
if isinstance(value, list):
|
813 |
-
transformed_data[db_column] =
|
814 |
else:
|
815 |
transformed_data[db_column] = str(value)
|
|
|
816 |
|
|
|
817 |
required_fields = [
|
818 |
"vk_id", "chat_id", "ws_st", "ws_stop", "web_st", "fin_prog",
|
819 |
"b_city", "b_fin", "b_ban", "b_ign", "b_baners", "b_butt", "b_mess",
|
@@ -823,33 +840,35 @@ def update_or_insert_user(db_name, user_data, mapping_template):
|
|
823 |
for field in required_fields:
|
824 |
if field not in transformed_data:
|
825 |
transformed_data[field] = ""
|
|
|
826 |
|
|
|
827 |
if 'phone' in user_data:
|
828 |
phone = user_data['phone']
|
829 |
if phone.startswith('+'):
|
830 |
phone = phone[1:]
|
831 |
transformed_data['phone'] = phone
|
|
|
832 |
|
|
|
833 |
transformed_data['web_st'] = web_st_value
|
834 |
|
835 |
-
#
|
836 |
-
|
837 |
-
transformed_data['b_mess'] = json.dumps(user_data['messages'])
|
838 |
-
else:
|
839 |
-
transformed_data['b_mess'] = ""
|
840 |
-
|
841 |
-
# Проверка наличия массива баннеров и установка значения
|
842 |
if 'banners' in user_data and isinstance(user_data['banners'], list):
|
843 |
transformed_data['b_baners'] = '1'
|
844 |
else:
|
845 |
transformed_data['b_baners'] = '0'
|
|
|
846 |
|
847 |
-
#
|
848 |
if 'buttons' in user_data and isinstance(user_data['buttons'], list):
|
849 |
transformed_data['b_butt'] = '1'
|
850 |
else:
|
851 |
transformed_data['b_butt'] = '0'
|
|
|
852 |
|
|
|
853 |
if user:
|
854 |
update_query = "UPDATE contacts SET "
|
855 |
update_values = []
|
@@ -858,19 +877,23 @@ def update_or_insert_user(db_name, user_data, mapping_template):
|
|
858 |
update_values.append(value)
|
859 |
update_query = update_query.rstrip(", ") + " WHERE email = ?"
|
860 |
update_values.append(email)
|
|
|
861 |
cursor.execute(update_query, update_values)
|
862 |
else:
|
863 |
columns = ', '.join(transformed_data.keys())
|
864 |
placeholders = ', '.join('?' for _ in transformed_data)
|
865 |
insert_query = f"INSERT INTO contacts ({columns}) VALUES ({placeholders})"
|
866 |
insert_values = list(transformed_data.values())
|
|
|
867 |
cursor.execute(insert_query, insert_values)
|
868 |
|
|
|
869 |
conn.commit()
|
870 |
conn.close()
|
871 |
|
872 |
|
873 |
|
|
|
874 |
@app.route('/send_get_request', methods=['GET'])
|
875 |
def send_get_request():
|
876 |
token = request.args.get('token')
|
|
|
782 |
|
783 |
DATABASE_NAME = 'data_gc.db'
|
784 |
def update_or_insert_user(db_name, user_data, mapping_template):
|
785 |
+
# Подключение к базе данных
|
786 |
conn = sqlite3.connect(db_name)
|
787 |
cursor = conn.cursor()
|
788 |
|
789 |
+
# Получение email пользователя из данных
|
790 |
email = user_data.get('email')
|
791 |
if not email:
|
792 |
+
logging.error(f"User data missing email: {user_data}")
|
793 |
return
|
794 |
|
795 |
+
logging.debug(f"Processing user with email: {email}")
|
796 |
+
|
797 |
+
# Проверка существования пользователя в базе данных по email
|
798 |
cursor.execute("SELECT web_st FROM contacts WHERE email = ?", (email,))
|
799 |
user = cursor.fetchone()
|
800 |
+
logging.debug(f"User found: {user}")
|
801 |
|
802 |
+
# Вынесение увеличения значения web_st в отдельный блок
|
803 |
+
web_st_value = 1 # Инициализация значения web_st
|
804 |
if user:
|
805 |
+
# Проверка текущего значения web_st и его инкрементация
|
806 |
current_web_st = user[0] if user[0] is not None and user[0] != "" else 0
|
807 |
web_st_value = int(current_web_st) + 1
|
808 |
+
logging.debug(f"Calculated web_st_value: {web_st_value}")
|
809 |
|
810 |
+
# Обновление значения web_st
|
811 |
cursor.execute("UPDATE contacts SET web_st = ? WHERE email = ?", (web_st_value, email))
|
812 |
conn.commit()
|
813 |
conn.close()
|
814 |
+
logging.debug(f"User {email} web_st updated to {web_st_value}")
|
815 |
else:
|
816 |
conn.close()
|
817 |
+
logging.debug(f"User {email} not found, proceeding with insert")
|
818 |
|
819 |
+
# Открываем соединение снова для остальных операций
|
820 |
conn = sqlite3.connect(db_name)
|
821 |
cursor = conn.cursor()
|
822 |
|
823 |
+
# Преобразование данных пользователя на основе шаблона сопоставления
|
824 |
transformed_data = {}
|
825 |
for json_key, db_column in mapping_template.items():
|
826 |
value = user_data.get(json_key, "")
|
827 |
if isinstance(value, list):
|
828 |
+
transformed_data[db_column] = "1" if value else "0"
|
829 |
else:
|
830 |
transformed_data[db_column] = str(value)
|
831 |
+
logging.debug(f"Transformed data: {transformed_data}")
|
832 |
|
833 |
+
# Заполнение обязательных полей значениями по умолчанию
|
834 |
required_fields = [
|
835 |
"vk_id", "chat_id", "ws_st", "ws_stop", "web_st", "fin_prog",
|
836 |
"b_city", "b_fin", "b_ban", "b_ign", "b_baners", "b_butt", "b_mess",
|
|
|
840 |
for field in required_fields:
|
841 |
if field not in transformed_data:
|
842 |
transformed_data[field] = ""
|
843 |
+
logging.debug(f"Transformed data after adding required fields: {transformed_data}")
|
844 |
|
845 |
+
# Обработка номера телефона, если он есть
|
846 |
if 'phone' in user_data:
|
847 |
phone = user_data['phone']
|
848 |
if phone.startswith('+'):
|
849 |
phone = phone[1:]
|
850 |
transformed_data['phone'] = phone
|
851 |
+
logging.debug(f"Transformed data after phone processing: {transformed_data}")
|
852 |
|
853 |
+
# Добавление значения web_st в данные для вставки
|
854 |
transformed_data['web_st'] = web_st_value
|
855 |
|
856 |
+
# Выполнение двух пунктов:
|
857 |
+
# Баннеры: Проверяется наличие ключа banners в user_data и устанавливается b_baners в 1 или 0.
|
|
|
|
|
|
|
|
|
|
|
858 |
if 'banners' in user_data and isinstance(user_data['banners'], list):
|
859 |
transformed_data['b_baners'] = '1'
|
860 |
else:
|
861 |
transformed_data['b_baners'] = '0'
|
862 |
+
logging.debug(f"Transformed data after banners processing: {transformed_data}")
|
863 |
|
864 |
+
# Кнопки: Проверяется наличие ключа buttons в user_data и устанавливается b_butt в 1 или 0.
|
865 |
if 'buttons' in user_data and isinstance(user_data['buttons'], list):
|
866 |
transformed_data['b_butt'] = '1'
|
867 |
else:
|
868 |
transformed_data['b_butt'] = '0'
|
869 |
+
logging.debug(f"Transformed data after buttons processing: {transformed_data}")
|
870 |
|
871 |
+
# Обновление данных пользователя в базе данных
|
872 |
if user:
|
873 |
update_query = "UPDATE contacts SET "
|
874 |
update_values = []
|
|
|
877 |
update_values.append(value)
|
878 |
update_query = update_query.rstrip(", ") + " WHERE email = ?"
|
879 |
update_values.append(email)
|
880 |
+
logging.debug(f"Update query: {update_query} with values: {update_values}")
|
881 |
cursor.execute(update_query, update_values)
|
882 |
else:
|
883 |
columns = ', '.join(transformed_data.keys())
|
884 |
placeholders = ', '.join('?' for _ in transformed_data)
|
885 |
insert_query = f"INSERT INTO contacts ({columns}) VALUES ({placeholders})"
|
886 |
insert_values = list(transformed_data.values())
|
887 |
+
logging.debug(f"Insert query: {insert_query} with values: {insert_values}")
|
888 |
cursor.execute(insert_query, insert_values)
|
889 |
|
890 |
+
# Подтверждение изменений и закрытие соединения
|
891 |
conn.commit()
|
892 |
conn.close()
|
893 |
|
894 |
|
895 |
|
896 |
+
|
897 |
@app.route('/send_get_request', methods=['GET'])
|
898 |
def send_get_request():
|
899 |
token = request.args.get('token')
|