Skip to main content
 首页 » 编程设计

python之如何从另一个脚本将 Bottle 作为守护进程启动

2025年05月04日11wuhuacong

我想使用 BottlePy作为从另一个脚本启动的守护程序,我在将独立脚本 (webserver.py) 转换为类时遇到了问题。下面我的网络服务器的独立版本工作正常:

import bottle 
 
@bottle.get('/hello') 
def hello(): 
    return 'Hello World' 
 
@bottle.error(404) 
def error404(error): 
    return 'error 404' 
 
bottle.run(host='localhost', port=8080) 

我现在的意图是从下面的主脚本开始

from webserver import WebServer 
from multiprocessing import Process 
 
def start_web_server(): 
    # initialize the webserver class 
    WebServer() 
 
# mainscript.py operations 
p = Process(target=start_web_server) 
p.daemon = True 
p.start() 
# more operations 

WebServer() 将在现在修改过的 webserver.py 中:

import bottle 
 
class WebServer(): 
    def __init__(self): 
        bottle.run(host='localhost', port=8080) 
 
    @bottle.get('/hello') 
    def hello(self): 
        return 'Hello World' 
 
    @bottle.error(404) 
    def error404(self, error): 
        return 'error 404' 

什么有效:整个过程开始,网络服务器正在监听

什么不起作用:在调用 http://localhost:8080/hello

时
127.0.0.1 - - [11/Dec/2013 10:16:23] "GET /hello HTTP/1.1" 500 746 
Traceback (most recent call last): 
  File "C:\Python27\lib\site-packages\bottle.py", line 764, in _handle 
    return route.call(**args) 
  File "C:\Python27\lib\site-packages\bottle.py", line 1575, in wrapper 
    rv = callback(*a, **ka) 
TypeError: hello() takes exactly 1 argument (0 given) 

我的问题是:

  • 我希望将什么样的参数传递给 hello() 和 error404()?
  • 我应该怎么做才能参数化 @bottle.get('/hello')?我想要像 @bottle.get(hello_url) 这样的东西,但是 hello_url = '/hello' 应该在哪里初始化? (self.hello_url 对于 @bottle.get 是未知的)

编辑:在准备这个问题的一个分支来处理问题 2(关于参数化)时,我顿悟并尝试了明显有效的解决方案(下面的代码)。我还不太习惯类,所以我没有反射性地将变量添加到类的范围内。

# new code with the path as a parameter 
class WebServer(): 
 
    myurl = '/hello' 
 
    def __init__(self): 
        bottle.run(host='localhost', port=8080, debug=True) 
 
    @bottle.get(myurl) 
    def hello(): 
        return 'Hello World' 
 
    @bottle.error(404) 
    def error404(error): 
        return 'error 404' 

请您参考如下方法:

what kind of parameters am I expected to pass to hello() and error404()?

简短的回答:没有。只需删除 self,它们就会开始工作。

@bottle.get('/hello') 
def hello(): 
    return 'Hello World' 
 
@bottle.error(404) 
def error404(error): 
    return 'error 404' 

what should I do in order to parametrize @bottle.get('/hello')? I would like to have something like @bottle.get(hello_url) but where should hello_url = '/hello' be initialized? (self.hello_url is unknown to @bottle.get)

我可以用几种不同的方式解释这一点,所以我不确定如何帮助你。但由于这是一个完全独立的问题(范围可能更大),请考虑在一个新的、单独的 SO 问题中提出。