DmitrMakeev commited on
Commit
5d56be8
·
verified ·
1 Parent(s): d08d9bf

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +136 -0
app.py CHANGED
@@ -321,6 +321,142 @@ def plot_ph():
321
 
322
 
323
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
324
  @app.route("/")
325
  def index():
326
  return flask.render_template('index.html')
 
321
 
322
 
323
 
324
+ @app.route('/plot_ph_week', methods=['GET'])
325
+ def plot_ph_week():
326
+ try:
327
+ # Получаем номер недели из параметров запроса
328
+ week_number = request.args.get('week')
329
+
330
+ # Если параметра нет, показываем форму выбора
331
+ if not week_number:
332
+ return '''
333
+ <html>
334
+ <body>
335
+ <h1>Выберите неделю для графика pH</h1>
336
+ <form method="GET">
337
+ <label for="week">Номер недели (1-30):</label>
338
+ <input type="number" id="week" name="week" min="1" max="30" required>
339
+ <br><br>
340
+ <button type="submit">Показать график</button>
341
+ </form>
342
+ </body>
343
+ </html>
344
+ '''
345
+
346
+ # Проверяем, что введённое значение - число от 1 до 30
347
+ try:
348
+ week_number = int(week_number)
349
+ if week_number < 1 or week_number > 30:
350
+ raise ValueError
351
+ except ValueError:
352
+ return '''
353
+ <html>
354
+ <body>
355
+ <h1>Ошибка!</h1>
356
+ <p>Введите номер недели от 1 до 30.</p>
357
+ <button onclick="window.location.href='/plot_ph_week'">Назад</button>
358
+ </body>
359
+ </html>
360
+ '''
361
+
362
+ # Подключаемся к базе данных
363
+ conn = sqlite3.connect('system_data.db')
364
+ cursor = conn.cursor()
365
+
366
+ # Проверяем, существует ли таблица
367
+ cursor.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='system_data'")
368
+ table_exists = cursor.fetchone()
369
+
370
+ if not table_exists:
371
+ return '''
372
+ <html>
373
+ <body>
374
+ <h1>Ошибка!</h1>
375
+ <p>Таблица system_data не существует.</p>
376
+ <button onclick="window.location.href='/plot_ph_week'">Назад</button>
377
+ </body>
378
+ </html>
379
+ '''
380
+
381
+ # Выполняем запрос на выборку данных за выбранную неделю
382
+ cursor.execute('''
383
+ SELECT date_time, ph, dey
384
+ FROM system_data
385
+ WHERE wek = ?
386
+ ORDER BY date_time
387
+ ''', (week_number,))
388
+ rows = cursor.fetchall()
389
+
390
+ conn.close()
391
+
392
+ # Проверяем, есть ли данные
393
+ if not rows:
394
+ return '''
395
+ <html>
396
+ <body>
397
+ <h1>Данные отсутствуют</h1>
398
+ <p>Для выбранной недели нет данных.</p>
399
+ <button onclick="window.location.href='/plot_ph_week'">Выбрать другую неделю</button>
400
+ </body>
401
+ </html>
402
+ '''
403
+
404
+ # Разделяем данные на дату и день недели
405
+ dates = [f"{row[0]} (d: {row[2]})" for row in rows] # Дата и день недели
406
+ ph_values = [float(row[1]) for row in rows] # Значения pH
407
+
408
+ # Создаём график
409
+ plt.figure(figsize=(15, 6))
410
+ plt.plot(dates, ph_values, marker='o', linestyle='-', color='b')
411
+ plt.title(f'График pH за {week_number}-ю неделю')
412
+ plt.xlabel('Дата и день недели')
413
+ plt.ylabel('Значение pH')
414
+ plt.xticks(rotation=90)
415
+ plt.grid(True)
416
+ plt.gcf().subplots_adjust(bottom=0.4)
417
+
418
+ # Сохраняем график в буфер
419
+ buffer = io.BytesIO()
420
+ plt.savefig(buffer, format='png')
421
+ buffer.seek(0)
422
+
423
+ # Кодируем график в base64
424
+ plot_data = base64.b64encode(buffer.getvalue()).decode('utf-8')
425
+
426
+ # Возвращаем HTML с графиком и кнопками
427
+ return f'''
428
+ <html>
429
+ <body>
430
+ <h1>График pH за {week_number}-ю неделю</h1>
431
+ <button onclick="window.location.href='/plot_ph_week'">Выбрать другую неделю</button>
432
+ <button onclick="window.location.reload()">Обновить данные</button>
433
+ <br><br>
434
+ <img src="data:image/png;base64,{plot_data}" alt="График pH">
435
+ </body>
436
+ </html>
437
+ '''
438
+
439
+ except Exception as e:
440
+ return jsonify({'status': 'error', 'message': str(e)}), 500
441
+
442
+
443
+
444
+
445
+
446
+
447
+
448
+
449
+
450
+
451
+
452
+
453
+
454
+
455
+
456
+
457
+
458
+
459
+
460
  @app.route("/")
461
  def index():
462
  return flask.render_template('index.html')