单击"从RaspberryPi向Firebase添加数据"按钮



正如标题所说,我正试图通过使用Python从树莓派按钮点击器中点击按钮,将数据添加到我的云火库中。我已经设法使它工作,但如果我多次单击该按钮,它将不会再次将数据添加到我的数据库中,除非再次运行我的脚本。这意味着如果我点击一次按钮,它会添加到数据库中,但如果我再次点击,它不会添加任何内容,只会显示"添加"。

new_doc = db.collection(u'report').document()
#YELLOW 
greenBtn = Button(17) #Using gpiozero library
greenLED = LED(13)

def add():
greenLED.on()
try:
new_doc.set({u'name': u'report two'})
print("add")
except:
print("fail")
greenBtn.when_pressed = add
greenBtn.when_released = greenLED.off

第一次运行脚本时,您正在创建一个新文档。然后,当用户按下按钮时,您将继续更新同一文档。因此,虽然每次单击按钮都会导致写入,但您不会看到后续写入,因为您一直在向同一文档写入相同的值。

两种解决方案:

  1. 每次写入不同的值
  2. 每次都写入不同的文档

既然你似乎期待一个新的文档,我将展示如何做到这一点:

#YELLOW 
greenBtn = Button(17) #Using gpiozero library
greenLED = LED(13)

def add():
greenLED.on()
new_doc = db.collection(u'report').document()
try:
new_doc.set({u'name': u'report two'})

因此,现在每当用户按下按钮时,都会创建新文档。

最新更新