Spaces:
				
			
			
	
			
			
		Sleeping
		
	
	
	
			
			
	
	
	
	
		
		
		Sleeping
		
	Update app.py
Browse files
    	
        app.py
    CHANGED
    
    | @@ -1703,7 +1703,18 @@ def verify_phone_number2(phone_number): | |
| 1703 | 
             
                else:
         | 
| 1704 | 
             
                    return "false"
         | 
| 1705 |  | 
| 1706 | 
            -
             | 
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
| 1707 | 
             
                global current_curator_index
         | 
| 1708 | 
             
                conn = sqlite3.connect(DATABASE2)
         | 
| 1709 | 
             
                cursor = conn.cursor()
         | 
| @@ -1711,6 +1722,7 @@ def insert_data2(data, template_key): | |
| 1711 | 
             
                mapping_template_cur = mapp_templates.get(template_key, mt_avp)
         | 
| 1712 |  | 
| 1713 | 
             
                for row in data:
         | 
|  | |
| 1714 | 
             
                    utc_now = datetime.utcnow()
         | 
| 1715 | 
             
                    msk_tz = pytz.timezone('Europe/Moscow')
         | 
| 1716 | 
             
                    msk_now = utc_now.replace(tzinfo=pytz.utc).astimezone(msk_tz)
         | 
| @@ -1726,10 +1738,21 @@ def insert_data2(data, template_key): | |
| 1726 | 
             
                        print(f"Missing required fields in row: {row}. Skipping insert.")
         | 
| 1727 | 
             
                        continue
         | 
| 1728 |  | 
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
| 1729 | 
             
                    if curator_on_off == "1":
         | 
| 1730 | 
             
                        user_data['curator'] = curators[current_curator_index]
         | 
| 1731 | 
             
                        current_curator_index = (current_curator_index + 1) % len(curators)
         | 
| 1732 |  | 
|  | |
| 1733 | 
             
                    if verifikation_start == "1":
         | 
| 1734 | 
             
                        user_data['ws_st'] = verify_phone_number2(phone)
         | 
| 1735 |  | 
| @@ -1749,13 +1772,8 @@ def insert_data2(data, template_key): | |
| 1749 | 
             
                        VALUES ({placeholders})
         | 
