-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
244 lines (191 loc) · 7.23 KB
/
main.py
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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
from json import encoder
from flask import Flask, render_template, jsonify, g, request, session, url_for, redirect
from datetime import datetime
import socket, threading, pymysql, os, json
from werkzeug.datastructures import Range
# server config
app = Flask(__name__)
app.secret_key = str(os.urandom(256))
def get_conn():
if "conn" not in g:
g.conn = pymysql.connect(
host=os.getenv('FLASK_DATABASE_HOST'),
user=os.getenv('FLASK_DATABASE_USER'),
password=os.getenv('FLASK_DATABASE_PASSWORD'),
database=os.getenv('FLASK_DATABASE')
)
g.cur=g.conn.cursor()
return g.conn, g.cur
####
def udp():
conn = pymysql.connect(
host=os.getenv('FLASK_DATABASE_HOST'),
user=os.getenv('FLASK_DATABASE_USER'),
password=os.getenv('FLASK_DATABASE_PASSWORD'),
database=os.getenv('FLASK_DATABASE')
)
cur=conn.cursor()
try:
server_udp = socket.socket(family=socket.AF_INET, type=socket.SOCK_DGRAM)
server_udp.bind(('0.0.0.0', 8051)) #cualquier cliente de la app, puede mandar datos
print("Servidor UDP funcionando...")
while True:
server_address = server_udp.recvfrom(1024)
msg = server_address[0]
msg = str(msg)
msg = msg[1:]
adrrs = server_address[1]
print (f"La direccion IP del emisor: {adrrs}")
print (f"El mensaje recibido es: {msg}")
arr = msg.split(",")
dt=arr[4]+ " " +arr[3]
placa=arr[6]
print (placa)
print(arr[7])
cur.execute(f"INSERT INTO {placa} (Latitud, Longitud, Fhora, RPM) VALUES (%s,%s,%s,%s)", (arr[1],arr[2],dt,arr[7]))
conn.commit()
except:
pass
# api
# login
"""@app.before_request
def before():
url = request.path
if not 'placa' in session and url != '/login' and url != "/registrar" or url != "/multiples" and not url.startswith("/static"):
return redirect('/login')"""
@app.route('/<placa>/sqlplaca')
def get_placa(placa:str=""):
conn, cur = get_conn()
cur=conn.cursor()
cur.execute(f"SELECT * FROM {placa} WHERE Id = (SELECT MAX(Id) FROM {placa})")
conn.commit() #si lo quito no sirve
datos = cur.fetchall()
cur.close()
def datetime_handler(x):
if isinstance(x, (datetime,datetime)):
return x.isoformat()
raise TypeError("Unknown type")
var1 = json.dumps(datos, default=datetime_handler)
return var1
@app.route('/<placa>/sqldata')
def get_data(placa:str=""):
placa = session.get('placa', None)
conn, cur = get_conn()
cur=conn.cursor()
cur.execute(f"SELECT * FROM {placa} WHERE Id = (SELECT MAX(Id) FROM {placa})")
conn.commit() #si lo quito no sirve
datos = cur.fetchall()
cur.close()
def datetime_handler(x):
if isinstance(x, (datetime,datetime)):
return x.isoformat()
raise TypeError("Unknown type")
var1 = json.dumps(datos, default=datetime_handler)
return var1
@app.route('/hmult')
def hmult():
return render_template('hmult.html',text="Inicio", url="logout")
@app.route('/hmultiple')
def get_hmult(placa:str=""):
init_date = request.args.get("param1")
final_date = request.args.get("param2")
conn, cur = get_conn()
cur=conn.cursor()
cur.execute(f"SELECT * FROM {placa} WHERE FHora between '"+ init_date +"' AND '"+ final_date +"'")
conn.commit() #si lo quito no sirve
datos = cur.fetchall()
cur.close()
return jsonify(datos)
@app.route('/<placa>/historicos')
def get_history(placa:str=""):
print(placa)
init_date = request.args.get("param1")
final_date = request.args.get("param2")
conn, cur = get_conn()
cur=conn.cursor()
cur.execute(f"SELECT * FROM {placa} WHERE FHora between '"+ init_date +"' AND '"+ final_date +"'")
conn.commit() #si lo quito no sirve
datos = cur.fetchall()
cur.close()
return jsonify(datos)
#enviar datos a app
@app.route('/changes', methods=["POST","GET"]) #git hub
def pull():
os.system('cd /home/ubuntu/Server_Taxi && git reset --hard && git pull') #esta linea de codigo hace que sea automatico el cambio del codigo si todas las instancias estan prendidas
return 'hello'
# rutas
@app.route('/<placa>/historial')
def historial(placa:str = ''):
for i in range(len(placas)):
if placas[i] == session[f'placa{i}']:
print(placas[i])
return render_template("Historial.html",text="Cerrar sesión", url="logout", texto_1="Tiempo real", texto_2="",placas=placas)
# rutas principales
@app.route('/registrar', methods = ["POST","GET"])
def register():
if request.method == 'POST':
placa = request.form["placa"]
conn, cur = get_conn()
cur=conn.cursor()
cur.execute("Show tables;")
myresult = cur.fetchall()
cur.close()
for i in range(len(myresult)):
if myresult[i][0] == placa:
return render_template("signup.html")
else:
sql = f"CREATE TABLE {placa} (id INT AUTO_INCREMENT PRIMARY KEY, Latitud VARCHAR(15), Longitud VARCHAR(15), FHora DATETIME)"
conn, cur = get_conn()
cur=conn.cursor()
cur.execute(sql)
conn.commit() #si lo quito no sirve
cur.close()
return redirect('/login')
else:
return render_template("signup.html")
@app.route('/multiples')
def multiples():
return render_template("multiples.html",text="Inicio", url="logout")
@app.route('/logout')
def logout():
session.pop("placa", None)
return redirect("/login")
@app.route('/')
@app.route('/login', methods=['POST', 'GET'])
def login():
if request.method == 'POST':
n = request.form['numero']
print (n)
global placas
placas = []
for i in range(int(n)):
placas.append(request.form[f'placa{i}'])
conn, cur = get_conn()
cur=conn.cursor()
cur.execute("Show tables;")
myresult = cur.fetchall()
cur.close()
for j in range(int(n)):
session[f'placa{j}'] = placas[j]
return redirect(url_for("index", placa=placas))
else:
conn, cur = get_conn()
cur=conn.cursor()
cur.execute("SELECT * FROM placas;")
myresult = cur.fetchall()
cur.close()
#print(myresult)
placas = [placa[1] for placa in myresult]
#show tables
return render_template('buscar.html', text="Registrar", url="registrar", texto_1="", texto_2="", placas=placas)
#Enviar lista en vez de placa
@app.route('/<placa>')
def index(placa:str = ''):
for i in range(len(placas)):
if placas[i] == session[f'placa{i}']:
return render_template('index.html', text="Cerrar sesión", url="logout", texto_1="", texto_2="Historial",placas=placas)
return "Placa invalida"
if __name__ == '__main__':
server_udp = threading.Thread(target=udp, daemon=True)
server_udp.start()
app.run(host='0.0.0.0', debug=True, port=8888)