Spaces:
Sleeping
Sleeping
Update main.py
Browse files
main.py
CHANGED
@@ -1,32 +1,100 @@
|
|
1 |
-
from fastapi import FastAPI, Request
|
2 |
-
from fastapi.middleware.cors import CORSMiddleware # Importa il middleware CORS
|
3 |
from fastapi.responses import JSONResponse
|
4 |
-
import requests
|
5 |
-
import os
|
6 |
-
import socket
|
7 |
-
import time
|
8 |
-
from enum import Enum
|
9 |
-
import random
|
10 |
-
import aiohttp
|
11 |
-
import asyncio
|
12 |
import json
|
|
|
|
|
|
|
|
|
13 |
|
14 |
-
|
15 |
app = FastAPI()
|
16 |
|
17 |
-
|
18 |
-
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
-
|
|
|
24 |
|
25 |
-
|
26 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
27 |
data = await request.json()
|
28 |
-
print(data)
|
29 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
30 |
|
31 |
@app.get("/")
|
32 |
def read_general():
|
|
|
1 |
+
from fastapi import FastAPI, Request, HTTPException
|
|
|
2 |
from fastapi.responses import JSONResponse
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
3 |
import json
|
4 |
+
from datetime import datetime
|
5 |
+
import pyodbc
|
6 |
+
import os
|
7 |
+
from dotenv import load_dotenv
|
8 |
|
9 |
+
load_dotenv()
|
10 |
app = FastAPI()
|
11 |
|
12 |
+
# --------------------------------------------| CONNESSIONE DB |-------------------------------------------------
|
13 |
+
# Connessione al DB Web (Amazon RDS)
|
14 |
+
def get_db_connection():
|
15 |
+
server = os.getenv('SERVER_DB')
|
16 |
+
username = os.getenv('USERNAME_DB')
|
17 |
+
password = os.getenv('PASSWORD_DB')
|
18 |
+
connection_string = f"DRIVER={{ODBC Driver 17 for SQL Server}};SERVER={server};UID={username};PWD={password}"
|
19 |
+
return pyodbc.connect(connection_string)
|
20 |
|
21 |
+
# --------------------------------------------| CREAZIONE AZIENDA-DB |-------------------------------------------------
|
22 |
+
# Controllo se presente il Database e la tabella aziendale. Se non ci sono le creo
|
23 |
+
def crea_database_azienda(database, azienda):
|
24 |
+
tabella = f"{azienda.upper()}transazioni"
|
25 |
+
conn = get_db_connection()
|
26 |
+
cursor = conn.cursor()
|
27 |
+
# Controllo presenza DATABASE
|
28 |
+
conn.autocommit = True
|
29 |
+
check_db_query = f"""
|
30 |
+
IF NOT EXISTS (SELECT name FROM sys.databases WHERE name = '{database}')
|
31 |
+
BEGIN
|
32 |
+
CREATE DATABASE {database};
|
33 |
+
END
|
34 |
+
"""
|
35 |
+
cursor.execute(check_db_query)
|
36 |
+
cursor.execute(f"USE {database}")
|
37 |
+
conn.autocommit = False
|
38 |
+
#Controllo presenza TABELLA
|
39 |
+
check_table_query = f"""
|
40 |
+
IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME = '{tabella}')
|
41 |
+
BEGIN
|
42 |
+
EXEC('CREATE TABLE dbo.{tabella} (
|
43 |
+
id INT IDENTITY(1,1) PRIMARY KEY,
|
44 |
+
datreg DATETIME NOT NULL,
|
45 |
+
azione VARCHAR(255) NOT NULL,
|
46 |
+
id_transazione VARCHAR(50) NOT NULL,
|
47 |
+
jsonCompleto NVARCHAR(MAX) NOT NULL
|
48 |
+
)');
|
49 |
+
END
|
50 |
+
"""
|
51 |
+
cursor.execute(check_table_query)
|
52 |
+
conn.commit()
|
53 |
+
cursor.close()
|
54 |
+
conn.close()
|
55 |
+
|
56 |
+
# ------------------------------------------------| POST |--------------------------------------------------
|
57 |
+
# Inizio transazione (questo endpoint viene chiamato dal RENTRI come CALLBACK per il PUSH Request)
|
58 |
+
@app.post("/{azione}/{versione}/{database}/{azienda}/start")
|
59 |
+
async def receive_post(request: Request, azione: str, versione :str, database: str, azienda: str):
|
60 |
data = await request.json()
|
61 |
+
print(azione + " " + database + " " + azienda + " " + json.dumps(data, indent=3))
|
62 |
+
conn = get_db_connection()
|
63 |
+
cursor = conn.cursor()
|
64 |
+
crea_database_azienda(database, azienda)
|
65 |
+
insert_query = f"INSERT INTO [{database}].dbo.{azienda}transazioni (datreg, azione, id_transazione, JsonCompleto) VALUES (?, ?, ?, ?)"
|
66 |
+
cursor.execute(insert_query, (datetime.now(), azione, data.get('transazione_id'), json.dumps(data)))
|
67 |
+
conn.commit()
|
68 |
+
cursor.close()
|
69 |
+
conn.close()
|
70 |
+
return JSONResponse(content={"message": "Received", "data": data})
|
71 |
+
|
72 |
+
# ------------------------------------------------| GET |-----------------------------------------------------
|
73 |
+
# Result/Status transazione (Questo endpoint viene chiamato da AdHoc per leggere il risultato della transazione) /dati-registri/v1.0/id_transazione/STATUS/Azienda
|
74 |
+
@app.get("/{azione}/{versione}/{database}/{azienda}/{id_transazione}/{tipo}")
|
75 |
+
async def get_status(azione: str, versione: str, id_transazione: str, tipo: str, database: str, azienda: str):
|
76 |
+
conn = get_db_connection()
|
77 |
+
cursor = conn.cursor()
|
78 |
+
select_query = f"SELECT TOP 1 JsonCompleto FROM [{database}].dbo.{azienda}transazioni WHERE azione = ? AND id_transazione = ? order by id desc"
|
79 |
+
cursor.execute(select_query, (azione, id_transazione))
|
80 |
+
row = cursor.fetchone()
|
81 |
+
cursor.close()
|
82 |
+
conn.close()
|
83 |
+
# STATUS: Restituisce 303 se esiste la riga della transazione (cioè se per il rentri è terminata)
|
84 |
+
if tipo == "status":
|
85 |
+
if not row:
|
86 |
+
raise HTTPException(status_code=200, detail="Transazione non terminata")
|
87 |
+
else:
|
88 |
+
raise HTTPException(status_code=303, detail="Transazione terminata")
|
89 |
+
# RESULT: Restituisce 303 se esiste la riga della transazione (cioè se per il rentri è terminata)
|
90 |
+
elif tipo == "result":
|
91 |
+
if not row:
|
92 |
+
raise HTTPException(status_code=404, detail="Transazione non terminata")
|
93 |
+
else:
|
94 |
+
result = json.loads(row.JsonCompleto)
|
95 |
+
return JSONResponse(content=result)
|
96 |
+
else:
|
97 |
+
raise HTTPException(status_code=404, detail="Endpoint non trovato")
|
98 |
|
99 |
@app.get("/")
|
100 |
def read_general():
|