我正在做一个有助于在家喂养我们的猫的项目。我打算实现的是在它说明猫最后一次喂食的网站上。如果它需要喂食,有人可以按下这个按钮,它会做两件事。它将时间添加到数据库,但也将 +1 添加到数据库中的整数上,以表示单击此按钮的次数。最重要的是,将有一个计时器来检查时间,如果是“5:00”,那么凌晨 5 点,它将在数据库中将整数重置为 0。我已经设置了时间戳,并且已经帮助设置了仅用于时间戳的数据库,我似乎无法对代码进行逆向工程来制作这个整数。目前我一直在测试计时器是否工作以及单击按钮时变量是否会更新。计时器现在才刚刚工作,并且在网页上视觉上它会更新变量,但是当打印到控制台时它不会更新,也不会更新变量时间。为了让 while 循环与侧面的 Flask 服务器一起工作,我设置了一个多进程,但我认为它没有正确设置,因为它们没有更新变量。
您能否建议我阅读任何资源以便我可以学习,或者您是否可以看到任何错误?任何帮助将不胜感激!:)
我的 main.py 文件
from flask import Flask, flash, request, render_template, redirect, url_for
from flask_sqlalchemy import SQLAlchemy #this is the database to store that most recent click
app = Flask(__name__) #creates the flask app
from datetime import *
from multiprocessing import Process, Value
import time
db = SQLAlchemy()
var = 0
def timer():
global var
while True:
now = datetime.now()
current_time = now.strftime('%H:%M')
print(current_time)
print(var)
time.sleep(5)
if str(current_time) == '12:00':
var = 0
print(var)
print("Resetting")
time.sleep(5)
return var
class ClickTime(db.Model):
id = db.Column(db.INTEGER, primary_key=True)
times= db.Column(db.String())
app.config['SECRET_KEY'] = 'keppThis secret'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///data.db' #this sets the name of the database file
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db.init_app(app) #connect the db to the flask app
db.create_all(app=app) #<--run this code once to create the database file
#when created you can block this code out
@app.route("/", methods=["POST", "GET"])
def index():
global var
lastedClick = ClickTime.query.first() #this will get the last time the button has been click in the db if there is nothing in db it will return None
try:
lastedClick = lastedClick.times #This will get the time
except:
lastedClick = "Has not yet been clicked" # if nothing exists this will show up
return render_template("index.html", clickTime = lastedClick, timed=var) #renders the html page with clicktime as a variable
@app.route("/click", methods=["POST", "GET"])
def click():
global var,time
var += 1
print(var)
#this code below gets the current time
day = time.strftime('%a')
hour = time.strftime('%H')
min = time.strftime('%M')
timern = f"{day}:{hour}:{min}"
timeInString = f"at {timern}"
#timeInString will look like this:
#may 13, 2021 at 11:32 34secs
if ClickTime.query.count() == 0: #if nothing is in database
newClick = ClickTime(times=timeInString) #it will add clicktime to database with time
db.session.add(newClick)
else:
editClick = ClickTime.query.first() #if something in database
editClick.times = timeInString #it will edit time of the intance
db.session.commit() #commit new changed to db
#note: at all time there will at most be one row in databse
return redirect(url_for("index")) #redirects to the "index" function
if __name__=='__main__':
p = Process(target=timer)
p.start()
app.run(host='0.0.0.0', debug=True) #runs the app
p.join
模板/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>PFC</title>
<link href='../static/css/main.css' rel='stylesheet' type='text/css'/>
</head>
<body>
<center>
<h1>Stitch was last fed at:<br>
{{clickTime}}</h1>
<h1>{{timed}}</h1>
<form method="POST" action="/click">
<input type="submit" value="Feeding"/>
</center>
</form>
</body>
</html>