Python 如何从另一个脚本启动瓶子作为守护进程?
我想用作从另一个脚本启动的守护进程,但在将独立脚本(Python 如何从另一个脚本启动瓶子作为守护进程?,python,multiprocessing,daemon,bottle,Python,Multiprocessing,Daemon,Bottle,我想用作从另一个脚本启动的守护进程,但在将独立脚本(webserver.py)转换为类时遇到问题。下面我的Web服务器的独立版本运行良好: 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)
webserver.py
)转换为类时遇到问题。下面我的Web服务器的独立版本运行良好:
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'
什么有效:整个过程开始,Web服务器正在监听
什么不起作用:调用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\u url)
应该在哪里初始化呢?(hello\u url='/hello'
对于self.hello\u url
是未知的)@battle.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'
我应该向hello()和error404()传递什么样的参数
简单的回答是:没有。只需移除self
,它们就可以开始工作了
@bottle.get('/hello')
def hello():
return 'Hello World'
@bottle.error(404)
def error404(error):
return 'error 404'
我应该怎么做才能参数化@瓶子.get('/hello')?我 想要像@瓶子。获取(hello_url)这样的东西,但是在哪里 应该初始化hello_url='/hello'吗?(self.hello\u url未知 发送至@bottle.get)
我可以用几种不同的方式来解释这一点,所以我不知道如何帮助你。但由于这是一个完全不同的问题(潜在的范围要大得多),请考虑在一个新的、单独的问题中提问。我认为一个人总是必须将
self
传递给一个方法。谢谢你-它的工作!我将按照你的建议,就第二部分提出一个单独的问题