本文介绍了Bottle Web框架-如何停止?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

启动没有线程或子进程的Bottle Web服务器时,没有问题.要退出瓶子应用程序-> CTRL + c.

When starting a bottle webserver without a thread or a subprocess, there's no problem. To exit the bottle app -> CTRL + c.

在一个线程中,如何以编程方式停止瓶子Web服务器?

In a thread, how can I programmatically stop the bottle web server ?

我没有在文档中找到stop()方法或类似方法.有原因吗?

I didn't find a stop() method or something like that in the documentation. Is there a reason ?

推荐答案

对于默认(WSGIRef)服务器,这就是我要做的(实际上,这是Vikram Pudi的建议的更简洁的方法):

For the default (WSGIRef) server, this is what I do (actually it is a cleaner approach of Vikram Pudi's suggestion):

from bottle import Bottle, ServerAdapter

class MyWSGIRefServer(ServerAdapter):
    server = None

    def run(self, handler):
        from wsgiref.simple_server import make_server, WSGIRequestHandler
        if self.quiet:
            class QuietHandler(WSGIRequestHandler):
                def log_request(*args, **kw): pass
            self.options['handler_class'] = QuietHandler
        self.server = make_server(self.host, self.port, handler, **self.options)
        self.server.serve_forever()

    def stop(self):
        # self.server.server_close() <--- alternative but causes bad fd exception
        self.server.shutdown()

app = Bottle()

@app.route('/')
def index():
    return 'Hello world'

@app.route('/stop')  # not working from here, it has to come from another thread
def stopit():
    server.stop()

server = MyWSGIRefServer(port=80)
try:
    app.run(server=server)
except:
    print('Bye')

当我想从另一个线程停止瓶子应用程序时,请执行以下操作:

When I want to stop the bottle application, from another thread, I do the following:

server.stop()

这篇关于Bottle Web框架-如何停止?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 12:26