Repository navigation
Expand file tree
/
Copy pathbackend.py
More file actions
64 lines (52 loc) · 2.46 KB
/
Copy pathbackend.py
File metadata and controls
64 lines (52 loc) · 2.46 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# Back-end:
# Lê um XLSX (começando da 2ª linha, 1ª e 2ª colunas).
# Trunca a tabela staging, insere os dados e executa a stored procedure.
# Exporta as 3 tabelas resultantes para um XLSX com 3 abas.
# Devolve uma mensagem (sucesso ou erro) para o front-end.
import os
import pandas as pd
from sqlalchemy import create_engine, text
SQL_SERVER = "SEU_SERVIDOR" # ex.: "localhost\\SQLEXPRESS"
SQL_DATABASE = "SEU_BANCO_DE_DADOS" # ex.: "Enriquecimento"
SQL_DRIVER = "ODBC Driver 17 for SQL Server"
TABELA_STAGING = "sua_tabela"
STORED_PROCEDURE = "sua_procedure"
TABELA1, TABELA2, TABELA3 = "tabela1", "tabela2", "tabela3"
def criar_engine():
# Cria a SQLAlchemy engine via pyodbc (sem urllib).
driver_enc = SQL_DRIVER.replace(" ", "+")
conn_str = (
f"mssql+pyodbc://@{SQL_SERVER}/{SQL_DATABASE}"
f"?driver={driver_enc}&trusted_connection=yes"
)
return create_engine(conn_str, fast_executemany=True)
def processar_enriquecimento(arquivo_excel: str) -> str:
# Executa todo o pipeline e devolve uma string de status para o front-end.
try:
df = pd.read_excel(arquivo_excel, header=None)
if df.shape[1] < 2:
return "O arquivo precisa ter, pelo menos, duas colunas."
dados = df.iloc[1:, [0, 1]]
dados.columns = ["cpf_cnpj", "tipo_pessoa"]
engine = criar_engine()
with engine.begin() as conn:
conn.execute(text(f"TRUNCATE TABLE {TABELA_STAGING}"))
dados.to_sql(
TABELA_STAGING,
con=conn,
if_exists="append",
index=False,
method="multi",
)
conn.execute(text(f"EXEC {STORED_PROCEDURE}"))
tabela1 = pd.read_sql(f"SELECT * FROM {TABELA1}", engine)
tabela2 = pd.read_sql(f"SELECT * FROM {TABELA2}", engine)
tabela3 = pd.read_sql(f"SELECT * FROM {TABELA3}", engine)
caminho_saida = os.path.splitext(arquivo_excel)[0] + " - Resultado.xlsx"
with pd.ExcelWriter(caminho_saida, engine="openpyxl") as writer:
tabela1.to_excel(writer, sheet_name="Tabela1", index=False)
tabela2.to_excel(writer, sheet_name="Tabela2", index=False)
tabela3.to_excel(writer, sheet_name="Tabela3", index=False)
return f"Base enriquecida e salva em:\n{caminho_saida}"
except Exception as exc:
return f"Ocorreu um erro:\n{exc}"