DmitrMakeev commited on
Commit
370dfa6
1 Parent(s): fdd446f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +24 -67
app.py CHANGED
@@ -1773,47 +1773,26 @@ def se_upl_csv():
1773
 
1774
 
1775
 
1776
- DATABASE4 = 'data_gc.db'
1777
-
1778
- def verify_phone_number_b(phone_number):
1779
- full_url_ver = f"{wa_url}{wa_ak}{ws_url_ver}{wa_api_key}"
1780
- payload = {"phoneNumber": phone_number}
1781
- headers = {'Content-Type': 'application/json'}
1782
- response = requests.post(full_url_ver, headers=headers, json=payload)
1783
- if response.status_code == 200:
1784
- response_body = response.json()
1785
- return response_body.get('existsWhatsapp', 'false')
1786
- else:
1787
- return "Error"
1788
-
1789
 
 
1790
 
1791
- def parse_csv_data_b(data):
1792
- parsed_data = []
1793
- for row in data:
1794
- parsed_row = {}
1795
- for key, value in row.items():
1796
- headers = next(csv.reader([key]))
1797
- values = next(csv.reader([value]))
1798
- parsed_row.update(dict(zip(headers, values)))
1799
- parsed_data.append(parsed_row)
1800
- return parsed_data
1801
-
1802
- def clean_phone_number_b(phone_number):
1803
  return re.sub(r'\D', '', phone_number)
1804
 
1805
- def insert_data_b(data, verify_phone, add_curator):
1806
- global current_curator_index
1807
- conn = sqlite3.connect(DATABASE4)
1808
  cursor = conn.cursor()
1809
 
1810
  for row in data:
1811
- name = row.get('Имя', '')
1812
- phone = row.get('WhatsApp', '').lstrip('+')
1813
- email = row.get('Email', '')
1814
- data_t = row.get('Дата', '').strip('"')
1815
 
1816
- phone = clean_phone_number_b(phone)
 
1817
 
1818
  cursor.execute("SELECT 1 FROM contacts WHERE email = ? OR phone = ?", (email, phone))
1819
  user_exists = cursor.fetchone()
@@ -1822,19 +1801,8 @@ def insert_data_b(data, verify_phone, add_curator):
1822
  print(f"User with email {email} or phone {phone} already exists. Skipping insert.")
1823
  continue
1824
 
1825
- if add_curator == "1":
1826
- curator = curators[current_curator_index]
1827
- current_curator_index = (current_curator_index + 1) % len(curators)
1828
- else:
1829
- curator = row.get('Куратор', '')
1830
-
1831
- if verify_phone == "1":
1832
- ws_st = verify_phone_number_b(phone)
1833
- else:
1834
- ws_st = row.get('ws_st', '')
1835
-
1836
  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', 'gc_url', 'key_pr', 'n_con', 'canal', 'data_t', 'utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content']
1837
- values = [name, phone, email, row.get('ВКонтакте', ''), row.get('Телеграм', ''), ws_st, row.get('ws_stop', ''), row.get('web_st', 0), row.get('fin_prog', 0), row.get('Город', ''), row.get('b_fin', ''), row.get('b_ban', ''), row.get('b_ign', ''), row.get('b_baners', ''), row.get('b_butt', ''), row.get('Реплики', ''), row.get('Статус покупки', ''), curator, row.get('pr1', ''), row.get('pr2', ''), row.get('pr3', ''), row.get('Канал трафика', ''), row.get('pr5', ''), row.get('GetCurse', ''), row.get('Ключ PR', ''), row.get('n_con', ''), row.get('Канал', ''), data_t, row.get('utm_source', ''), row.get('utm_medium', ''), row.get('utm_campaign', ''), row.get('utm_term', ''), row.get('utm_content', '')]
1838
 
1839
  placeholders = ', '.join(['?' for _ in columns])
1840
  columns_str = ', '.join(columns)
@@ -1846,44 +1814,33 @@ def insert_data_b(data, verify_phone, add_curator):
1846
 
1847
  try:
1848
  cursor.execute(query, values)
1849
- user_data = dict(zip(columns, values))
1850
- send_to_google_forms(user_data, gog_url)
1851
  except Exception as e:
1852
  print(f"Error inserting row: {row}")
1853
  print(f"Error message: {str(e)}")
1854
  conn.rollback()
1855
- raise
1856
 
1857
  conn.commit()
1858
  conn.close()
1859
 
1860
- @app.route('/upload_csv_b', methods=['POST'])
1861
- def upload_csv_b():
 
1862
  if 'file' not in request.files:
1863
  return jsonify({"error": "No file part"}), 400
1864
  file = request.files['file']
1865
  if file.filename == '':
1866
  return jsonify({"error": "No selected file"}), 400
