DmitrMakeev
commited on
Commit
•
3797008
1
Parent(s):
b00524d
Update app.py
Browse files
app.py
CHANGED
@@ -1680,21 +1680,6 @@ def add_data_ver_cur():
|
|
1680 |
|
1681 |
DATABASE2 = 'data_gc.db'
|
1682 |
|
1683 |
-
# Функция для верификации номера телефона через внешний API
|
1684 |
-
def verify_phone_number2(phone_number):
|
1685 |
-
if verifikation_start == "1":
|
1686 |
-
full_url_ver = f"{wa_url}{wa_ak}{ws_url_ver}{wa_api_key}"
|
1687 |
-
payload = json.dumps({"phoneNumber": phone_number})
|
1688 |
-
headers = {'Content-Type': 'application/json'}
|
1689 |
-
response = requests.post(full_url_ver, headers=headers, data=payload)
|
1690 |
-
if response.status_code == 200:
|
1691 |
-
response_body = response.json()
|
1692 |
-
return response_body.get('existsWhatsapp', 'false')
|
1693 |
-
else:
|
1694 |
-
return "Error"
|
1695 |
-
else:
|
1696 |
-
return "false"
|
1697 |
-
|
1698 |
def parse_csv_data(data):
|
1699 |
parsed_data = []
|
1700 |
for item in data:
|
@@ -1704,53 +1689,69 @@ def parse_csv_data(data):
|
|
1704 |
parsed_data.append(dict(zip(headers, row)))
|
1705 |
return parsed_data
|
1706 |
|
1707 |
-
def
|
1708 |
-
|
1709 |
-
conn = sqlite3.connect(DATABASE2)
|
1710 |
cursor = conn.cursor()
|
1711 |
|
1712 |
-
mapping_template_cur = mapp_templates.get(template_key, mt_avp)
|
1713 |
-
|
1714 |
for row in data:
|
|
|
1715 |
utc_now = datetime.utcnow()
|
1716 |
msk_tz = pytz.timezone('Europe/Moscow')
|
1717 |
msk_now = utc_now.replace(tzinfo=pytz.utc).astimezone(msk_tz)
|
1718 |
data_t = msk_now.strftime('%Y-%m-%d %H:%M:%S')
|
1719 |
|
1720 |
-
|
1721 |
-
|
1722 |
-
|
1723 |
-
|
1724 |
-
|
1725 |
-
|
1726 |
-
|
1727 |
-
|
1728 |
-
|
1729 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1730 |
cursor.execute("SELECT 1 FROM contacts WHERE email = ? OR phone = ?", (email, phone))
|
1731 |
user_exists = cursor.fetchone()
|
1732 |
|
|
|
1733 |
if user_exists:
|
1734 |
-
|
1735 |
continue
|
1736 |
|
1737 |
-
|
1738 |
-
|
1739 |
-
|
1740 |
-
|
1741 |
-
if verifikation_start == "1":
|
1742 |
-
user_data['ws_st'] = verify_phone_number2(phone)
|
1743 |
|
1744 |
-
|
1745 |
-
|
1746 |
-
fields = [
|
1747 |
-
'name', 'phone', 'email', 'vk_id', 'chat_id', 'ws_st', 'ws_stop', 'web_st', 'fin_prog',
|
1748 |
-
'b_city', 'b_fin', 'b_ban', 'b_ign', 'b_baners', 'b_butt', 'b_mess', 'shop_st', 'curator',
|
1749 |
-
'pr1', 'pr2', 'pr3', 'pr4', 'pr5', 'ad_url', 'key_pr', 'n_con', 'canal', 'data_t', 'utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content'
|
1750 |
-
]
|
1751 |
-
|
1752 |
-
placeholders = ', '.join(['?' for _ in fields])
|
1753 |
-
columns_str = ', '.join(fields)
|
1754 |
|
1755 |
query = f'''
|
1756 |
INSERT INTO contacts ({columns_str})
|
@@ -1758,27 +1759,15 @@ def insert_data2(data, template_key):
|
|
1758 |
'''
|
1759 |
|
1760 |
try:
|
1761 |
-
cursor.execute(query,
|
1762 |
-
logging.debug(f"Row inserted successfully: {user_data}")
|
1763 |
except Exception as e:
|
1764 |
-
|
1765 |
-
|
1766 |
conn.rollback()
|
1767 |
raise
|
1768 |
|
1769 |
-
|
1770 |
-
|
1771 |
-
logging.debug("Transaction committed successfully.")
|
1772 |
-
except Exception as e:
|
1773 |
-
logging.error(f"Error committing transaction: {str(e)}")
|
1774 |
-
conn.rollback()
|
1775 |
-
finally:
|
1776 |
-
conn.close()
|
1777 |
-
|
1778 |
-
def verify_api_key():
|
1779 |
-
api_key = request.args.get('api_sys')
|
1780 |
-
if api_key != "fasSd345D":
|
1781 |
-
return jsonify({"error": "Invalid API key"}), 403
|
1782 |
|
1783 |
@app.route('/upload_csv', methods=['POST'])
|
1784 |
def upload_csv():
|
@@ -1792,7 +1781,8 @@ def upload_csv():
|
|
1792 |
csv_input = csv.DictReader(stream)
|
1793 |
data = [row for row in csv_input]
|
1794 |
parsed_data = parse_csv_data(data)
|
1795 |
-
|
|
|
1796 |
return jsonify({"message": "Data uploaded and inserted successfully"})
|
1797 |
return jsonify({"error": "Invalid file format"}), 400
|
1798 |
|
|
|
1680 |
|
1681 |
DATABASE2 = 'data_gc.db'
|
1682 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1683 |
def parse_csv_data(data):
|
1684 |
parsed_data = []
|
1685 |
for item in data:
|
|
|
1689 |
parsed_data.append(dict(zip(headers, row)))
|
1690 |
return parsed_data
|
1691 |
|
1692 |
+
def insert_data(data, db_name):
|
1693 |
+
conn = sqlite3.connect(db_name)
|
|
|
1694 |
cursor = conn.cursor()
|
1695 |
|
|
|
|
|
1696 |
for row in data:
|
1697 |
+
# Получение текущего времени в московском часовом поясе
|
1698 |
utc_now = datetime.utcnow()
|
1699 |
msk_tz = pytz.timezone('Europe/Moscow')
|
1700 |
msk_now = utc_now.replace(tzinfo=pytz.utc).astimezone(msk_tz)
|
1701 |
data_t = msk_now.strftime('%Y-%m-%d %H:%M:%S')
|
1702 |
|
1703 |
+
# Проверка наличия ключей перед их использованием и предоставление значений по умолчанию
|
1704 |
+
name = row.get('Name', '')
|
1705 |
+
|
1706 |
+
# Удаление ведущего плюсика из номера телефона, если он есть
|
1707 |
+
phone = row.get('Phone', '').lstrip('+')
|
1708 |
+
|
1709 |
+
email = row.get('Email', '')
|
1710 |
+
vk_id = row.get('vk_id', '')
|
1711 |
+
chat_id = row.get('chat_id', '')
|
1712 |
+
ws_st = row.get('ws_st', '')
|
1713 |
+
ws_stop = row.get('ws_stop', '')
|
1714 |
+
web_st = row.get('web_st', 0)
|
1715 |
+
fin_prog = row.get('fin_prog', 0)
|
1716 |
+
b_city = row.get('b_city', '')
|
1717 |
+
b_fin = row.get('b_fin', '')
|
1718 |
+
b_ban = row.get('b_ban', '')
|
1719 |
+
b_ign = row.get('b_ign', '')
|
1720 |
+
b_baners = row.get('b_baners', '')
|
1721 |
+
b_butt = row.get('b_butt', '')
|
1722 |
+
b_mess = row.get('b_mess', '')
|
1723 |
+
shop_st = row.get('shop_st', '')
|
1724 |
+
curator = row.get('curator', '')
|
1725 |
+
pr1 = row.get('pr1', '')
|
1726 |
+
pr2 = row.get('pr2', '')
|
1727 |
+
pr3 = row.get('pr3', '')
|
1728 |
+
pr4 = row.get('pr4', '')
|
1729 |
+
pr5 = row.get('pr5', '')
|
1730 |
+
ad_url = row.get('ad_url', '')
|
1731 |
+
key_pr = row.get('key_pr', '')
|
1732 |
+
n_con = row.get('n_con', '')
|
1733 |
+
canal = row.get('canal', '')
|
1734 |
+
utm_source = row.get('utm_source', '')
|
1735 |
+
utm_medium = row.get('utm_medium', '')
|
1736 |
+
utm_campaign = row.get('utm_campaign', '')
|
1737 |
+
utm_term = row.get('utm_term', '')
|
1738 |
+
utm_content = row.get('utm_content', '')
|
1739 |
+
|
1740 |
+
# Проверка существования пользователя в базе данных по email или телефону
|
1741 |
cursor.execute("SELECT 1 FROM contacts WHERE email = ? OR phone = ?", (email, phone))
|
1742 |
user_exists = cursor.fetchone()
|
1743 |
|
1744 |
+
# Если пользователь существует, пропускаем вставку
|
1745 |
if user_exists:
|
1746 |
+
print(f"User with email {email} or phone {phone} already exists. Skipping insert.")
|
1747 |
continue
|
1748 |
|
1749 |
+
# Создание динамического SQL-запроса для вставки данных
|
1750 |
+
columns = ['name', 'phone', 'email', 'vk_id', 'chat_id', 'ws_st', 'ws_stop', 'web_st', 'fin_prog', 'b_city', 'b_fin', 'b_ban', 'b_ign', 'b_baners', 'b_butt', 'b_mess', 'shop_st', 'curator', 'pr1', 'pr2', 'pr3', 'pr4', 'pr5', 'ad_url', 'key_pr', 'n_con', 'canal', 'data_t', 'utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content']
|
1751 |
+
values = [name, phone, email, vk_id, chat_id, ws_st, ws_stop, web_st, fin_prog, b_city, b_fin, b_ban, b_ign, b_baners, b_butt, b_mess, shop_st, curator, pr1, pr2, pr3, pr4, pr5, ad_url, key_pr, n_con, canal, data_t, utm_source, utm_medium, utm_campaign, utm_term, utm_content]
|
|
|
|
|
|
|
1752 |
|
1753 |
+
placeholders = ', '.join(['?' for _ in columns])
|
1754 |
+
columns_str = ', '.join(columns)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1755 |
|
1756 |
query = f'''
|
1757 |
INSERT INTO contacts ({columns_str})
|
|
|
1759 |
'''
|
1760 |
|
1761 |
try:
|
1762 |
+
cursor.execute(query, values)
|
|
|
1763 |
except Exception as e:
|
1764 |
+
print(f"Error inserting row: {row}")
|
1765 |
+
print(f"Error message: {str(e)}")
|
1766 |
conn.rollback()
|
1767 |
raise
|
1768 |
|
1769 |
+
conn.commit()
|
1770 |
+
conn.close()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1771 |
|
1772 |
@app.route('/upload_csv', methods=['POST'])
|
1773 |
def upload_csv():
|
|
|
1781 |
csv_input = csv.DictReader(stream)
|
1782 |
data = [row for row in csv_input]
|
1783 |
parsed_data = parse_csv_data(data)
|
1784 |
+
for db_name in DATABASES:
|
1785 |
+
insert_data(parsed_data, db_name)
|
1786 |
return jsonify({"message": "Data uploaded and inserted successfully"})
|
1787 |
return jsonify({"error": "Invalid file format"}), 400
|
1788 |
|