在flask应用程序外部继承全局变量

时间:2018-08-30 05:11:57

标签: python flask raspberry-pi

我有一个应用程序,我在其中监视交换机的状态,同时提供一个URL供用户激活另一个交换机:

door="closed"
def switch():
  global door
  #handle GPIO SETUP
  button_state = GPIO.input(#pin)
  if button_state == True:
    if door=="closed":
      door="open"
  if button_state == False:
    door="closed"

def door_loop():
  while True:
    switch()
    #printing door here returns either open or closed
    time.sleep(1);

@app.route("/click", methods=['GET','POST'])
  def clicky():
    command = request.data
    if command:
      #turn other switch on

  return json.dumps({'is_open':door})


if __name__ == '__main__':
  p = Process(target=door_loop)
  p.start()

  app.run(
    host="0.0.0.0",
    port=int("5000"),
    debug=True
  )
  p.join()

如果在对函数door的调用之后打印出switch(),则在开门或关门时都得到了预期的输出(按下开关时,放开时看到“开”) ,我看到“关闭”)。但是,无论切换状态如何,访问http://myapp.com/click时都会得到{'is_open':'closed'}。是否有某些东西可以阻止flask从其他进程继承修改后的全局变量?

1 个答案:

答案 0 :(得分:0)

因为可变瓶门不在烧瓶和过程之间共享。您需要使用多处理中的价值

from multiprocessing import Process, Value
door = Value('i', 0)

def switch():
  global door
  #handle GPIO SETUP
  button_state = GPIO.input(#pin)
  if button_state == True:
      door.value = 1
  else:
      door.value = 2

def door_loop():
  while True:
    switch()
    #printing door here returns either open or closed
    time.sleep(1);

@app.route("/click", methods=['GET','POST'])
def clicky():
    command = request.data
    if command:
      #turn other switch on

    return json.dumps({'is_open': 'open' if door.value else 'closed'})


if __name__ == '__main__':
  p = Process(target=door_loop)
  p.start()

  app.run(
    host="0.0.0.0",
    port=int("5000"),
    debug=True
  )
  p.join()

请注意,树莓派支持事件驱动的编程,因此您可能想尝试一下而不是循环。