DmitrMakeev
commited on
Commit
•
d45745f
1
Parent(s):
19f25d6
Update app.py
Browse files
app.py
CHANGED
@@ -1187,75 +1187,106 @@ def parse_csv_data(data):
|
|
1187 |
parsed_data.append(dict(zip(headers, row)))
|
1188 |
return parsed_data
|
1189 |
|
1190 |
-
def
|
1191 |
-
conn = sqlite3.connect(
|
1192 |
cursor = conn.cursor()
|
1193 |
-
# Инвертируем порядок данных
|
1194 |
-
data = reversed(data)
|
1195 |
-
for row in data:
|
1196 |
-
# Получение текущего времени в московском часовом поясе
|
1197 |
-
utc_now = datetime.utcnow()
|
1198 |
-
msk_tz = pytz.timezone('Europe/Moscow')
|
1199 |
-
msk_now = utc_now.replace(tzinfo=pytz.utc).astimezone(msk_tz)
|
1200 |
-
data_t = msk_now.strftime('%Y-%m-%d %H:%M:%S')
|
1201 |
|
1202 |
-
|
1203 |
-
|
1204 |
-
|
1205 |
-
|
1206 |
-
|
1207 |
-
chat_id = row.get('chat_id', '')
|
1208 |
-
ws_st = row.get('ws_st', '')
|
1209 |
-
ws_stop = row.get('ws_stop', '')
|
1210 |
-
web_st = row.get('web_st', 0)
|
1211 |
-
fin_prog = row.get('fin_prog', 0)
|
1212 |
-
b_city = row.get('b_city', '')
|
1213 |
-
b_fin = row.get('b_fin', '')
|
1214 |
-
b_ban = row.get('b_ban', '')
|
1215 |
-
b_ign = row.get('b_ign', '')
|
1216 |
-
b_baners = row.get('b_baners', '')
|
1217 |
-
b_butt = row.get('b_butt', '')
|
1218 |
-
b_mess = row.get('b_mess', '')
|
1219 |
-
shop_st = row.get('shop_st', '')
|
1220 |
-
curator = row.get('curator', '')
|
1221 |
-
pr1 = row.get('pr1', '')
|
1222 |
-
pr2 = row.get('pr2', '')
|
1223 |
-
pr3 = row.get('pr3', '')
|
1224 |
-
pr4 = row.get('pr4', '')
|
1225 |
-
pr5 = row.get('pr5', '')
|
1226 |
-
ad_url = row.get('ad_url', '')
|
1227 |
-
key_pr = row.get('key_pr', '')
|
1228 |
-
n_con = row.get('n_con', '')
|
1229 |
-
canal = row.get('canal', '')
|
1230 |
-
|
1231 |
-
# Создание динамического SQL-запроса с использованием INSERT ON CONFLICT
|
1232 |
-
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']
|
1233 |
-
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]
|
1234 |
-
|
1235 |
-
placeholders = ', '.join(['?' for _ in columns])
|
1236 |
-
columns_str = ', '.join(columns)
|
1237 |
-
|
1238 |
-
update_str = ', '.join([f"{col} = excluded.{col}" for col in columns if col != 'email'])
|
1239 |
-
|
1240 |
-
query = f'''
|
1241 |
-
INSERT INTO contacts ({columns_str})
|
1242 |
-
VALUES ({placeholders})
|
1243 |
-
ON CONFLICT(email) DO UPDATE SET
|
1244 |
-
{update_str}
|
1245 |
-
'''
|
1246 |
|
1247 |
-
|
1248 |
-
|
1249 |
-
|
1250 |
-
|
1251 |
-
|
1252 |
-
|
1253 |
-
raise
|
1254 |
|
1255 |
-
|
1256 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1257 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1258 |
|
|
|
|
|
|
|
|
|
1259 |
|
1260 |
@app.route('/upload_csv', methods=['POST'])
|
1261 |
def upload_csv():
|
@@ -1269,7 +1300,18 @@ def upload_csv():
|
|
1269 |
csv_input = csv.DictReader(stream)
|
1270 |
data = [row for row in csv_input]
|
1271 |
parsed_data = parse_csv_data(data)
|
1272 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1273 |
return jsonify({"message": "Data uploaded and inserted successfully"})
|
1274 |
return jsonify({"error": "Invalid file format"}), 400
|
1275 |
|
|
|
1187 |
parsed_data.append(dict(zip(headers, row)))
|
1188 |
return parsed_data
|
1189 |
|
1190 |
+
def update_or_insert_user(db_name, user_data, mapping_template):
|
1191 |
+
conn = sqlite3.connect(db_name)
|
1192 |
cursor = conn.cursor()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1193 |
|
1194 |
+
# Получение email пользователя из данных
|
1195 |
+
email = user_data.get('Email')
|
1196 |
+
if not email:
|
1197 |
+
logging.error(f"User data missing email: {user_data}")
|
1198 |
+
return
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1199 |
|
1200 |
+
logging.debug(f"Processing user with email: {email}")
|
1201 |
+
|
1202 |
+
# Проверка существования пользователя в базе данных по email
|
1203 |
+
cursor.execute("SELECT web_st FROM contacts WHERE email = ?", (email,))
|
1204 |
+
user = cursor.fetchone()
|
1205 |
+
logging.debug(f"User found: {user}")
|
|
|
1206 |
|
1207 |
+
# Вынесение увеличения значения web_st в отдельный блок
|
1208 |
+
web_st_value = 1 # Инициализация значения web_st
|
1209 |
+
if user:
|
1210 |
+
# Проверка текущего значения web_st и его инкрементация
|
1211 |
+
current_web_st = user[0] if user[0] is not None and user[0] != "" else 0
|
1212 |
+
web_st_value = int(current_web_st) + 1
|
1213 |
+
logging.debug(f"Calculated web_st_value: {web_st_value}")
|
1214 |
+
|
1215 |
+
# Обновление значения web_st
|
1216 |
+
cursor.execute("UPDATE contacts SET web_st = ? WHERE email = ?", (web_st_value, email))
|
1217 |
+
conn.commit()
|
1218 |
+
conn.close()
|
1219 |
+
logging.debug(f"User {email} web_st updated to {web_st_value}")
|
1220 |
+
else:
|
1221 |
+
conn.close()
|
1222 |
+
logging.debug(f"User {email} not found, proceeding with insert")
|
1223 |
+
|
1224 |
+
# Открываем соединение снова для остальных операций
|
1225 |
+
conn = sqlite3.connect(db_name)
|
1226 |
+
cursor = conn.cursor()
|
1227 |
+
|
1228 |
+
# Преобразование данных пользователя на основе шаблона сопоставления
|
1229 |
+
transformed_data = {}
|
1230 |
+
for json_key, db_column in mapping_template.items():
|
1231 |
+
value = user_data.get(json_key, "")
|
1232 |
+
|
1233 |
+
if isinstance(value, list):
|
1234 |
+
# Проверяем тип элементов списка
|
1235 |
+
if all(isinstance(item, str) for item in value):
|
1236 |
+
transformed_data[db_column] = "; ".join(value) # Сохраняем сообщения в строку
|
1237 |
+
else:
|
1238 |
+
logging.error(f"Expected list of strings for key {json_key}, but got: {value}")
|
1239 |
+
transformed_data[db_column] = ""
|
1240 |
+
else:
|
1241 |
+
transformed_data[db_column] = str(value)
|
1242 |
+
logging.debug(f"Transformed data: {transformed_data}")
|
1243 |
+
|
1244 |
+
# Заполнение обязательных полей значениями по умолчанию
|
1245 |
+
required_fields = [
|
1246 |
+
"vk_id", "chat_id", "ws_st", "ws_stop", "web_st", "fin_prog",
|
1247 |
+
"b_city", "b_fin", "b_ban", "b_ign", "b_baners", "b_butt", "b_mess",
|
1248 |
+
"shop_st", "curator", "pr1", "pr2", "pr3", "pr4", "pr5", "ad_url",
|
1249 |
+
"key_pr", "n_con", "canal", "data_t"
|
1250 |
+
]
|
1251 |
+
for field in required_fields:
|
1252 |
+
if field not in transformed_data:
|
1253 |
+
transformed_data[field] = ""
|
1254 |
+
logging.debug(f"Transformed data after adding required fields: {transformed_data}")
|
1255 |
+
|
1256 |
+
# Обработка номера телефона, если он есть
|
1257 |
+
if 'Phone' in user_data:
|
1258 |
+
phone = user_data['Phone']
|
1259 |
+
if phone.startswith('+'):
|
1260 |
+
phone = phone[1:]
|
1261 |
+
transformed_data['phone'] = phone
|
1262 |
+
logging.debug(f"Transformed data after phone processing: {transformed_data}")
|
1263 |
+
|
1264 |
+
# Добавление значения web_st в данные для вставки
|
1265 |
+
transformed_data['web_st'] = web_st_value
|
1266 |
|
1267 |
+
# Обновление данных пользователя в базе данных
|
1268 |
+
if user:
|
1269 |
+
update_query = "UPDATE contacts SET "
|
1270 |
+
update_values = []
|
1271 |
+
for column, value in transformed_data.items():
|
1272 |
+
update_query += f"{column} = ?, "
|
1273 |
+
update_values.append(value)
|
1274 |
+
update_query = update_query.rstrip(", ") + " WHERE email = ?"
|
1275 |
+
update_values.append(email)
|
1276 |
+
logging.debug(f"Update query: {update_query} with values: {update_values}")
|
1277 |
+
cursor.execute(update_query, update_values)
|
1278 |
+
else:
|
1279 |
+
columns = ', '.join(transformed_data.keys())
|
1280 |
+
placeholders = ', '.join('?' for _ in transformed_data)
|
1281 |
+
insert_query = f"INSERT INTO contacts ({columns}) VALUES ({placeholders})"
|
1282 |
+
insert_values = list(transformed_data.values())
|
1283 |
+
logging.debug(f"Insert query: {insert_query} with values: {insert_values}")
|
1284 |
+
cursor.execute(insert_query, insert_values)
|
1285 |
|
1286 |
+
# Подтверждение изменений и закрытие соединения
|
1287 |
+
conn.commit()
|
1288 |
+
conn.close()
|
1289 |
+
logging.debug(f"User with email {email} processed successfully")
|
1290 |
|
1291 |
@app.route('/upload_csv', methods=['POST'])
|
1292 |
def upload_csv():
|
|
|
1300 |
csv_input = csv.DictReader(stream)
|
1301 |
data = [row for row in csv_input]
|
1302 |
parsed_data = parse_csv_data(data)
|
1303 |
+
|
1304 |
+
# Пример шаблона сопоставления
|
1305 |
+
mapping_template = {
|
1306 |
+
'Email': 'email',
|
1307 |
+
'Name': 'name',
|
1308 |
+
'Phone': 'phone',
|
1309 |
+
# Добавьте остальные поля в шаблон сопоставления
|
1310 |
+
}
|
1311 |
+
|
1312 |
+
for user_data in parsed_data:
|
1313 |
+
update_or_insert_user(DATABASE2, user_data, mapping_template)
|
1314 |
+
|
1315 |
return jsonify({"message": "Data uploaded and inserted successfully"})
|
1316 |
return jsonify({"error": "Invalid file format"}), 400
|
1317 |
|