如何在python中不再提供一个HTTP请求?

2024-05-15 02:30:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个简单的HTTP服务器设置,比如this one。它处理一个缓慢的40秒请求,打开然后关闭闸门(真正的金属闸门)。如果第二个HTTP查询是在第一个查询的执行过程中进行的,则将其放入队列中,然后在第一次运行之后执行。我不需要这种行为,如果门打开/关闭过程正在进行,我需要用错误回复。 我该怎么做?有一个参数“request\u queue\u size”-但我不知道如何设置它。你知道吗


Tags: 服务器http参数size队列queue过程request
3条回答

“请求队列大小”似乎没有效果。 解决方案是使服务器多线程化,并实现锁定变量“busy”:

from socketserver import ThreadingMixIn
from http.server import BaseHTTPRequestHandler, HTTPServer
import time
from gpiozero import DigitalOutputDevice
import logging
from time import sleep
logging.basicConfig(format='%(asctime)s %(levelname)s:%(message)s', level=logging.INFO)

hostName = ''
hostPort = 9001
busy = False

class ThreadingServer(ThreadingMixIn, HTTPServer):
    pass

class MyServer(BaseHTTPRequestHandler):
    def do_GET(self):
        global busy
        self.send_response(200)
        self.send_header("Content-type", "text/html")
        self.end_headers()
        self.wfile.write(bytes("Hello!<br>", "utf-8"))
        if self.path == '/gates':
           if not busy:
             busy = True
             relay = DigitalOutputDevice(17) # Initialize GPIO 17
             relay.on()
             logging.info('Cycle started')
             self.wfile.write(bytes("Cycle started<br>", "utf-8"))
             sleep(2)
             relay.close()
             sleep(20)
             relay = DigitalOutputDevice(17)
             relay.on()
             sleep(2)
             relay.close()
             logging.info('Cycle finished')
             self.wfile.write(bytes("Cycle finished", "utf-8"))
             busy = False
           else:
#             self.wfile.write(bytes("Busy now!<br>", "utf-8"))
             self.send_error(503)

myServer = ThreadingServer((hostName, hostPort), MyServer)
print(time.asctime(), "Server Starts - %s:%s" % (hostName, hostPort))

try:
    myServer.serve_forever()
except KeyboardInterrupt:
    pass

myServer.server_close()
print(time.asctime(), "Server Stops - %s:%s" % (hostName, hostPort))

一般来说,您要寻找的想法称为请求节流。在网络上有很多这样的实现应该不难挖掘:这里有一个是针对Flask的,我选择的微框架-https://flask-limiter.readthedocs.io/en/stable/

快速使用示例:

@app.route("/open_gate")
@limiter.limit("1 per minute")
def slow():
    gate_robot.open_gate()
    return 

您需要遵循不同的策略来设计服务器服务。您需要将门的状态保存在内存或数据库中。然后,每次收到对门执行操作的请求时,都会在持久性中检查门的当前状态,如果可以对当前状态执行操作,则执行该操作,否则返回错误。另外,一旦一个动作完成,不要忘记更新门的状态。你知道吗

相关问题 更多 >

    热门问题