DmitrMakeev
commited on
Commit
•
4d79d7b
1
Parent(s):
888e945
Update app.py
Browse files
app.py
CHANGED
@@ -782,81 +782,99 @@ 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 |
-
|
789 |
-
|
790 |
-
|
|
|
|
|
791 |
|
792 |
-
|
793 |
-
|
|
|
|
|
|
|
|
|
794 |
|
|
|
795 |
web_st_value = 1 # Инициализация значения web_st
|
796 |
-
if user:
|
797 |
-
|
798 |
-
|
799 |
-
|
800 |
-
|
801 |
-
|
802 |
-
|
803 |
-
|
|
|
|
|
|
|
804 |
else:
|
805 |
-
conn.close()
|
|
|
806 |
|
807 |
-
|
808 |
-
|
|
|
809 |
|
810 |
-
|
811 |
-
|
812 |
-
|
813 |
-
|
814 |
-
|
|
|
815 |
else:
|
816 |
-
transformed_data[db_column] = str(value)
|
817 |
-
logging.debug(f"Transformed data: {transformed_data}")
|
818 |
|
819 |
-
|
|
|
820 |
"vk_id", "chat_id", "ws_st", "ws_stop", "web_st", "fin_prog",
|
821 |
"b_city", "b_fin", "b_ban", "b_ign", "b_baners", "b_butt", "b_mess",
|
822 |
"shop_st", "curator", "pr1", "pr2", "pr3", "pr4", "pr5", "ad_url",
|
823 |
"key_pr", "n_con", "canal", "data_t"
|
824 |
]
|
825 |
-
for field in required_fields:
|
826 |
-
if field not in transformed_data:
|
827 |
-
transformed_data[field] = ""
|
828 |
-
logging.debug(f"Transformed data after adding required fields: {transformed_data}")
|
829 |
-
|
830 |
-
|
831 |
-
|
832 |
-
|
833 |
-
|
834 |
-
|
835 |
-
|
836 |
-
|
837 |
-
|
838 |
-
|
839 |
-
|
840 |
-
|
841 |
-
|
842 |
-
|
843 |
-
|
844 |
-
|
845 |
-
|
846 |
-
|
847 |
-
|
848 |
-
|
|
|
|
|
|
|
849 |
else:
|
850 |
-
columns = ', '.join(transformed_data.keys())
|
851 |
-
placeholders = ', '.join('?' for _ in transformed_data)
|
852 |
-
insert_query = f"INSERT INTO contacts ({columns}) VALUES ({placeholders})"
|
853 |
-
insert_values = list(transformed_data.values())
|
854 |
-
logging.debug(f"Insert query: {insert_query} with values: {insert_values}")
|
855 |
-
cursor.execute(insert_query, insert_values)
|
856 |
-
|
857 |
-
|
858 |
-
conn.
|
859 |
-
|
|
|
860 |
|
861 |
@app.route('/send_get_request', methods=['GET'])
|
862 |
def send_get_request():
|
@@ -864,37 +882,34 @@ def send_get_request():
|
|
864 |
webinarId = request.args.get('webinarId')
|
865 |
url = f'https://online.bizon365.ru/api/v1/webinars/reports/get?webinarId={webinarId}'
|
866 |
|
867 |
-
# Выполнение GET-запроса к API для получения отчета и сообщений
|
868 |
response = requests.get(url, headers={'X-Token': token})
|
869 |
|
870 |
-
# Проверка, успешно ли выполнен запрос
|
871 |
if response.status_code == 200:
|
872 |
-
data = response.json()
|
873 |
|
874 |
-
# Получение разделов 'report' и 'messages' из данных
|
875 |
report = data.get('report', {})
|
876 |
-
|
877 |
|
878 |
-
|
879 |
try:
|
880 |
-
|
881 |
except json.JSONDecodeError:
|
882 |
-
|
883 |
|
884 |
-
|
885 |
-
|
|
|
|
|
|
|
886 |
|
887 |
-
|
888 |
-
processed_emails = set()
|
889 |
|
890 |
-
#
|
|
|
891 |
for user_id, user_data in users_meta.items():
|
892 |
-
|
893 |
-
messages_user = messages_json.get(user_id, []) # Получение сообщений пользователя
|
894 |
-
user_data['messages'] = messages_user # Добавление сообщений в данные пользователя
|
895 |
-
|
896 |
email = user_data.get('email')
|
897 |
-
if email
|
898 |
update_or_insert_user(DATABASE_NAME, user_data, mapping_template)
|
899 |
processed_emails.add(email)
|
900 |
|
|
|
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 пользователя из данных
|
789 |
+
email = user_data.get('email')
|
790 |
+
if not email:
|
791 |
+
logging.error(f"User data missing email: {user_data}")
|
792 |
+
return
|
793 |
|
794 |
+
logging.debug(f"Processing user with email: {email}")
|
795 |
+
|
796 |
+
# Проверка существования пользователя в базе данных по email
|
797 |
+
cursor.execute("SELECT web_st FROM contacts WHERE email = ?", (email,))
|
798 |
+
user = cursor.fetchone()
|
799 |
+
logging.debug(f"User found: {user}")
|
800 |
|
801 |
+
# Вынесение увеличения значения web_st в отдельный блок
|
802 |
web_st_value = 1 # Инициализация значения web_st
|
803 |
+
if user:
|
804 |
+
# Проверка текущего значения web_st и его инкрементация
|
805 |
+
current_web_st = user[0] if user[0] is not None and user[0] != "" else 0
|
806 |
+
web_st_value = int(current_web_st) + 1
|
807 |
+
logging.debug(f"Calculated web_st_value: {web_st_value}")
|
808 |
+
|
809 |
+
# Обновление значения web_st
|
810 |
+
cursor.execute("UPDATE contacts SET web_st = ? WHERE email = ?", (web_st_value, email))
|
811 |
+
conn.commit()
|
812 |
+
conn.close()
|
813 |
+
logging.debug(f"User {email} web_st updated to {web_st_value}")
|
814 |
else:
|
815 |
+
conn.close()
|
816 |
+
logging.debug(f"User {email} not found, proceeding with insert")
|
817 |
|
818 |
+
# Открываем соединение снова для остальных операций
|
819 |
+
conn = sqlite3.connect(db_name)
|
820 |
+
cursor = conn.cursor()
|
821 |
|
822 |
+
# Преобразование данных пользователя на основе шаблона сопоставления
|
823 |
+
transformed_data = {}
|
824 |
+
for json_key, db_column in mapping_template.items():
|
825 |
+
value = user_data.get(json_key, "")
|
826 |
+
if isinstance(value, list):
|
827 |
+
transformed_data[db_column] = "1" if value else "0"
|
828 |
else:
|
829 |
+
transformed_data[db_column] = str(value)
|
830 |
+
logging.debug(f"Transformed data: {transformed_data}")
|
831 |
|
832 |
+
# Заполнение обязательных полей значениями по умолчанию
|
833 |
+
required_fields = [
|
834 |
"vk_id", "chat_id", "ws_st", "ws_stop", "web_st", "fin_prog",
|
835 |
"b_city", "b_fin", "b_ban", "b_ign", "b_baners", "b_butt", "b_mess",
|
836 |
"shop_st", "curator", "pr1", "pr2", "pr3", "pr4", "pr5", "ad_url",
|
837 |
"key_pr", "n_con", "canal", "data_t"
|
838 |
]
|
839 |
+
for field in required_fields:
|
840 |
+
if field not in transformed_data:
|
841 |
+
transformed_data[field] = ""
|
842 |
+
logging.debug(f"Transformed data after adding required fields: {transformed_data}")
|
843 |
+
|
844 |
+
# Обработка номера телефона, если он есть
|
845 |
+
if 'phone' in user_data:
|
846 |
+
phone = user_data['phone']
|
847 |
+
if phone.startswith('+'):
|
848 |
+
phone = phone[1:]
|
849 |
+
transformed_data['phone'] = phone
|
850 |
+
logging.debug(f"Transformed data after phone processing: {transformed_data}")
|
851 |
+
|
852 |
+
# Добавление значения web_st в данные для вставки
|
853 |
+
transformed_data['web_st'] = web_st_value
|
854 |
+
|
855 |
+
# Обновление данных пользователя в базе данных
|
856 |
+
if user:
|
857 |
+
update_query = "UPDATE contacts SET "
|
858 |
+
update_values = []
|
859 |
+
for column, value in transformed_data.items():
|
860 |
+
update_query += f"{column} = ?, "
|
861 |
+
update_values.append(value)
|
862 |
+
update_query = update_query.rstrip(", ") + " WHERE email = ?"
|
863 |
+
update_values.append(email)
|
864 |
+
logging.debug(f"Update query: {update_query} with values: {update_values}")
|
865 |
+
cursor.execute(update_query, update_values)
|
866 |
else:
|
867 |
+
columns = ', '.join(transformed_data.keys())
|
868 |
+
placeholders = ', '.join('?' for _ in transformed_data)
|
869 |
+
insert_query = f"INSERT INTO contacts ({columns}) VALUES ({placeholders})"
|
870 |
+
insert_values = list(transformed_data.values())
|
871 |
+
logging.debug(f"Insert query: {insert_query} with values: {insert_values}")
|
872 |
+
cursor.execute(insert_query, insert_values)
|
873 |
+
|
874 |
+
# Подтверждение изменений и закрытие соединения
|
875 |
+
conn.commit()
|
876 |
+
conn.close()
|
877 |
+
logging.debug(f"User with email {email} processed successfully")
|
878 |
|
879 |
@app.route('/send_get_request', methods=['GET'])
|
880 |
def send_get_request():
|
|
|
882 |
webinarId = request.args.get('webinarId')
|
883 |
url = f'https://online.bizon365.ru/api/v1/webinars/reports/get?webinarId={webinarId}'
|
884 |
|
|
|
885 |
response = requests.get(url, headers={'X-Token': token})
|
886 |
|
|
|
887 |
if response.status_code == 200:
|
888 |
+
data = response.json()
|
889 |
|
|
|
890 |
report = data.get('report', {})
|
891 |
+
messages = data.get('messages', {})
|
892 |
|
893 |
+
report_json_str = report.get('report', '{}')
|
894 |
try:
|
895 |
+
report_json = json.loads(report_json_str)
|
896 |
except json.JSONDecodeError:
|
897 |
+
report_json = {}
|
898 |
|
899 |
+
messages_json_str = report.get('messages', '{}')
|
900 |
+
try:
|
901 |
+
messages_json = json.loads(messages_json_str)
|
902 |
+
except json.JSONDecodeError:
|
903 |
+
messages_json = {}
|
904 |
|
905 |
+
users_meta = report_json.get('usersMeta', {})
|
|
|
906 |
|
907 |
+
# Обновление или добавление каждого пользователя в базу данных data_gc.db
|
908 |
+
processed_emails = set()
|
909 |
for user_id, user_data in users_meta.items():
|
910 |
+
user_data['messages'] = messages_json
|
|
|
|
|
|
|
911 |
email = user_data.get('email')
|
912 |
+
if email not in processed_emails:
|
913 |
update_or_insert_user(DATABASE_NAME, user_data, mapping_template)
|
914 |
processed_emails.add(email)
|
915 |
|