【问题标题】:How to start Bottle as a daemon from another script?如何从另一个脚本启动 Bottle 作为守护进程?
【发布时间】: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


    【解决方案1】:

    我希望将什么样的参数传递给 hello() 和 error404()?

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

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

    我应该怎么做才能参数化@bottle.get('/hello')?我 想要类似@bottle.get(hello_url) 但在哪里 hello_url = '/hello' 应该被初始化吗? (self.hello_url 未知 到@bottle.get)

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

    【讨论】:

    • 哈。我认为一个人总是必须将self 传递给一个方法。谢谢 - 它有效!
    • 我会听从你的建议,并为第二部分提出一个单独的问题
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-05
    相关资源
    最近更新 更多