【问题标题】:Forcing single threaded request handling with web.py使用 web.py 强制单线程请求处理
【发布时间】:2012-10-27 12:58:39
【问题描述】:

我正在使用 web.py 框架。出于调试目的,我想强制所有请求由单个线程处理,或者使用互斥锁模拟这种行为。我该怎么做?

【问题讨论】:

    标签: multithreading thread-safety web.py


    【解决方案1】:

    让我提出类似的建议,但它只会将当前应用程序堆栈锁定在您的控制器方法上。

    import web
    from threading import Lock
    
    urls = ("/", "Index")
    
    
    class Index:
    
        def GET(self):
            # This will be locked
            return "hello world"
    
    
    def mutex_processor():
        mutex = Lock()
    
        def processor_func(handle):
            mutex.acquire()
            try:
                return handle()
            finally:
                mutex.release()
        return processor_func
    
    app = web.application(urls, globals())
    
    app.add_processor(mutex_processor())
    
    if __name__ == "__main__":
        app.run()
    

    UPD:如果您需要锁定整个应用程序堆栈,那么您可能必须使用您自己的 WSGI 中间件包装app.wsgifunc。要了解一下,请查看我的回答 to this question

    【讨论】:

      【解决方案2】:

      为了让事情体面地进入单线程调试模式,web.py 应用可以在单线程 WSGI 服务器上运行。

      这样的服务器“几乎”由 web.py 本身作为 web.httpserver.runbasic() 提供,它使用 Python 的内置 BaseHTTPServer.HTTPServer - 但也使用 SocketServer.ThreadingMixIn 。 这个ThreadingMixIn 但是可以被这样的东西阻止:

      # single threaded execution of web.py app
      
      app = web.application(urls, globals())
      
      # suppress ThreadingMixIn in web.httpserver.runbasic()
      import SocketServer
      class NoThreadingMixIn:
          pass
      assert SocketServer.ThreadingMixIn
      SocketServer.ThreadingMixIn = NoThreadingMixIn
      
      web.httpserver.runbasic(app.wsgifunc())
      

      或者您可以复制相当短的web.httpserver.runbasic() 代码。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-07-06
        • 2021-04-09
        • 1970-01-01
        • 2021-06-28
        相关资源
        最近更新 更多