#python #html #flask
#python #HTML #flask
Вопрос:
Я создаю смоделированный центр по лечению covid, в котором я использую python flask, html и т. Д. В этом у меня будет таблица, показывающая некоторые значения на главном экране, а затем чат-бот и страница часто задаваемых вопросов. Я создал чат-бота и часто задаваемые вопросы, но у меня возникают проблемы с динамическим обновлением моих HTML-данных. (Данные создаются на серверной части с использованием случайных и потоковых модулей). Вот мой main.py:
import flask
import time
import mysql.connector
app = flask.Flask(__name__)
app.static_folder = 'static'
#I am storing the values in a database
f = mysql.connector.connect(host = "localhost", user = "root", passwd = "")
mycur = f.cursor()
mycur.execute("use one_stop_healthcare;")
mycur.execute("select * from ccinfo;")
lines = mycur.fetchall()
@app.route("/")
def print_val():
global lines
return flask.render_template("index.html", lines = lines)
app.run()
Вот мой index.html который хранится в каталоге шаблонов:
<html>
<style>
table, th, td {
border: 1px solid black;
border-collapse: collapse;
}
th, td {
padding: 15px;
text-align: center;
}
.button {
border: none;
color: white;
padding: 15px 32px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
margin: 4px 2px;
cursor: pointer;
}
.button1 {background-color: #4CAF50;} /* Green */
.button2 {background-color: #008CBA;} /* Blue */
</style>
<head>
<title> One Stop Healthcare </title>
</head>
<body>
<h2> The data for all the COVID care centers </h1>
<table style="width:100%">
<tr>
<th> ID </th>
<th> NAME </th>
<th> LOCATION </th>
<th> BEDS </th>
<th> DISCARGED </th>
<th> ACTIVE </th>
<th> DEAD </th>
<th> DOCTORS </th>
<th> MONEY </th>
<th> PPE_KITS </th>
<th> BLANKETS </th>
<th> MASKS </th>
<th> SANITIZER </th>
</tr>
{% for line in lines %}
<tr>
{% for i in line %}
<td>{{ i }}</td>
{% endfor %}
</tr>
{% endfor %}
</table>
<button type="button"><a href="http://127.0.0.1:5000/chatbot"> Chatbot </a></button>
<button type="button"><a href="http://127.0.0.1:5000/faq"> FAQs </a></button>
</body>
</html>
Вот моя база данных вставка значений в базу данных (вам просто нужно запустить это один раз, чтобы вставить значения и создать базу данных). У него нет проблемы
import mysql.connector
f = mysql.connector.connect(host = "localhost", user = "root", passwd = "")
mycur = f.cursor()
mycur.execute("create database One_Stop_Healthcare;")
f.commit()
mycur.execute("use One_Stop_Healthcare;")
print("database created")
que = "create table ccinfo(ID INTEGER NOT NULL primary key, NAME varchar(20), LOCATION varchar(20), BEDS integer, DISCHARGED integer, ACTIVE integer, DEAD integer, DOCTORS integer, MONEY integer, PPE_KITS integer, BLANKETS integer, MASKS integer, SANITIZER integer);"
mycur.execute(que)
print("table created")
mycur.execute("insert into ccinfo(ID, NAME, LOCATION, BEDS, DISCHARGED, ACTIVE, DEAD, DOCTORS, MONEY , PPE_KITS, BLANKETS, MASKS, SANITIZER)values(1, 'Ward-1', 'KRM', 500, 100, 300, 50, 25, 100000, 20, 100, 100, 70);")
mycur.execute("insert into ccinfo(ID, NAME, LOCATION, BEDS, DISCHARGED, ACTIVE, DEAD, DOCTORS, MONEY , PPE_KITS, BLANKETS, MASKS, SANITIZER)values(2, 'Ward-2', 'KRM', 1000, 290, 700, 150, 78, 250000, 40, 600, 300, 130);")
mycur.execute("insert into ccinfo(ID, NAME, LOCATION, BEDS, DISCHARGED, ACTIVE, DEAD, DOCTORS, MONEY , PPE_KITS, BLANKETS, MASKS, SANITIZER)values(3, 'Ward-3', 'KRM', 50, 10, 30, 5, 5, 80000, 7, 50, 30, 40);")
mycur.execute("insert into ccinfo(ID, NAME, LOCATION, BEDS, DISCHARGED, ACTIVE, DEAD, DOCTORS, MONEY , PPE_KITS, BLANKETS, MASKS, SANITIZER)values(4, 'Ward-4', 'HSR', 1500, 400, 1300, 250, 100, 400000, 70, 500, 300, 150);")
mycur.execute("insert into ccinfo(ID, NAME, LOCATION, BEDS, DISCHARGED, ACTIVE, DEAD, DOCTORS, MONEY , PPE_KITS, BLANKETS, MASKS, SANITIZER)values(5, 'Ward-5', 'Bellandur', 500, 50, 100, 25, 40, 90000, 30, 100, 90, 90);")
f.commit()
И, наконец, здесь я моделирую данные
import threading
import time
import random
import mysql.connector
TC=5 #Total thread count
count = 0
thr = [0 for i in range(TC)]
db_data = [[] for i in range(TC 1)]
def print_time():
global count
global db_data
count = count 1
mylocal = count
'''
1: id
2: location
3: beds
4: discharged
5: active
6: dead
7: doctors
8: money
9: ppe kits
10: blankets
11: masks
12: sanitizer
'''
i = 0
while i < 5:
i = i 1
x = random.randint(1,350)
#print(x)
if x == 1:
db_data[mylocal][3] = db_data[mylocal][3] 50
st = "UPDATE ccinfo SET BEDS = {} where ID = {}".format(db_data[mylocal][3], mylocal)
elif x == 2 and db_data[mylocal][3] > 50:
db_data[mylocal][3] = db_data[mylocal][3] - 50
st = "UPDATE ccinfo SET BEDS = {} where ID = {}".format(db_data[mylocal][3], mylocal)
elif x == 3:
db_data[mylocal][7] = db_data[mylocal][7] 1
st = "UPDATE ccinfo SET DOCTORS = {} where ID = {}".format(db_data[mylocal][7], mylocal)
elif x == 4 and db_data[mylocal][7] > 7:
db_data[mylocal][7] = db_data[mylocal][7] - 1
st = "UPDATE ccinfo SET DOCTORS = {} where ID = {}".format(db_data[mylocal][7], mylocal)
elif x > 4 and x < 101:
db_data[mylocal][4] = db_data[mylocal][4] 1
st = "UPDATE ccinfo SET DISCHARGED = {} where ID = {}".format(db_data[mylocal][4], mylocal)
elif x > 100 and x < 201:
db_data[mylocal][5] = db_data[mylocal][5] 1
st = "UPDATE ccinfo SET ACTIVE = {} where ID = {}".format(db_data[mylocal][5], mylocal)
elif x > 200 and x < 211:
db_data[mylocal][6] = db_data[mylocal][6] 1
st = "UPDATE ccinfo SET DEAD = {} where ID = {}".format(db_data[mylocal][6], mylocal)
elif x > 210 and x < 221:
db_data[mylocal][8] = db_data[mylocal][8] 10000
st = "UPDATE ccinfo SET MONEY = {} where ID = {}".format(db_data[mylocal][8], mylocal)
elif x > 220 and x < 231 and db_data[mylocal][8] > 20000:
db_data[mylocal][8] = db_data[mylocal][8] - 10000
st = "UPDATE ccinfo SET MONEY = {} where ID = {}".format(db_data[mylocal][8], mylocal)
elif x > 230 and x < 241:
db_data[mylocal][9] = db_data[mylocal][9] 5
st = "UPDATE ccinfo SET PPE_KITS = {} where ID = {}".format(db_data[mylocal][9], mylocal)
elif x > 240 and x < 251 and db_data[mylocal][9] > 0:
db_data[mylocal][9] = db_data[mylocal][9] - 5
st = "UPDATE ccinfo SET PPE_KITS = {} where ID = {}".format(db_data[mylocal][9], mylocal)
elif x > 250 and x < 261:
db_data[mylocal][10] = db_data[mylocal][10] 5
st = "UPDATE ccinfo SET BLANKETS = {} where ID = {}".format(db_data[mylocal][10], mylocal)
elif x > 260 and x < 271 and db_data[mylocal][10] > 0:
db_data[mylocal][10] = db_data[mylocal][10] - 5
st = "UPDATE ccinfo SET BLANKETS = {} where ID = {}".format(db_data[mylocal][10], mylocal)
elif x > 270 and x < 281:
db_data[mylocal][11] = db_data[mylocal][11] 5
st = "UPDATE ccinfo SET MASKS = {} where ID = {}".format(db_data[mylocal][11], mylocal)
elif x > 280 and x < 291 and db_data[mylocal][11] > 0:
db_data[mylocal][11] = db_data[mylocal][11] - 5
st = "UPDATE ccinfo SET MASKS = {} where ID = {}".format(db_data[mylocal][11], mylocal)
elif x > 290 and x < 301:
db_data[mylocal][12] = db_data[mylocal][12] 5
st = "UPDATE ccinfo SET SANITIZER = {} where ID = {}".format(db_data[mylocal][12], mylocal)
elif x > 300 and x < 311 and db_data[mylocal][12] > 0:
db_data[mylocal][12] = db_data[mylocal][12] - 5
st = "UPDATE ccinfo SET SANITIZER = {} where ID = {}".format(db_data[mylocal][12], mylocal)
print(st)
mycur.execute(st)
f.commit()
time.sleep(10)
if __name__ == "__main__":
f = mysql.connector.connect(host = "localhost", user = "root", passwd = "")
mycur = f.cursor()
mycur.execute("use one_stop_healthcare;")
mycur.execute("select * from ccinfo;")
dat = mycur.fetchall()
for val in dat:
i = val[0]
db_data[i] = list(val)
print(db_data)
for i in range(TC):
thr[i] = threading.Thread(target=print_time)
thr[i].start()
time.sleep(1)
for i in range(TC):
thr[i].join()
```
Ответ №1:
Просто добавьте это <meta http-equiv="refresh" content="5">
в свой HTML
head
Комментарии:
1. Привет, спасибо за совет, но я попробовал это, и он обновлял страницу каждые 5 секунд, но данные оставались прежними. Для проверки я проверил базу данных, и значения там изменились.
2. @PranshuGoel Попробуйте добавить вызов функции, которая извлекает данные из HTML. Что-то вроде этого
<body> <p>{{ myfunction() }}</p> </body>
3. Где именно находится функция, которая извлекает данные из внешней базы данных?
4. Привет, в моем main.py , когда я render_template(«index.html «, lines=lines) это когда я отправляю строки (которые находятся в формате списка в списке), а затем в html я использую jinja2 для добавления данных в таблицу. В противном случае в моем main.py я получаю данные из mycur.execute(«выберите * из ccinfo;»)
5. @PranshuGoel Я не понимаю, откуда именно вы извлекаете данные «from». Какая база данных обновляется, а ваша нет? В любом случае, если это
print_time
, например, для извлечения данных .. просто добавьте для этого вызов в шаблон jinja{{ print_time }}
, чтобы узнать, связана ли это с функцией или это потому, что вы вызываете функцию только один раз. Таким образом, функция будет извлекать данные каждый раз при обновлении страницы