Spaces:
Sleeping
Sleeping
File size: 4,595 Bytes
2efccc9 5d26a98 739823d 2efccc9 d707be1 2efccc9 b916cdf c53513a 2efccc9 2cd7197 2efccc9 f7205b4 2efccc9 6159237 c550535 7a4300a f7205b4 |
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 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 |
from fastapi import FastAPI, Request, HTTPException
from fastapi.responses import JSONResponse
import json
from datetime import datetime
import pyodbc
import os
from dotenv import load_dotenv
load_dotenv()
app = FastAPI()
# --------------------------------------------| CONNESSIONE DB |-------------------------------------------------
# Connessione al DB Web (Amazon RDS)
def get_db_connection():
server = os.getenv('SERVER_DB')
username = os.getenv('USERNAME_DB')
password = os.getenv('PASSWORD_DB')
connection_string = f"DRIVER={{ODBC Driver 17 for SQL Server}};SERVER={server};UID={username};PWD={password}"
return pyodbc.connect(connection_string)
# --------------------------------------------| CREAZIONE AZIENDA-DB |-------------------------------------------------
# Controllo se presente il Database e la tabella aziendale. Se non ci sono le creo
def crea_database_azienda(database, azienda):
tabella = f"{azienda.upper()}transazioni"
conn = get_db_connection()
cursor = conn.cursor()
# Controllo presenza DATABASE
conn.autocommit = True
check_db_query = f"""
IF NOT EXISTS (SELECT name FROM sys.databases WHERE name = '{database}')
BEGIN
CREATE DATABASE {database};
END
"""
cursor.execute(check_db_query)
cursor.execute(f"USE {database}")
conn.autocommit = False
#Controllo presenza TABELLA
check_table_query = f"""
IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME = '{tabella}')
BEGIN
EXEC('CREATE TABLE dbo.{tabella} (
id INT IDENTITY(1,1) PRIMARY KEY,
datreg DATETIME NOT NULL,
azione VARCHAR(255) NOT NULL,
id_transazione VARCHAR(50) NOT NULL,
jsonCompleto NVARCHAR(MAX) NOT NULL
)');
END
"""
cursor.execute(check_table_query)
conn.commit()
cursor.close()
conn.close()
# ------------------------------------------------| POST |--------------------------------------------------
# Inizio transazione (questo endpoint viene chiamato dal RENTRI come CALLBACK per il PUSH Request)
@app.post("/{azione}/{versione}/{database}/{azienda}/start")
async def receive_post(request: Request, azione: str, versione :str, database: str, azienda: str):
data = await request.json()
print(azione + " " + database + " " + azienda + " " + json.dumps(data, indent=3))
conn = get_db_connection()
cursor = conn.cursor()
crea_database_azienda(database, azienda)
insert_query = f"INSERT INTO [{database}].dbo.{azienda}transazioni (datreg, azione, id_transazione, JsonCompleto) VALUES (?, ?, ?, ?)"
cursor.execute(insert_query, (datetime.now(), azione, data.get('transazione_id'), json.dumps(data)))
conn.commit()
cursor.close()
conn.close()
return JSONResponse(content={"message": "Received", "data": data})
# ------------------------------------------------| GET |-----------------------------------------------------
# Result/Status transazione (Questo endpoint viene chiamato da AdHoc per leggere il risultato della transazione) /dati-registri/v1.0/id_transazione/STATUS/Azienda
@app.get("/{azione}/{versione}/{database}/{azienda}/{id_transazione}/{tipo}")
async def get_status(azione: str, versione: str, id_transazione: str, tipo: str, database: str, azienda: str):
conn = get_db_connection()
cursor = conn.cursor()
select_query = f"SELECT TOP 1 JsonCompleto FROM [{database}].dbo.{azienda}transazioni WHERE azione = ? AND id_transazione = ? order by id desc"
cursor.execute(select_query, (azione, id_transazione))
row = cursor.fetchone()
cursor.close()
conn.close()
# STATUS: Restituisce 303 se esiste la riga della transazione (cioè se per il rentri è terminata)
if tipo == "status":
if not row:
raise HTTPException(status_code=200, detail="Transazione non terminata")
else:
raise HTTPException(status_code=303, detail="Transazione terminata")
# RESULT: Restituisce 303 se esiste la riga della transazione (cioè se per il rentri è terminata)
elif tipo == "result":
if not row:
raise HTTPException(status_code=404, detail="Transazione non terminata")
else:
result = json.loads(row.JsonCompleto)
return JSONResponse(content=result)
else:
raise HTTPException(status_code=404, detail="Endpoint non trovato")
@app.get("/")
def read_general():
return {"response": "Benvenuto. Per maggiori info: https://matteoscript-RentriWebServer.hf.space/docs"} |