| 1750 | 
             
                    '''
         | 
| 1751 |  | 
| 1752 | 
            -
                    # Вывод информации о строке перед записью в базу данных
         | 
| 1753 | 
            -
                    print(f"Inserting row: {user_data}")
         | 
| 1754 | 
            -
             | 
| 1755 | 
             
                    try:
         | 
| 1756 | 
             
                        cursor.execute(query, [user_data.get(field, '') for field in fields])
         | 
| 1757 | 
            -
                        # Вывод информации о том, что запись была успешно выполнена
         | 
| 1758 | 
            -
                        print(f"Row inserted successfully: {user_data}")
         | 
| 1759 | 
             
                    except Exception as e:
         | 
| 1760 | 
             
                        print(f"Error inserting row: {row}")
         | 
| 1761 | 
             
                        print(f"Error message: {str(e)}")
         | 
| @@ -1765,12 +1783,15 @@ def insert_data2(data, template_key): | |
| 1765 | 
             
                conn.commit()
         | 
| 1766 | 
             
                conn.close()
         | 
| 1767 |  | 
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
| 1768 | 
             
            @app.route('/upload_csv', methods=['POST'])
         | 
| 1769 | 
             
            def upload_csv():
         | 
| 1770 | 
            -
                global verifikation_start, curator_on_off
         | 
| 1771 | 
            -
             | 
| 1772 | 
            -
                template_key = 'avp'  # Исправлено на существующий ключ
         | 
| 1773 | 
            -
             | 
| 1774 | 
             
                if 'file' not in request.files:
         | 
| 1775 | 
             
                    return jsonify({"error": "No file part"}), 400
         | 
| 1776 | 
             
                file = request.files['file']
         | 
| @@ -1780,7 +1801,8 @@ def upload_csv(): | |
| 1780 | 
             
                    stream = io.StringIO(file.stream.read().decode("UTF8"), newline=None)
         | 
| 1781 | 
             
                    csv_input = csv.DictReader(stream)
         | 
| 1782 | 
             
                    data = [row for row in csv_input]
         | 
| 1783 | 
            -
                     | 
|  | |
| 1784 | 
             
                    return jsonify({"message": "Data uploaded and inserted successfully"})
         | 
| 1785 | 
             
                return jsonify({"error": "Invalid file format"}), 400
         | 
| 1786 |  | 
|  | |
| 1703 | 
             
                else:
         | 
| 1704 | 
             
                    return "false"
         | 
| 1705 |  | 
| 1706 | 
            +
            # Функция для обработки CSV данных
         | 
| 1707 | 
            +
            def parse_csv_data(data):
         | 
| 1708 | 
            +
                parsed_data = []
         | 
| 1709 | 
            +
                for item in data:
         | 
| 1710 | 
            +
                    for key, value in item.items():
         | 
| 1711 | 
            +
                        headers = key.split(';')
         | 
| 1712 | 
            +
                        row = value.split(';')
         | 
| 1713 | 
            +
                        parsed_data.append(dict(zip(headers, row)))
         | 
| 1714 | 
            +
                return parsed_data
         | 
| 1715 | 
            +
             | 
| 1716 | 
            +
            # Функция для вставки данных в базу данных
         | 
| 1717 | 
            +
            def insert_data(data, template_key):
         | 
| 1718 | 
             
                global current_curator_index
         | 
| 1719 | 
             
                conn = sqlite3.connect(DATABASE2)
         | 
| 1720 | 
             
                cursor = conn.cursor()
         | 
|  | |
| 1722 | 
             
                mapping_template_cur = mapp_templates.get(template_key, mt_avp)
         | 
| 1723 |  | 
| 1724 | 
             
                for row in data:
         | 
| 1725 | 
            +
                    # Получение текущего времени в московском часовом поясе
         | 
| 1726 | 
             
                    utc_now = datetime.utcnow()
         | 
| 1727 | 
             
                    msk_tz = pytz.timezone('Europe/Moscow')
         | 
| 1728 | 
             
                    msk_now = utc_now.replace(tzinfo=pytz.utc).astimezone(msk_tz)
         | 
|  | |
| 1738 | 
             
                        print(f"Missing required fields in row: {row}. Skipping insert.")
         | 
| 1739 | 
             
                        continue
         | 
| 1740 |  | 
| 1741 | 
            +
                    # Проверка существования пользователя в базе данных по email или телефону
         | 
| 1742 | 
            +
                    cursor.execute("SELECT 1 FROM contacts WHERE email = ? OR phone = ?", (email, phone))
         | 
| 1743 | 
            +
                    user_exists = cursor.fetchone()
         | 
| 1744 | 
            +
             | 
| 1745 | 
            +
                    # Если пользователь существует, пропускаем вставку
         | 
| 1746 | 
            +
                    if user_exists:
         | 
| 1747 | 
            +
                        print(f"User with email {email} or phone {phone} already exists. Skipping insert.")
         | 
| 1748 | 
            +
                        continue
         | 
| 1749 | 
            +
             | 
| 1750 | 
            +
                    # Назначение куратора
         | 
| 1751 | 
             
                    if curator_on_off == "1":
         | 
| 1752 | 
             
                        user_data['curator'] = curators[current_curator_index]
         | 
| 1753 | 
             
                        current_curator_index = (current_curator_index + 1) % len(curators)
         | 
| 1754 |  | 
| 1755 | 
            +
                    # Верификация номера телефона
         | 
| 1756 | 
             
                    if verifikation_start == "1":
         | 
| 1757 | 
             
                        user_data['ws_st'] = verify_phone_number2(phone)
         | 
| 1758 |  | 
|  | |
| 1772 | 
             
                        VALUES ({placeholders})
         | 
| 1773 | 
             
                    '''
         | 
| 1774 |  | 
|  | |
|  | |
|  | |
| 1775 | 
             
                    try:
         | 
| 1776 | 
             
                        cursor.execute(query, [user_data.get(field, '') for field in fields])
         | 
|  | |
|  | |
| 1777 | 
             
                    except Exception as e:
         | 
| 1778 | 
             
                        print(f"Error inserting row: {row}")
         | 
| 1779 | 
             
                        print(f"Error message: {str(e)}")
         | 
|  | |
| 1783 | 
             
                conn.commit()
         | 
| 1784 | 
             
                conn.close()
         | 
| 1785 |  | 
| 1786 | 
            +
            # Проверка ключа API
         | 
| 1787 | 
            +
            @app.before_request
         | 
| 1788 | 
            +
            def verify_api_key():
         | 
| 1789 | 
            +
                api_key = request.args.get('api_key')
         | 
| 1790 | 
            +
                if api_key != "fasSd345D":
         | 
| 1791 | 
            +
                    return jsonify({"error": "Invalid API key"}), 403
         | 
| 1792 | 
            +
             | 
| 1793 | 
             
            @app.route('/upload_csv', methods=['POST'])
         | 
| 1794 | 
             
            def upload_csv():
         | 
|  | |
|  | |
|  | |
|  | |
| 1795 | 
             
                if 'file' not in request.files:
         | 
| 1796 | 
             
                    return jsonify({"error": "No file part"}), 400
         | 
| 1797 | 
             
                file = request.files['file']
         | 
|  | |
| 1801 | 
             
                    stream = io.StringIO(file.stream.read().decode("UTF8"), newline=None)
         | 
| 1802 | 
             
                    csv_input = csv.DictReader(stream)
         | 
| 1803 | 
             
                    data = [row for row in csv_input]
         | 
| 1804 | 
            +
                    parsed_data = parse_csv_data(data)
         | 
| 1805 | 
            +
                    insert_data(parsed_data, 'avp')
         | 
| 1806 | 
             
                    return jsonify({"message": "Data uploaded and inserted successfully"})
         | 
| 1807 | 
             
                return jsonify({"error": "Invalid file format"}), 400
         | 
| 1808 |  |