1

I want to create my own decorotar which will be "extend" @route decorator from Bottle framework. I have problem with sementic. This code dosen't work and I don't have idea how to repair it.

from bottle import route, run
class router(object):
    def __init__(self, f):
        self.f = f

    def __call__(self, *args):
        self.f(*args)

@router('/hello')
def hello():
    return "Hello World!"

run(host='localhost', port=8080, debug=True)

edit: Second try:

from bottle import Bottle
class B(Bottle):
    def route(self,*args):
        def f(*args):
            print "My Text" #This dosen't print
            super(B, self).route(*args)
        return f  
b = B()

@b.route('/hello')
def hello():
    return "Hello World!x"

b.run(host='localhost', port=8080, debug=True)

Also dosen't work.

Bartłomiej Bartnicki
  • 1,067
  • 2
  • 14
  • 30

1 Answers1

0

As I stumbled on this question to try to solve a similar issue, I found out that there are several issues in your code:

  • decorators with arguments shall return a decorator with the decorated function as sole argument (read this twice ;-));
  • you use *args twice in your decorator;
  • you do nothing from the function in the decorator;
  • it's not clear what is a function or a "plain" argument.

Here is a fixed version (python 3):

from bottle import Bottle

class B(Bottle):
    def route(self, *rt_args):
        def wrapper(func):  # <<-- your decorator shall take the function as argument
            print(f"registering {func.__name__} with {rt_args}")
            super(B, self).route(*rt_args, callback=func)  # <<-- register the function!
            return func
        return wrapper

b = B()
@b.route('/hello')
def hello():
    return "hello world!"

b.run(host='localhost', port=8080, debug=True)

This works well for me afterwards, with the print statement visible in terminal:

(.env) joel@joel-T470s:~/......$ python3 test-bottle.py 
registering hello with ('/hello',)
Bottle v0.12.18 server starting up (using WSGIRefServer())...
Listening on http://localhost:8080/
Hit Ctrl-C to quit.

127.0.0.1 - - [19/Apr/2020 10:19:34] "GET /hello HTTP/1.1" 200 12

This subject is somewhat answered in a similar questions.

Joël
  • 2,723
  • 18
  • 36