Spaces:
Sleeping
Sleeping
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 | |
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) | |
async def receive_post(request: Request, azione: str, versione :str, database: str, azienda: str): | |
data = await request.json() | |
print(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 | |
async def get_status(azione: str, versione: str, id_transazione: str, tipo: str, database: str, azienda: str): | |
print('{"message": "OK"}') | |
return '{"message": "OK"}' | |
#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") | |
def read_general(): | |
return {"response": "Benvenuto. Per maggiori info: https://matteoscript-RentriWebServer.hf.space/docs"} |