Update app.py
Browse files
app.py
CHANGED
|
@@ -782,19 +782,20 @@ def send_request():
|
|
| 782 |
|
| 783 |
DATABASE_NAME = 'data_gc.db'
|
| 784 |
|
| 785 |
-
|
| 786 |
-
|
| 787 |
def update_or_insert_user(db_name, user_data, mapping_template):
|
| 788 |
conn = sqlite3.connect(db_name)
|
| 789 |
cursor = conn.cursor()
|
| 790 |
|
|
|
|
| 791 |
email = user_data.get('email')
|
| 792 |
logging.debug(f"Processing user with email: {email}")
|
| 793 |
|
|
|
|
| 794 |
cursor.execute("SELECT web_st FROM contacts WHERE email = ?", (email,))
|
| 795 |
user = cursor.fetchone()
|
| 796 |
logging.debug(f"User found: {user}")
|
| 797 |
|
|
|
|
| 798 |
transformed_data = {}
|
| 799 |
for json_key, db_column in mapping_template.items():
|
| 800 |
value = user_data.get(json_key, "")
|
|
@@ -804,18 +805,19 @@ def update_or_insert_user(db_name, user_data, mapping_template):
|
|
| 804 |
transformed_data[db_column] = str(value)
|
| 805 |
logging.debug(f"Transformed data: {transformed_data}")
|
| 806 |
|
|
|
|
| 807 |
required_fields = [
|
| 808 |
"vk_id", "chat_id", "ws_st", "ws_stop", "web_st", "fin_prog",
|
| 809 |
"b_city", "b_fin", "b_ban", "b_ign", "b_baners", "b_butt", "b_mess",
|
| 810 |
"shop_st", "curator", "pr1", "pr2", "pr3", "pr4", "pr5", "ad_url",
|
| 811 |
"key_pr", "n_con", "canal", "data_t"
|
| 812 |
]
|
| 813 |
-
|
| 814 |
for field in required_fields:
|
| 815 |
if field not in transformed_data:
|
| 816 |
transformed_data[field] = ""
|
| 817 |
logging.debug(f"Transformed data after adding required fields: {transformed_data}")
|
| 818 |
|
|
|
|
| 819 |
if 'phone' in user_data:
|
| 820 |
phone = user_data['phone']
|
| 821 |
if phone.startswith('+'):
|
|
@@ -823,12 +825,15 @@ def update_or_insert_user(db_name, user_data, mapping_template):
|
|
| 823 |
transformed_data['phone'] = phone
|
| 824 |
logging.debug(f"Transformed data after phone processing: {transformed_data}")
|
| 825 |
|
|
|
|
| 826 |
web_st_value = 0
|
| 827 |
if user:
|
| 828 |
-
|
|
|
|
| 829 |
web_st_value += 1
|
| 830 |
logging.debug(f"Calculated web_st_value: {web_st_value}")
|
| 831 |
|
|
|
|
| 832 |
update_query = "UPDATE contacts SET "
|
| 833 |
update_values = []
|
| 834 |
for column, value in transformed_data.items():
|
|
@@ -839,6 +844,7 @@ def update_or_insert_user(db_name, user_data, mapping_template):
|
|
| 839 |
logging.debug(f"Update query: {update_query} with values: {update_values}")
|
| 840 |
cursor.execute(update_query, update_values)
|
| 841 |
|
|
|
|
| 842 |
if cursor.rowcount == 0:
|
| 843 |
columns = ', '.join(transformed_data.keys()) + ", web_st"
|
| 844 |
placeholders = ', '.join('?' for _ in transformed_data) + ", ?"
|
|
@@ -847,10 +853,48 @@ def update_or_insert_user(db_name, user_data, mapping_template):
|
|
| 847 |
logging.debug(f"Insert query: {insert_query} with values: {insert_values}")
|
| 848 |
cursor.execute(insert_query, insert_values)
|
| 849 |
|
|
|
|
| 850 |
conn.commit()
|
| 851 |
conn.close()
|
| 852 |
logging.debug(f"User with email {email} processed successfully")
|
| 853 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 854 |
|
| 855 |
|
| 856 |
|
|
|
|
| 782 |
|
| 783 |
DATABASE_NAME = 'data_gc.db'
|
| 784 |
|
|
|
|
|
|
|
| 785 |
def update_or_insert_user(db_name, user_data, mapping_template):
|
| 786 |
conn = sqlite3.connect(db_name)
|
| 787 |
cursor = conn.cursor()
|
| 788 |
|
| 789 |
+
# Получение email пользователя из данных
|
| 790 |
email = user_data.get('email')
|
| 791 |
logging.debug(f"Processing user with email: {email}")
|
| 792 |
|
| 793 |
+
# Проверка существования пользователя в базе данных по email
|
| 794 |
cursor.execute("SELECT web_st FROM contacts WHERE email = ?", (email,))
|
| 795 |
user = cursor.fetchone()
|
| 796 |
logging.debug(f"User found: {user}")
|
| 797 |
|
| 798 |
+
# Преобразование данных пользователя на основе шаблона сопоставления
|
| 799 |
transformed_data = {}
|
| 800 |
for json_key, db_column in mapping_template.items():
|
| 801 |
value = user_data.get(json_key, "")
|
|
|
|
| 805 |
transformed_data[db_column] = str(value)
|
| 806 |
logging.debug(f"Transformed data: {transformed_data}")
|
| 807 |
|
| 808 |
+
# Заполнение обязательных полей значениями по умолчанию
|
| 809 |
required_fields = [
|
| 810 |
"vk_id", "chat_id", "ws_st", "ws_stop", "web_st", "fin_prog",
|
| 811 |
"b_city", "b_fin", "b_ban", "b_ign", "b_baners", "b_butt", "b_mess",
|
| 812 |
"shop_st", "curator", "pr1", "pr2", "pr3", "pr4", "pr5", "ad_url",
|
| 813 |
"key_pr", "n_con", "canal", "data_t"
|
| 814 |
]
|
|
|
|
| 815 |
for field in required_fields:
|
| 816 |
if field not in transformed_data:
|
| 817 |
transformed_data[field] = ""
|
| 818 |
logging.debug(f"Transformed data after adding required fields: {transformed_data}")
|
| 819 |
|
| 820 |
+
# Обработка номера телефона, если он есть
|
| 821 |
if 'phone' in user_data:
|
| 822 |
phone = user_data['phone']
|
| 823 |
if phone.startswith('+'):
|
|
|
|
| 825 |
transformed_data['phone'] = phone
|
| 826 |
logging.debug(f"Transformed data after phone processing: {transformed_data}")
|
| 827 |
|
| 828 |
+
# Вынесение увеличения значения web_st в отдельный блок
|
| 829 |
web_st_value = 0
|
| 830 |
if user:
|
| 831 |
+
# Проверка текущего значения web_st и его инкрементация
|
| 832 |
+
web_st_value = 1 if user[0] is None or user[0] == "" or user[0] == 0 else int(user[0])
|
| 833 |
web_st_value += 1
|
| 834 |
logging.debug(f"Calculated web_st_value: {web_st_value}")
|
| 835 |
|
| 836 |
+
# Обновление данных пользователя в базе данных
|
| 837 |
update_query = "UPDATE contacts SET "
|
| 838 |
update_values = []
|
| 839 |
for column, value in transformed_data.items():
|
|
|
|
| 844 |
logging.debug(f"Update query: {update_query} with values: {update_values}")
|
| 845 |
cursor.execute(update_query, update_values)
|
| 846 |
|
| 847 |
+
# Если пользователь не найден, вставка нового пользователя
|
| 848 |
if cursor.rowcount == 0:
|
| 849 |
columns = ', '.join(transformed_data.keys()) + ", web_st"
|
| 850 |
placeholders = ', '.join('?' for _ in transformed_data) + ", ?"
|
|
|
|
| 853 |
logging.debug(f"Insert query: {insert_query} with values: {insert_values}")
|
| 854 |
cursor.execute(insert_query, insert_values)
|
| 855 |
|
| 856 |
+
# Подтверждение изменений и закрытие соединения
|
| 857 |
conn.commit()
|
| 858 |
conn.close()
|
| 859 |
logging.debug(f"User with email {email} processed successfully")
|
| 860 |
|
| 861 |
+
@app.route('/send_get_request', methods=['GET'])
|
| 862 |
+
def send_get_request():
|
| 863 |
+
token = request.args.get('token')
|
| 864 |
+
webinarId = request.args.get('webinarId')
|
| 865 |
+
url = f'https://online.bizon365.ru/api/v1/webinars/reports/get?webinarId={webinarId}'
|
| 866 |
+
|
| 867 |
+
response = requests.get(url, headers={'X-Token': token})
|
| 868 |
+
|
| 869 |
+
if response.status_code == 200:
|
| 870 |
+
data = response.json()
|
| 871 |
+
|
| 872 |
+
report = data.get('report', {})
|
| 873 |
+
messages = data.get('messages', {})
|
| 874 |
+
|
| 875 |
+
report_json_str = report.get('report', '{}')
|
| 876 |
+
try:
|
| 877 |
+
report_json = json.loads(report_json_str)
|
| 878 |
+
except json.JSONDecodeError:
|
| 879 |
+
report_json = {}
|
| 880 |
+
|
| 881 |
+
messages_json_str = report.get('messages', '{}')
|
| 882 |
+
try:
|
| 883 |
+
messages_json = json.loads(messages_json_str)
|
| 884 |
+
except json.JSONDecodeError:
|
| 885 |
+
messages_json = {}
|
| 886 |
+
|
| 887 |
+
users_meta = report_json.get('usersMeta', {})
|
| 888 |
+
|
| 889 |
+
# Обновление или добавление каждого пользователя в базу данных data_gc.db
|
| 890 |
+
for user_id, user_data in users_meta.items():
|
| 891 |
+
user_data['messages'] = messages_json
|
| 892 |
+
update_or_insert_user(DATABASE_NAME, user_data, mapping_template)
|
| 893 |
+
|
| 894 |
+
return jsonify({'status': 'User data saved successfully'})
|
| 895 |
+
else:
|
| 896 |
+
return jsonify({'error': 'Failed to fetch data from the API'}), response.status_code
|
| 897 |
+
|
| 898 |
|
| 899 |
|
| 900 |
|