DmitrMakeev
commited on
Commit
•
ee4861c
1
Parent(s):
00e9060
Update app.py
Browse files
app.py
CHANGED
@@ -100,6 +100,19 @@ for db in DATABASES:
|
|
100 |
|
101 |
|
102 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
103 |
|
104 |
|
105 |
|
@@ -759,18 +772,59 @@ def send_request():
|
|
759 |
|
760 |
|
761 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
762 |
@app.route('/send_get_request', methods=['GET'])
|
763 |
def send_get_request():
|
764 |
token = request.args.get('token')
|
765 |
webinarId = request.args.get('webinarId')
|
766 |
url = f'https://online.bizon365.ru/api/v1/webinars/reports/get?webinarId={webinarId}'
|
|
|
767 |
response = requests.get(url, headers={'X-Token': token})
|
|
|
768 |
if response.status_code == 200:
|
769 |
data = response.json()
|
770 |
-
|
771 |
-
report_json_str = report.get('report', '{}')
|
772 |
-
messages_json_str =
|
773 |
-
|
774 |
try:
|
775 |
report_json = json.loads(report_json_str)
|
776 |
except json.JSONDecodeError:
|
@@ -781,72 +835,14 @@ def send_get_request():
|
|
781 |
except json.JSONDecodeError:
|
782 |
messages_json = {}
|
783 |
|
784 |
-
|
785 |
-
|
786 |
-
'messages': messages_json
|
787 |
-
}
|
788 |
-
|
789 |
-
# Маппинг полей
|
790 |
-
template = {
|
791 |
-
"username": "name",
|
792 |
-
"phone": "phone",
|
793 |
-
"email": "email",
|
794 |
-
"city": "b_city",
|
795 |
-
"finished": "b_fin",
|
796 |
-
"ban": "b_ban",
|
797 |
-
"ignore": "b_ign",
|
798 |
-
"banners": "b_baners", # Если массив заполнен пишем -1, если пустой пишем - 0
|
799 |
-
"buttons": "b_butt", # Если массив заполнен пишем -1, если пустой пишем - 0
|
800 |
-
"messages": "b_mess",
|
801 |
-
"0": "web_st", # С первого раза и с каждым обновлением пользователя, увеличиваем на 1
|
802 |
-
}
|
803 |
-
|
804 |
-
# Получение usersMeta и email
|
805 |
-
users_meta = report_json.get('usersMeta', {})
|
806 |
-
for user_id, user_data in users_meta.items():
|
807 |
-
email = user_data.get('email', '')
|
808 |
-
|
809 |
-
if not email:
|
810 |
-
continue
|
811 |
-
|
812 |
-
# Проверка наличия пользователя по email
|
813 |
-
conn = sqlite3.connect('data_gc.db')
|
814 |
-
cursor = conn.cursor()
|
815 |
-
cursor.execute("SELECT * FROM contacts WHERE email = ?", (email,))
|
816 |
-
existing_user = cursor.fetchone()
|
817 |
-
|
818 |
-
# Подготовка данных для вставки/обновления
|
819 |
-
mapped_data = {}
|
820 |
-
for key, value in template.items():
|
821 |
-
if key in user_data:
|
822 |
-
if key in ["banners", "buttons"]:
|
823 |
-
mapped_data[value] = -1 if user_data[key] else 0
|
824 |
-
elif key == "0":
|
825 |
-
if existing_user:
|
826 |
-
mapped_data[value] = existing_user[8] + 1 # Увеличиваем на 1 значение поля web_st
|
827 |
-
else:
|
828 |
-
mapped_data[value] = 1 # Изначальное значение
|
829 |
-
else:
|
830 |
-
mapped_data[value] = user_data[key]
|
831 |
-
elif key == "messages":
|
832 |
-
mapped_data[value] = json.dumps(messages_json.get(user_id, []))
|
833 |
-
|
834 |
-
# Вставка или обновление пользователя
|
835 |
-
if existing_user:
|
836 |
-
placeholders = ", ".join([f"{field} = ?" for field in mapped_data.keys()])
|
837 |
-
values = list(mapped_data.values())
|
838 |
-
values.append(email)
|
839 |
-
cursor.execute(f"UPDATE contacts SET {placeholders} WHERE email = ?", values)
|
840 |
-
else:
|
841 |
-
fields = ", ".join(mapped_data.keys())
|
842 |
-
placeholders = ", ".join(["?" for _ in mapped_data.values()])
|
843 |
-
values = list(mapped_data.values())
|
844 |
-
cursor.execute(f"INSERT INTO contacts ({fields}) VALUES ({placeholders})", values)
|
845 |
|
846 |
-
|
847 |
-
|
|
|
848 |
|
849 |
-
return jsonify(
|
850 |
else:
|
851 |
return jsonify({'error': 'Failed to fetch data from the API'}), response.status_code
|
852 |
|
|
|
100 |
|
101 |
|
102 |
|
103 |
+
mplate = {
|
104 |
+
"username": "name",
|
105 |
+
"phone": "phone",
|
106 |
+
"email": "email",
|
107 |
+
"city": "b_city",
|
108 |
+
"finished": "b_fin",
|
109 |
+
"ban": "b_ban",
|
110 |
+
"ignore": "b_ign",
|
111 |
+
"banners": "b_baners", # Если массив заполнен пишем -1, если пустой пишем - 0
|
112 |
+
"buttons": "b_butt", # Если массив заполнен пишем -1, если пустой пишем - 0
|
113 |
+
"messages": "b_mess",
|
114 |
+
"0": "web_st" # С первого раза и с каждым обновлением пользователя, увеличиваем на 1
|
115 |
+
}
|
116 |
|
117 |
|
118 |
|
|
|
772 |
|
773 |
|
774 |
|
775 |
+
def update_or_insert_user(db_name, user_data, mapping_template):
|
776 |
+
conn = sqlite3.connect(db_name)
|
777 |
+
cursor = conn.cursor()
|
778 |
+
|
779 |
+
email = user_data.get('email')
|
780 |
+
|
781 |
+
# Проверка существования пользователя
|
782 |
+
cursor.execute("SELECT * FROM contacts WHERE email = ?", (email,))
|
783 |
+
user = cursor.fetchone()
|
784 |
+
|
785 |
+
# Преобразование данных пользователя на основе шаблона
|
786 |
+
transformed_data = {}
|
787 |
+
for json_key, db_column in mapping_template.items():
|
788 |
+
value = user_data.get(json_key, "")
|
789 |
+
if isinstance(value, list):
|
790 |
+
transformed_data[db_column] = "-1" if value else "0"
|
791 |
+
else:
|
792 |
+
transformed_data[db_column] = value
|
793 |
+
|
794 |
+
if user:
|
795 |
+
# Обновление существующего пользователя
|
796 |
+
update_query = "UPDATE contacts SET "
|
797 |
+
update_values = []
|
798 |
+
for column, value in transformed_data.items():
|
799 |
+
update_query += f"{column} = ?, "
|
800 |
+
update_values.append(value)
|
801 |
+
update_query = update_query.rstrip(", ") + " WHERE email = ?"
|
802 |
+
update_values.append(email)
|
803 |
+
cursor.execute(update_query, update_values)
|
804 |
+
else:
|
805 |
+
# Добавление нового пользователя
|
806 |
+
columns = ', '.join(transformed_data.keys())
|
807 |
+
placeholders = ', '.join('?' for _ in transformed_data)
|
808 |
+
insert_query = f"INSERT INTO contacts ({columns}) VALUES ({placeholders})"
|
809 |
+
cursor.execute(insert_query, list(transformed_data.values()))
|
810 |
+
|
811 |
+
conn.commit()
|
812 |
+
conn.close()
|
813 |
+
|
814 |
@app.route('/send_get_request', methods=['GET'])
|
815 |
def send_get_request():
|
816 |
token = request.args.get('token')
|
817 |
webinarId = request.args.get('webinarId')
|
818 |
url = f'https://online.bizon365.ru/api/v1/webinars/reports/get?webinarId={webinarId}'
|
819 |
+
|
820 |
response = requests.get(url, headers={'X-Token': token})
|
821 |
+
|
822 |
if response.status_code == 200:
|
823 |
data = response.json()
|
824 |
+
|
825 |
+
report_json_str = data.get('report', {}).get('report', '{}')
|
826 |
+
messages_json_str = data.get('messages', '{}')
|
827 |
+
|
828 |
try:
|
829 |
report_json = json.loads(report_json_str)
|
830 |
except json.JSONDecodeError:
|
|
|
835 |
except json.JSONDecodeError:
|
836 |
messages_json = {}
|
837 |
|
838 |
+
user_data = report_json.get('usersMeta', {}).get('HXJY5fEdC', {})
|
839 |
+
user_data['messages'] = messages_json
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
840 |
|
841 |
+
# Обновление или добавление пользователя во все базы данных
|
842 |
+
for db in DATABASES:
|
843 |
+
update_or_insert_user(db, user_data, template)
|
844 |
|
845 |
+
return jsonify({'status': 'User data saved successfully'})
|
846 |
else:
|
847 |
return jsonify({'error': 'Failed to fetch data from the API'}), response.status_code
|
848 |
|