【问题标题】:Is it possible to turn a led on and off after every apache request是否可以在每次 apache 请求后打开和关闭 LED
【发布时间】:2020-06-16 11:48:48
【问题描述】:

我现在尝试 2 周,以便在有人打开我的网站后打开 LED。顺序应该是这样的:

  1. 已收到请求
  2. LED 亮起,0.5 秒后再次熄灭
  3. 回复已发回

我有一个 Raspberry Pi 可以打开我的 LED。

到目前为止我的python代码:

import time
import RPi.GPIO as GPIO

pin = 4

GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.setup(pin, GPIO.OUT)

GPIO.output(pin, GPIO.HIGH)
time.sleep(0.1)
GPIO.output(pin, GPIO.LOW)

它有时会起作用,但现在显示了网站。 我用 WSGI 试过,但有点复杂。 也许有人有同样的想法,它适用于他,他可以帮助我。

【问题讨论】:

  • 您需要使用“钩子”将您的 Python 代码与 apache 集成。 mod_wsgi 模块允许制作这样的钩子,参见例如教程toptal.com/python/pythons-wsgi-server-application-interface
  • @EvertW 你知道如何用 wsgi 制作这样的钩子吗,因为你的教程会做出响应,但我不希望 python 做出响应,但我的网络服务器 apache 应该用请求的文件响应

标签: python apache raspberry-pi mod-wsgi raspberry-pi4


【解决方案1】:

您根本不需要任何 Apache 或任何复杂的东西,您只需将用于打开和关闭 LED 的位添加到 Python 提供的简单 Web 服务器类中。

只需调整这段代码顶部的 IP 地址和端口,然后在终端中运行它并连接到它所服务的地址:

#!/usr/bin/env python3

#import RPi.GPIO as GPIO
import os
from time import sleep
from http.server import BaseHTTPRequestHandler, HTTPServer

host_name = '192.168.0.8'
host_port = 63000
pin = 4

class MyServer(BaseHTTPRequestHandler):

    def do_HEAD(self):
        self.send_response(200)
        self.send_header('Content-type', 'text/html')
        self.end_headers()

    def do_GET(self):
        html = '''
           <html>
           <body style="width:960px; margin: 20px auto;">
           <h1>Welcome to my Raspberry Pi</h1>
           </body>
           </html>
        '''

        # You may want to move these 3 setup lines to the very start of the program
        GPIO.setwarnings(False)
        GPIO.setmode(GPIO.BCM)
        GPIO.setup(pin, GPIO.OUT)

        GPIO.output(pin, GPIO.HIGH)
        sleep(0.1)
        GPIO.output(pin, GPIO.LOW)

        self.do_HEAD()
        self.wfile.write(html.encode("utf-8"))

if __name__ == '__main__':
    http_server = HTTPServer((host_name, host_port), MyServer)
    print("Server Starts - %s:%s" % (host_name, host_port))

    try:
        http_server.serve_forever()
    except KeyboardInterrupt:
        http_server.server_close()

【讨论】:

  • 这是个好主意,但我已经有一个完全配置的 apache 服务器,只是想在 apache 发回响应之前运行一点 python
猜你喜欢
  • 2012-02-11
  • 2015-11-08
  • 2020-05-22
  • 2014-01-14
  • 2021-03-12
  • 1970-01-01
  • 1970-01-01
  • 2020-03-10
  • 1970-01-01
相关资源
最近更新 更多