1867
- if file and file.filename.endswith('.csv'):
1868
- stream = io.StringIO(file.stream.read().decode("UTF8"), newline=None)
1869
- csv_input = csv.DictReader(stream)
1870
- data = [row for row in csv_input]
1871
- parsed_data = parse_csv_data_b(data)
1872
- verify_phone = request.form.get('verify_phone', '0')
1873
- add_curator = request.form.get('add_curator', '0')
1874
- print(f"Verify Phone: {verify_phone}")
1875
- print(f"Add Curator: {add_curator}")
1876
- insert_data_b(parsed_data, verify_phone, add_curator)
1877
  return jsonify({"message": "Data uploaded and inserted successfully"})
1878
  return jsonify({"error": "Invalid file format"}), 400
1879
 
1880
- @app.route('/upl_csv_b', methods=['GET'])
1881
- def se_upl_csv_b():
1882
- api_sys_control = request.args.get('api_sys')
1883
- if api_sys_control != api_key_sys:
1884
- return "EUR 22", 200
1885
- return render_template('upl_csv_b.html')
1886
-
1887
 
1888
 
1889
 
 
1773
 
1774
 
1775
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1776
 
1777
+ DATABASE = 'data_gc.db'
1778
 
1779
+ # Функция для очистки номера телефона
1780
+ def clean_phone_number_j(phone_number):
 
 
 
 
 
 
 
 
 
 
1781
  return re.sub(r'\D', '', phone_number)
1782
 
1783
+ # Функция для вставки данных в базу данных
1784
+ def insert_data(data):
1785
+ conn = sqlite3.connect(DATABASE) # Подключаемся к базе данных
1786
  cursor = conn.cursor()
1787
 
1788
  for row in data:
1789
+ name = row.get('name', '')
1790
+ phone = row.get('phone', '').lstrip('+')
1791
+ email = row.get('email', '')
1792
+ data_t = row.get('data_t', '').strip('"')
1793
 
1794
+ # Очистка номера телефона
1795
+ phone = clean_phone_number_j(phone)
1796
 
1797
  cursor.execute("SELECT 1 FROM contacts WHERE email = ? OR phone = ?", (email, phone))
1798
  user_exists = cursor.fetchone()
 
1801
  print(f"User with email {email} or phone {phone} already exists. Skipping insert.")
1802
  continue
1803
 
 
 
 
 
 
 
 
 
 
 
 
1804
  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', 'gc_url', 'key_pr', 'n_con', 'canal', 'data_t', 'utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content']
1805
+ values = [name, phone, email, row.get('vk_id', ''), row.get('chat_id', ''), row.get('ws_st', ''), row.get('ws_stop', ''), row.get('web_st', 0), row.get('fin_prog', 0), row.get('b_city', ''), row.get('b_fin', ''), row.get('b_ban', ''), row.get('b_ign', ''), row.get('b_baners', ''), row.get('b_butt', ''), row.get('b_mess', ''), row.get('shop_st', ''), row.get('curator', ''), row.get('pr1', ''), row.get('pr2', ''), row.get('pr3', ''), row.get('pr4', ''), row.get('pr5', ''), row.get('gc_url', ''), row.get('key_pr', ''), row.get('n_con', ''), row.get('canal', ''), data_t, row.get('utm_source', ''), row.get('utm_medium', ''), row.get('utm_campaign', ''), row.get('utm_term', ''), row.get('utm_content', '')]
1806
 
1807
  placeholders = ', '.join(['?' for _ in columns])
1808
  columns_str = ', '.join(columns)
 
1814
 
1815
  try:
1816
  cursor.execute(query, values)
 
 
1817
  except Exception as e:
1818
  print(f"Error inserting row: {row}")
1819
  print(f"Error message: {str(e)}")
1820
  conn.rollback()
1821
+ continue
1822
 
1823
  conn.commit()
1824
  conn.close()
1825
 
1826
+ # Маршрут для загрузки JSON-файла
1827
+ @app.route('/upload_json', methods=['POST'])
1828
+ def upload_json():
1829
  if 'file' not in request.files:
1830
  return jsonify({"error": "No file part"}), 400
1831
  file = request.files['file']
1832
  if file.filename == '':
1833
  return jsonify({"error": "No selected file"}), 400
1834
+ if file and file.filename.endswith('.json'):
1835
+ data = json.load(file)
1836
+ insert_data(data)
 
 
 
 
 
 
 
1837
  return jsonify({"message": "Data uploaded and inserted successfully"})
1838
  return jsonify({"error": "Invalid file format"}), 400
1839
 
1840
+ # Маршрут для отображения формы загрузки JSON
1841
+ @app.route('/upl_json', methods=['GET'])
1842
+ def display_form():
1843
+ return render_template('upload_json.html')
 
 
 
1844
 
1845
 
1846