-
Notifications
You must be signed in to change notification settings - Fork 1
/
flask_app.py
3343 lines (2566 loc) · 115 KB
/
flask_app.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
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Rencana Pembelajaran FGA Big Using Python Kelas A Fakultas Ilmu Komputer (Filkom),
# Universitas Brawijaya (UB) 2022 Instruktur:
# 1. Imam Cholissodin, S.Si., M.Kom. | email: [email protected] | Filkom UB
# 2. Nur Silviyah Rahmi, S.Si., M.Stat. | email: [email protected] | Mipa UB
# Link Free Buku Ajar tentang "Big Data Dengan Java/Scala/Python"
# dari saya (Pak Imam Cholissodin) : http://bit.ly/2FMLnfw
#
# Tgl 12 Juli 2022 - 3 September 2022
# Kolaborasi Instruktur Filkom x Mipa UB 2022
# Di Bawah Naungan Kominfo Pusat x Cisco Academy x lainnya dlm FGA
# Asisten Kelas A: Yusron Yogatama
from flask import Flask,render_template, Response, redirect,url_for,session,request,jsonify
from flask import json, make_response, render_template_string
import sqlite3
from flask_cors import CORS
from flask import send_file
from flask_qrcode import QRcode
from requests.packages.urllib3.exceptions import ProtocolError
from collections import OrderedDict
from operator import itemgetter
from textblob import TextBlob
from tweepy.streaming import StreamListener
import tweepy
import re
import string
import datetime
import joblib
from flask import send_file
from io import BytesIO
from flask_wtf.file import FileField
from wtforms import SubmitField
from flask_wtf import FlaskForm
# import json
import os
# # untuk CronJob
# from apscheduler.schedulers.background import BackgroundScheduler
from flask_crontab import Crontab
from flask_gtts import gtts
# from flask_app import static
# untuk sqlite admin
# from flask_sqlite_admin.core import sqliteAdminBlueprint, required_roles
app = Flask(__name__, static_folder='static')
crontab = Crontab(app)
gtts(app)
qrcode = QRcode(app)
# sqliteAdminBP = sqliteAdminBlueprint(
# dbPath = 'data.db',
# decorator = required_roles('admin', 'user')
# )
# app.register_blueprint(sqliteAdminBP, url_prefix='/sql')
# Ref:
# Big Thanks to,
# https://towardsdatascience.com/building-a-barcode-qr-code-reader-using-python-360e22dfb6e5
# https://github.com/piinalpin/absent-qrcode-python
# ==============================================================
#
# from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
# import os
project_dir = os.path.dirname(os.path.abspath(__file__))
database_file = "sqlite:///{}".format(os.path.join(project_dir, "static/qr_app/db/database.db"))
# app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = database_file
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = True
# DB kedua untuk qr_app :D
db_qr = SQLAlchemy(app)
migrate = Migrate(app, db_qr)
# Operasi untuk migrate
# flask db_qr init
# flask db_qr migrate
# flask db_qr upgrade
# from static.qr_app.controller.AppController import *
# from static.qr_app import qr_app
# from static.qr_app import app
# from static.qr_app.model.StudentModel import Student
# from static.qr_app.model.AttendanceModel import Attendance
from static.qr_app.model.StudentModel import Student
from static.qr_app.model.AttendanceModel import Attendance
# static/qr_app/module/Camera.py
# from static.qr_app.module.Camera import Scanner
from static.qr_app.module.Camera import Scanner
import pyqrcode
import uuid
# CORS(app)
CORS(app, resources=r'/api/*')
# CORS(app, resources=r'/*')
# CORS(app)
# app.debug = False
app.secret_key = 'fga^&&*(&^(filkom#BJH#G#VB#Big99nDatakPyICS_ap938255bnUB'
# app.secret_key = secrets.token_bytes(32) # used to cryptographically sign session cookies
# keterangan:
# "#" adalah untuk comment
# <br> adalah new line
# adalah spasi
# <!-- --> atau <!--- ---> adalah untuk comment
# FrameWeb_atas & FrameWeb_bawah untuk dekorasi web
# agar menjadi Web yang Responsif
FrameWeb_atas = """
{% extends "extends/base.html" %}
{% block title %}
<title>Web App MatKom Dgn Python</title>
{% endblock title %}
{{ self.title() }}
Home
{{ self.title() }}
<button onclick="window.location.href='/'" class="btn btn-outline btn-rounded btn-info">
<i class="ti-arrow-left m-l-5"></i>
<span>Back Home</span>
</button> Project 1
{{ self.title() }}
Project 1
{% block content %}
"""
A_a = FrameWeb_atas
FrameWeb_bawah = """
{% endblock content %}
"""
Z_z = FrameWeb_bawah
FrameWeb_atas_no_frame = """
{% extends "extends/base_no_frame.html" %}
{% block title %}
<title>Web App MatKom Dgn Python</title>
{% endblock title %}
{{ self.title() }}
Home
{{ self.title() }}
<button onclick="window.location.href='/'" class="btn btn-outline btn-rounded btn-info">
<i class="ti-arrow-left m-l-5"></i>
<span>Back Home</span>
</button> Project 1
{{ self.title() }}
Project 1
{% block content %}
"""
A_a_no_frame = FrameWeb_atas_no_frame
Z_z_no_frame = FrameWeb_bawah
@app.route('/tts')
def tts():
return render_template('gtts.html')
@app.route('/db/<aksi>')
def manipulate_tabel(aksi):
conn = connect_db()
db = conn.cursor()
# buat tabel data_cronjob
# Tipe Run => menit, jam, harian
# Date Pembuatan => Date
# Sintaks Cron Job => python /homw/../iot_api.py
# Keterangan
# Date Masa Berlaku
# Aksi => Edit, Hapus, Play, Extenf Date Berlaku
# db.execute("DROP TABLE IF EXISTS '" + DATABASE_TABLE + "'");
if aksi == 'c':
str_info = 'tabel berhasil dibuat :D'
# create tabel
db.execute("""
CREATE TABLE IF NOT EXISTS data_cronjob
(tipe_run TEXT, date_pembuatan DATETIME,
teks_call_sintaks TEXT,
keterangan TEXT,
date_masa_berlaku DATETIME)
""")
elif aksi== 'd':
str_info = 'tabel berhasil dihapus :D'
# hapus tabel
db.execute("""
DROP TABLE IF EXISTS data_cronjob
""")
conn.commit()
db.close()
conn.close()
return str_info
@app.route('/db/CloudAI_Air/<aksi>')
def manipulate_tabel_CloundAI_Air(aksi):
conn = connect_db()
db = conn.cursor()
if aksi == 'c':
# create tabel
db.execute("""
CREATE TABLE IF NOT EXISTS CloudAI_Air (
id INTEGER PRIMARY KEY AUTOINCREMENT,
suhu_dlm_celcius TEXT,
humidity_kelembaban_dlm_persen TEXT,
precipitation_curah_hujan_dlm_persen TEXT,
wind_angin_dlm_km_per_jam TEXT,
durasi_air_dlm_menit TEXT
)
""")
str_info = 'tabel berhasil dibuat :D'
elif aksi== 'd':
# hapus tabel
db.execute("""
DROP TABLE IF EXISTS CloudAI_Air
""")
str_info = 'tabel berhasil dihapus :D'
conn.commit()
db.close()
conn.close()
return str_info
@app.route('/db/CloudAI_Air_Rev/<aksi>')
def manipulate_tabel_CloundAI_Air_Rev(aksi):
conn = connect_db()
db = conn.cursor()
if aksi == 'c':
# create tabel
db.execute("""
CREATE TABLE IF NOT EXISTS CloudAI_Air_Rev (
id INTEGER PRIMARY KEY AUTOINCREMENT,
suhu_dlm_celcius TEXT,
humidity_kelembaban_dlm_persen TEXT,
precipitation_curah_hujan_dlm_persen TEXT,
wind_angin_dlm_km_per_jam TEXT,
durasi_air_dlm_menit TEXT
)
""")
str_info = 'tabel berhasil dibuat :D'
elif aksi== 'd':
# hapus tabel
db.execute("""
DROP TABLE IF EXISTS CloudAI_Air_Rev
""")
str_info = 'tabel berhasil dihapus :D'
conn.commit()
db.close()
conn.close()
return str_info
@app.route('/job', methods = ['POST', 'GET'])
def get_time():
from datetime import datetime
# from time import strftime
import pytz
# Date = str(datetime.today().astimezone(pytz.timezone('Asia/Jakarta')).strftime('%d-%m-%Y %H:%M:%S'))
Date = str(datetime.today().astimezone(pytz.timezone('Asia/Jakarta')).strftime('%Y-%m-%dT%H:%M'))
# time_req = request.args.get("html_time")
# format_time = datetime.strptime(time_req, "%Y-%m-%dT%H:%M")
# minute = format_time.minute
# hour = format_time.hour
# day = format_time.day
# month = format_time.month
# crontab.job(minute=minute, hour=hour, day=day, month=month)(exe_control)
# return render_template('myjob.html', time_req=time_req)
# return str(time_req)
if request.method == 'POST': # dioperasikan dihalaman sendiri tanpa send ke route, misal /post_add2
time_req = request.form['html_time'] # time data '2022-08-09' does not match format '%Y-%m-%dT%H:%M'
# format_time = datetime.strptime(time_req, "%Y-%m-%dT%H:%M")
# ValueError: time data '10-08-2022 08:32:26' does not match format '%Y-%m-%dT%H:%M'
format_time = datetime.strptime(Date, "%Y-%m-%dT%H:%M")
minute = format_time.minute
hour = format_time.hour
day = format_time.day
month = format_time.month
# crontab.job(minute=minute, hour=hour, day=day, month=month)(exe_control)
crontab.job(minute="1")(exe_control)
# return str(time_req)
return render_template('mycronjob.html', time_req=time_req)
else: # untuk yang 'GET' data awal untuk di send ke /post_add3
return render_template('mycronjob.html')
# - without decorator -
def exe_control():
# return 'run job'
import requests
from datetime import datetime
import pytz
Date = str(datetime.today().astimezone(pytz.timezone('Asia/Jakarta')).strftime('%d-%m-%Y %H:%M:%S'))
def F2C(f_in):
return (f_in - 32)* 5/9
def Kelvin2C(k_in):
return (k_in-273.15)
# simpan ke db
conn = connect_db()
db = conn.cursor()
db.execute("""CREATE TABLE IF NOT EXISTS data_suhu_dll (date DATETIME, kota TEXT, suhu_dlm_celcius TEXT, precipitation_curah_hujan_dlm_persen TEXT, humidity_kelembaban_dlm_persen TEXT, wind_angin_dlm_km_per_jam TEXT) """)
list_kota = ['Jakarta','Los Angeles','Chicago','New York City','Toronto','São Paulo', \
'Lagos', 'London', 'Johannesburg', 'Kairo', 'Paris', 'Zurich', 'Istanbul', 'Moskwa', 'Dubai', \
'Mumbai','Hong Kong','Shanghai','Singapura','Tokyo','Sydney']
for nama_kota in list_kota:
# each_list_link='http://api.weatherapi.com/v1/current.json?key=re2181c95fd6d746e9a1331323220104&q='+nama_kota
each_list_link='http://api.weatherapi.com/v1/current.json?key=2181c95fd6d746e9a1331323220104&q='+nama_kota
resp=requests.get(each_list_link)
# print(nama_kota)
#http_respone 200 means OK status
if resp.status_code==200:
resp=resp.json()
suhu = resp['current']['temp_c']
curah_hujan = resp['current']['precip_mm']
lembab = resp['current']['humidity']
angin = resp['current']['wind_mph']
else:
# print("Error")
suhu = '-'
curah_hujan = '-'
lembab = '-'
angin = '-'
print(nama_kota, 'dengan suhu = ', round(float(suhu),2),'°C', end='\n')
db.execute("""INSERT INTO data_suhu_dll (date, kota, suhu_dlm_celcius, precipitation_curah_hujan_dlm_persen, humidity_kelembaban_dlm_persen, wind_angin_dlm_km_per_jam) VALUES (?,?,?,?,?,?) """,(Date,nama_kota,suhu,curah_hujan,lembab,angin))
conn.commit()
db.close()
conn.close()
@app.route('/job2', methods = ['POST', 'GET'])
def get_job2():
from datetime import datetime
# from time import strftime
import pytz
# Date = str(datetime.today().astimezone(pytz.timezone('Asia/Jakarta')).strftime('%d-%m-%Y %H:%M:%S'))
Date = str(datetime.today().astimezone(pytz.timezone('Asia/Jakarta')).strftime('%Y-%m-%dT%H:%M'))
# time_req = request.args.get("html_time")
# format_time = datetime.strptime(time_req, "%Y-%m-%dT%H:%M")
# minute = format_time.minute
# hour = format_time.hour
# day = format_time.day
# month = format_time.month
# crontab.job(minute=minute, hour=hour, day=day, month=month)(exe_control)
# return render_template('myjob.html', time_req=time_req)
# return str(time_req)
if request.method == 'POST': # dioperasikan dihalaman sendiri tanpa send ke route, misal /post_add2
time_req = request.form['html_time'] # time data '2022-08-09' does not match format '%Y-%m-%dT%H:%M'
# format_time = datetime.strptime(time_req, "%Y-%m-%dT%H:%M")
# ValueError: time data '10-08-2022 08:32:26' does not match format '%Y-%m-%dT%H:%M'
format_time = datetime.strptime(Date, "%Y-%m-%dT%H:%M")
minute = format_time.minute
hour = format_time.hour
day = format_time.day
month = format_time.month
# crontab.job(minute=minute, hour=hour, day=day, month=month)(exe_control)
crontab.job(minute="1")(exe_control)
# return str(time_req)
return render_template('mycronjob2.html', time_req=time_req)
else: # untuk yang 'GET' data awal untuk di send ke /post_add3
return render_template('mycronjob2.html')
@app.route('/user')
def data_user():
try:
conn = connect_db()
db = conn.cursor()
rs = db.execute("SELECT * FROM user order by id")
userslist = rs.fetchall()
return render_template('data_user.html',userslist=userslist)
except Exception as e:
print(e)
finally:
db.close()
conn.close()
@app.route("/update_user",methods=["POST","GET"])
def update_user():
try:
conn = connect_db()
db = conn.cursor()
if request.method == 'POST':
field = request.form['field']
value = request.form['value']
editid = request.form['id']
if field == 'mail':
db.execute("""UPDATE user SET Mail=? WHERE id=?""",(value,editid))
if field == 'name':
db.execute("""UPDATE user SET Name=? WHERE id=?""",(value,editid))
if field == 'pwd':
db.execute("""UPDATE user SET Password=? WHERE id=?""",(value,editid))
if field == 'level':
db.execute("""UPDATE user SET Level=? WHERE id=?""",(value,editid))
conn.commit()
success = 1
return jsonify(success)
except Exception as e:
print(e)
finally:
db.close()
conn.close()
# # Inisialisasi variabel scheduler untuk CronJob
# sched = BackgroundScheduler(daemon = True)
# sched.start()
# # Mendefinisikan suatu fungsi cronjob untuk run todo dalam Flask app
# @sched.scheduled_job(trigger = 'cron', minute = '*')
# def print_hello():
# print('Hello world!')
# # Defining a single API endpoint
# @app.route('/test')
# def test_func():
# js = json.dumps({'Test': 'Successful!'})
# return Response(json.dumps(js), status = 200, mimetype = 'application/json')
############ Flask routes general: ############
# ================ awal - dasar ke-2 ===============
#
# buat input dari url, untuk penjumlahan misal 2 bilangan
@app.route('/add/<a>/<b>')
def add_ab(a,b):
c = int(a) + float(b)
return 'a + b = ' + str(c)
# return 'a + b = %s' % c
# https://bigdatafga.pythonanywhere.com/add/1/2.5
# hasil => a + b = 3.5
#
# buatlah halaman post sekaligus get
# nilai a dan b, lalu ditambahkan
# dengan return kode html dalam flask python Web App
@app.route('/post_add2', methods=["POST", "GET"])
def inputkan_ab():
# membuat penjumlahan 2 bilangan
if request.method == 'POST': # dioperasikan dihalaman sendiri tanpa send ke route, misal /post_add2
a_in = float(request.form['a'])
b_in = float(request.form['b'])
c = a_in + b_in
return '''
<html>
<head>
</head>
<body>
<form method="post">
<input type="text" name="a" value="%s" />
<input type="text" name="b" value="%s" />
<input type="submit" value="Hitung a + b"/>
</form>
<h2>Hasil a + b = %s + %s = %s </h2>
</body>
</html>
''' % (a_in, b_in, a_in, b_in, c)
else: # untuk yang 'GET' data awal untuk di send ke /post_add2
return '''
<html>
<head>
</head>
<body>
<form action="/post_add2" method="post">
Masukkan nilai a = <input type="text" name="a" value="" />
<br>
Masukkan nilai b = <input type="text" name="b" value="" />
<input type="submit" value="Hitung a + b"/>
</form>
</body>
</html>
'''
#
# buatlah halaman post sekaligus get
# nilai a dan b, lalu ditambahkan
# dengan return file "form_add3.html" dalam folder "mysite/templates", flask python Web App
@app.route('/post_add3', methods=["POST", "GET"])
def inputkan_ab3():
# membuat penjumlahan 2 bilangan
if request.method == 'POST': # dioperasikan dihalaman sendiri tanpa send ke route, misal /post_add2
a_in = float(request.form['a'])
b_in = float(request.form['b'])
c = a_in + b_in
return render_template('form_add3.html', a_save = a_in, b_save = b_in, c_save = c)
else: # untuk yang 'GET' data awal untuk di send ke /post_add3
return render_template('form_add3.html')
# ================================================================================
# Untuk mengakselerasi pengerjaan sebagian FP ke-1 dan FP ke-2, berikut:
#
# Contoh koding dasar operasi CRUD pada tabel CloudAI_Air,
# mulai dari "def dasar2_create_database():" sampai sebelum "# ================ akhir - dasar ke-2 ==============="
#
#
# Contoh koding dasar Run isi kode iot_api.py,
# @app.route('/dasar2_add2')
#
# Jangan lupa menambahkan "from flask import render_template_string" pada bagian atas flask_app.py
#
# ==============================================================
#
# membuat render_template_string sebagai pengganti render_template
# agar semua kodenya hanya dalam 1 file, sehingga lebih mudah untuk membuat dan run kodingnya
#
# Ref: https://stackoverflow.com/questions/67429333/flask-how-to-update-information-on-sqlite-based-on-button-input
# Remodified by Imam Cholissodin
#
# untuk Pengmas 2022 | membuat tabel CloudAI_Air untuk Penentuan Durasi Pengairan / Penyiraman Tanaman
# dengan menggunakan KNN & Fuzzy Mamdani dalam Ekosistem Cloud-AI
#
def dasar2_create_database():
conn = connect_db()
cur = conn.cursor()
cur.execute("""
CREATE TABLE IF NOT EXISTS CloudAI_Air (
id INTEGER PRIMARY KEY AUTOINCREMENT,
suhu_dlm_celcius TEXT,
humidity_kelembaban_dlm_persen TEXT,
precipitation_curah_hujan_dlm_persen TEXT,
wind_angin_dlm_km_per_jam TEXT,
durasi_air_dlm_menit TEXT
)
""")
conn.commit()
conn.close()
def dasar2_generate_data():
"""Generate sintesis atau dummy data untuk percontohan."""
conn = connect_db()
cur = conn.cursor()
# start - insert where tabel CloudAI_Air masih kosong
# cur.execute('SELECT * FROM CloudAI_Air WHERE (Col1=? AND Col2=? AND Col3=?)', ('a', 'b', 'c'))
cur.execute('SELECT * FROM CloudAI_Air')
entry = cur.fetchone()
# rs = db.execute("SELECT * FROM user order by id")
# datalist = rs.fetchall()
# if entry is None:
# for i in range(1, 11):
# cur.execute("""INSERT INTO CloudAI_Air (suhu_dlm_celcius, humidity_kelembaban_dlm_persen, precipitation_curah_hujan_dlm_persen, wind_angin_dlm_km_per_jam, durasi_air_dlm_menit) VALUES (?, ?, ?, ?, ?)""",
# (f"Suhu {i}", f"Kelembaban {i}", f"Hujan {i}", f"Angin {i}", f"Durasi {i}"))
if entry is None:
import numpy as np
import pandas as pd
import os.path
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
# Misal skema dataset-nya seperti berikut: => Silahkan dimodifikasi sesuai case Anda
kolomFitur_X_plus_Target_Y = ['Suhu (X1)','Kelembaban (X2)', 'Curah Hujan (X3)','Angin (X4)','Durasi Air Dlm Menit (Y)']
# set bykData = 3*np.power(10,7)
bykData = 10
bykFitur = len(kolomFitur_X_plus_Target_Y)-1
# Interval atau Variasi nilai fitur
nilaiFitur_Suhu = [17,35]
nilaiFitur_Kelembaban = [70,90]
nilaiFitur_Curah_Hujan = [2,95]
nilaiFitur_Angin = [0,15]
labelTargetY = [0.0,90.0]
# generate isi dataset
content_dataGenerate = np.array([np.arange(bykData)]*(bykFitur+1)).T
df_gen = pd.DataFrame(content_dataGenerate, columns=kolomFitur_X_plus_Target_Y)
df_gen ['Suhu (X1)'] = np.random.randint(nilaiFitur_Suhu[0], nilaiFitur_Suhu[1], df_gen.shape[0])
df_gen ['Kelembaban (X2)'] = np.random.randint(nilaiFitur_Kelembaban[0], nilaiFitur_Kelembaban[1], df_gen.shape[0])
df_gen ['Curah Hujan (X3)'] = np.random.randint(nilaiFitur_Curah_Hujan[0], nilaiFitur_Curah_Hujan[1], df_gen.shape[0])
df_gen ['Angin (X4)'] = np.random.randint(nilaiFitur_Angin[0], nilaiFitur_Angin[1], df_gen.shape[0])
df_gen ['Durasi Air Dlm Menit (Y)'] = np.round(np.random.uniform(labelTargetY[0], labelTargetY[1], df_gen.shape[0]),2)
# save dataframe generate ke *.csv
import os
# print(os.path.expanduser("~"))
userhome = os.path.expanduser("~").split("/")[-1]
# print(userhome)
# file_name_data_generate = '/home/bigdatafga/mysite/static/data_contoh/Data_CloudAI_Air.csv'
# df_gen.to_csv(file_name_data_generate, encoding='utf-8', index=False)
path = "/home/"+userhome+"/mysite/static/data_contoh"
if not os.path.exists(path):
os.makedirs(path)
# file_name_data_generate = 'static/data_contoh/Data_CloudAI_Air.csv'
# df_gen.to_csv(file_name_data_generate, encoding='utf-8', index=False)
url_file_name_data_generate = os.path.join(BASE_DIR, "static/data_contoh/Data_CloudAI_Air.csv")
df_gen.to_csv(url_file_name_data_generate, encoding='utf-8', index=False)
# read file *.csv dan tampilkan
# data_generate = pd.read_csv(file_name_data_generate)
url = os.path.join(BASE_DIR, "static/data_contoh/Data_CloudAI_Air.csv")
# Importing the dataset => ganti sesuai dengan case yg anda usulkan
dataset = pd.read_csv(url)
# X = dataset.iloc[:, :-1].values
# y = dataset.iloc[:, 1].values
def pushCSVdatasetToDB(x1,x2,x3,x4,y):
#inserting values inside the created table
# db = sqlite3.connect("data.db")
# conn = connect_db()
# cur = conn.cursor()
cmd = "INSERT INTO CloudAI_Air(suhu_dlm_celcius, humidity_kelembaban_dlm_persen, precipitation_curah_hujan_dlm_persen, wind_angin_dlm_km_per_jam, durasi_air_dlm_menit) VALUES('{}','{}','{}','{}','{}')".format(x1,x2,x3,x4,y)
cur.execute(cmd)
conn.commit()
# CSV_to_SQLite3 dari file dataset
for i in range(0,len(dataset)):
pushCSVdatasetToDB(dataset.iloc[i][0],dataset.iloc[i][1],dataset.iloc[i][2],dataset.iloc[i][3],dataset.iloc[i][4])
# for i in range(1, 11):
# cur.execute("""INSERT INTO CloudAI_Air (suhu_dlm_celcius, humidity_kelembaban_dlm_persen, precipitation_curah_hujan_dlm_persen, wind_angin_dlm_km_per_jam) VALUES (?, ?, ?, ?)""",
# (f"Type {i}", f"Receipt {i}", f"Amount {i}", f"Description {i}"))
else:
ket_hasil = 'Tidak dilakukan Insert, karena Tabel tidak kosong'
print(ket_hasil)
# end - insert where tabel CloudAI_Air masih kosong
# # Misal skema dataset-nya seperti berikut: => Silahkan dimodifikasi sesuai case Anda
# kolomFitur_X_plus_Target_Y = ['Jenis Aktifitas (X1)','Pola Hidup (X2)', 'Olah Raga (08.00-09.30) dalam menit (X3)','Target Rating Imun (Y)']
# # Interval atau Variasi nilai fitur
# nilaiFitur_Jenis_Aktifitas = ['Ringan','Sedang']
# nilaiFitur_Pola_Hidup = ['Cukup Sehat','Sehat','Sangat Sehat']
# nilaiFitur_Waktu_Olah_Raga = [15,45]
# labelTargetY = [1.0,5.0]
# # set bykData = 3*np.power(10,7)
# bykData = 10
# bykFitur = len(kolomFitur_X_plus_Target_Y)-1
# print('Banyak Data = ', bykData)
# print('Banyak Fitur = ', bykFitur)
# # generate isi dataset
# content_dataGenerate = np.array([np.arange(bykData)]*(bykFitur+1)).T
# df_gen = pd.DataFrame(content_dataGenerate, columns=kolomFitur_X_plus_Target_Y)
# # set secara random nilai Fitur untuk generate data
# df_gen ['Jenis Aktifitas (X1)'] = np.random.choice(nilaiFitur_Jenis_Aktifitas, df_gen.shape[0])
# df_gen ['Pola Hidup (X2)'] = np.random.choice(nilaiFitur_Pola_Hidup, df_gen.shape[0])
# df_gen ['Olah Raga (08.00-09.30) dalam menit (X3)'] = np.random.randint(nilaiFitur_Waktu_Olah_Raga[0], nilaiFitur_Waktu_Olah_Raga[1], df_gen.shape[0])
# df_gen ['Target Rating Imun (Y)'] = np.random.uniform(labelTargetY[0], labelTargetY[1], df_gen.shape[0])
# # save dataframe generate ke *.csv
# file_name_data_generate = 'Data_Generate_Reg.csv'
# df_gen.to_csv(file_name_data_generate, encoding='utf-8', index=False)
# # read file *.csv dan tampilkan
# data_generate = pd.read_csv(file_name_data_generate)
# # Menampilkan data
# print('\nMenampilkan hasil generate dataset:')
# display(data_generate)
conn.commit()
cur.close()
conn.close()
@app.route('/dasar2_crud')
def dasar2_index():
return '<a href="/dasar2_list">Demo Menampilkan List dari Tabel + Support => Create, Read, Update, Delete (CRUD)</a>'
@app.route('/dasar2_list')
def dasar2_list():
# buat tabel dan generate data dummy
dasar2_create_database()
dasar2_generate_data()
conn = connect_db()
cur = conn.cursor()
cur.execute("SELECT * FROM CloudAI_Air")
rows = cur.fetchall()
conn.close()
#return render_template("list.html", rows=rows)
return render_template_string(template_list, rows=rows)
@app.route('/dasar2_edit/<int:number>', methods=['GET', 'POST'])
def dasar2_edit(number):
conn = connect_db()
cur = conn.cursor()
if request.method == 'POST':
item_id = number
item_suhu = request.form['suhu']
item_kelembaban = request.form['kelembaban']
item_hujan = request.form['hujan']
item_angin = request.form['angin']
item_durasi = request.form['durasi']
# suhu_dlm_celcius, humidity_kelembaban_dlm_persen, precipitation_curah_hujan_dlm_persen, wind_angin_dlm_km_per_jam, durasi_air_dlm_menit
cur.execute("UPDATE CloudAI_Air SET suhu_dlm_celcius = ?, humidity_kelembaban_dlm_persen = ?, precipitation_curah_hujan_dlm_persen = ?, wind_angin_dlm_km_per_jam = ?, durasi_air_dlm_menit = ? WHERE id = ?",
(item_suhu, item_kelembaban, item_hujan, item_angin, item_durasi, item_id))
conn.commit()
return redirect('/dasar2_list')
cur.execute("SELECT * FROM CloudAI_Air WHERE id = ?", (number,))
item = cur.fetchone()
conn.close()
#return render_template("edit.html", item=item)
return render_template_string(template_edit, item=item)
@app.route('/dasar2_delete/<int:number>')
def dasar2_delete(number):
conn = connect_db()
cur = conn.cursor()
cur.execute("DELETE FROM CloudAI_Air WHERE id = ?", (number,))
conn.commit()
conn.close()
return redirect('/dasar2_list')
@app.route('/dasar2_add', methods=['GET', 'POST'])
def dasar2_add():
conn = connect_db()
cur = conn.cursor()
if request.method == 'POST':
# item_id = number
item_suhu = request.form['suhu']
item_kelembaban = request.form['kelembaban']
item_hujan = request.form['hujan']
item_angin = request.form['angin']
item_durasi = request.form['durasi']
cur.execute("""INSERT INTO CloudAI_Air (suhu_dlm_celcius, humidity_kelembaban_dlm_persen, precipitation_curah_hujan_dlm_persen, wind_angin_dlm_km_per_jam, durasi_air_dlm_menit) VALUES (?, ?, ?, ?, ?)""",
(item_suhu, item_kelembaban, item_hujan, item_angin, item_durasi))
conn.commit()
return redirect('/dasar2_list')
#return render_template("add.html", item=item)
return render_template_string(template_add)
@app.route('/dasar2_add2')
def dasar2_add2():
conn = connect_db()
cur = conn.cursor()
# get data dari iot API
import requests
# from datetime import datetime
# import pytz
# Date = str(datetime.today().astimezone(pytz.timezone('Asia/Jakarta')).strftime('%d-%m-%Y %H:%M:%S'))
def F2C(f_in):
return (f_in - 32)* 5/9
def Kelvin2C(k_in):
return (k_in-273.15)
# list_kota = ['Jakarta','Los Angeles','Chicago','New York City','Toronto','São Paulo', \
# 'Lagos', 'London', 'Johannesburg', 'Kairo', 'Paris', 'Zurich', 'Istanbul', 'Moskwa', 'Dubai', \
# 'Mumbai','Hong Kong','Shanghai','Singapura','Tokyo','Sydney']
list_kota = ['Malang']
for nama_kota in list_kota:
# each_list_link='http://api.weatherapi.com/v1/current.json?key=re2181c95fd6d746e9a1331323220104&q='+nama_kota
each_list_link='http://api.weatherapi.com/v1/current.json?key=2181c95fd6d746e9a1331323220104&q='+nama_kota
resp=requests.get(each_list_link)
# print(nama_kota)
#http_respone 200 means OK status
if resp.status_code==200:
resp=resp.json()
suhu = resp['current']['temp_c']
curah_hujan = resp['current']['precip_mm']
lembab = resp['current']['humidity']
angin = resp['current']['wind_mph']
else:
# print("Error")
suhu = '-'
curah_hujan = '-'
lembab = '-'
angin = '-'
# print(nama_kota, 'dengan suhu = ', round(float(suhu),2),'°C', end='\n')
cur.execute("""INSERT INTO CloudAI_Air (suhu_dlm_celcius, humidity_kelembaban_dlm_persen, precipitation_curah_hujan_dlm_persen, wind_angin_dlm_km_per_jam) VALUES (?, ?, ?, ?)""",
(suhu, lembab, curah_hujan, angin))
conn.commit()
cur.close()
conn.close()
return redirect('/dasar2_list')
template_list = """
<h2>Menampilkan Data CloudAI Air + Support Create, Read, Update, delete (CRUD)</h2>
<a href="{{ url_for( "dasar2_add" ) }}">Tambah Data</a> |
<a href="{{ url_for( "dasar2_add2" ) }}">Tambah Data dari iot_api (tanpa nilai Durasi Waktu)</a>
{% if rows %}
<table border="1">
<thead>
<td>No</td>
<td>Suhu (°C)</td>
<td>Kelembaban (%)</td>
<td>Curah Hujan (%)</td>
<td>Kecepatan Angin (Km/Jam)</td>
<td>Durasi Waktu Pengairan / Penyiraman (Menit)</td>
</thead>
{% for row in rows %}
<tr>
<td>{{ loop.index }}</td>
<td>{{row[1]}}</td>
<td>{{row[2]}}</td>
<td>{{row[3]}}</td>
<td>{{row[4]}}</td>
<td>{{row[5]}}</td>
<td>
<a href="{{ url_for( "dasar2_edit", number=row[0] ) }}">Edit</a> |
<a href="{{ url_for( "dasar2_delete", number=row[0] ) }}">Hapus</a>
</td>
</tr>
{% endfor %}
</table>
{% else %}
Empty</br>
{% endif %}
"""
template_add = """
<h1>Tambah Data CloudAI Air</h1>
<form method="POST" action="{{ url_for( "dasar2_add" ) }}">
Suhu: <input name="suhu" value=""/></br>
Kelembaban: <input name="kelembaban" value=""/></br>
Curah Hujan: <input name="hujan" value=""/></br>
Kecepatan Angin: <input name="angin" value=""/></br>
Durasi Waktu Pengairan / Penyiraman: <input name="durasi" value=""/></br>
<button>Simpan Data</button></br>
</form>
"""
template_edit = """
<h1>Edit Data CloudAI Air</h1>
<form method="POST" action="{{ url_for( "dasar2_edit", number=item[0] ) }}">
Suhu: <input name="suhu" value="{{item[1]}}"/></br>
Kelembaban: <input name="kelembaban" value="{{item[2]}}"/></br>
Curah Hujan: <input name="hujan" value="{{item[3]}}"/></br>
Kecepatan Angin: <input name="angin" value="{{item[4]}}"/></br>
Durasi Waktu Pengairan / Penyiraman: <input name="durasi" value="{{item[5]}}"/></br>
<button>Simpan Update Data</button></br>
</form>
"""
# ================ akhir - dasar ke-2 ===============
# ================ awal - dasar ke-1 ===============
# #
# @app.route('/')
# def hello_world():
# return 'Hello Big Data Using Python from Flask - FGA x Cisco Academy 2022 x Filkom UB!'
# @app.route('/add')
# def add():
# # membuat penjumlahan 2 bilangan
# a = 10
# b = 90
# c = a + b
# return str(c)
# # buatlah halaman perkalian
# # antara a*b
# @app.route('/kali')
# def kali():
# # membuat perkalian 2 bilangan
# a = 10
# b = 90
# c = a * b
# return str(c)
# # buatlah tampilan indeks looping 1..10
# @app.route('/loop')
# def loop():
# c = ''
# for i in range(10): # i = 0,1,..,9
# c +=str(i+1) + ' '
# return str(c)
# # buatlah tampilan indeks looping 1..10 dengan new line (<br> dari tag html)
# @app.route('/loop_new_line')
# def loop_new_line():
# c = ''
# for i in range(10): # i = 0,1,..,9
# c +=str(i+1) + '<br>'
# return str(c)