【问题标题】:Run Python HTTPServer in Background and Continue Script Execution在后台运行 Python HTTPServer 并继续执行脚本
【发布时间】:2015-10-09 01:45:02
【问题描述】:

我试图弄清楚在运行“”.serve_forever() 方法后如何在后台运行我重载的自定义 BaseHTTPServer 实例。

通常,当您运行该方法时,执行将挂起,直到您执行键盘中断,但我希望它在继续执行脚本的同时在后台处理请求。请帮忙!

【问题讨论】:

    标签: python python-multithreading basehttpserver python-daemon


    【解决方案1】:

    您可以在不同的线程中启动服务器:https://docs.python.org/2/library/thread.html

    比如:

    def start_server():
        # Setup stuff here...
        server.serve_forever()
    
    # start the server in a background thread
    thread.start_new_thread(start_server)
    
    print('The server is running but my script is still executing!')
    

    【讨论】:

      【解决方案2】:

      我试图使用 async 做一些长期动画,并认为我必须重写服务器以使用 aiohttp (https://docs.aiohttp.org/en/v0.12.0/web.html),但 Olivers 使用单独线程的技术为我节省了所有痛苦。我的代码如下所示,其中 MyHTTPServer 只是我自定义的 HTTPServer 子类

      import threading
      import asyncio
      from http.server import BaseHTTPRequestHandler, HTTPServer
      import socketserver
      import io
      import threading
      
      async def tick_async(server):        
          while True:
              server.animate_something()
              await asyncio.sleep(1.0)
      
      def start_server():
          httpd.serve_forever()
          
      try:
          print('Server listening on port 8082...')
      
          httpd = MyHTTPServer(('', 8082), MyHttpHandler)
          asyncio.ensure_future(tick_async(httpd))
          loop = asyncio.get_event_loop()
          t = threading.Thread(target=start_server)
          t.start()
          loop.run_forever()
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-06-14
        • 2020-03-21
        • 1970-01-01
        • 2011-08-26
        • 2019-01-10
        • 1970-01-01
        相关资源
        最近更新 更多