【发布时间】:2015-10-09 01:45:02
【问题描述】:
我试图弄清楚在运行“”.serve_forever() 方法后如何在后台运行我重载的自定义 BaseHTTPServer 实例。
通常,当您运行该方法时,执行将挂起,直到您执行键盘中断,但我希望它在继续执行脚本的同时在后台处理请求。请帮忙!
【问题讨论】:
标签: python python-multithreading basehttpserver python-daemon
我试图弄清楚在运行“”.serve_forever() 方法后如何在后台运行我重载的自定义 BaseHTTPServer 实例。
通常,当您运行该方法时,执行将挂起,直到您执行键盘中断,但我希望它在继续执行脚本的同时在后台处理请求。请帮忙!
【问题讨论】:
标签: python python-multithreading basehttpserver python-daemon
您可以在不同的线程中启动服务器: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!')
【讨论】:
我试图使用 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()
【讨论】: