I would like to use BottlePy as a daemon started from another script and I have issues turning a standalone script (webserver.py
) into a class. The standalone version of my webserver below works fine:
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)
My intent is now to start it from the main script below as
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
where WebServer()
would be in the naively now-modified 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'
What works: the whole thing starts and the webserver is listening
What does not work: upon calling 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)
My questions are:
- what kind of parameters am I expected to pass to
hello()
anderror404()
? - what should I do in order to parametrize
@bottle.get('/hello')
? I would like to have something like@bottle.get(hello_url)
but where shouldhello_url = '/hello'
be initialized? (self.hello_url
is unknown to@bottle.get
)
EDIT: while preparing a fork of this question to handle question 2 (about the parametrization) I had an epiphany and tried the obvious solution which works (code below). I am not that used to classes yet so I did not have the reflex to add the variable in the scope of the class.
# 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'