【发布时间】:2013-12-12 15:33:05
【问题描述】:
我想使用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'
【问题讨论】:
标签: python multiprocessing daemon bottle