Search code examples
pythonbottle

What is the correct way to access endpoints using get_url() or url()?


i'm using Bottle. I have defined several routes with their corresponding view function for example

/log/<page>
/showlogs

How am i supposed to access the endpoints?! Here are the relevant view functions:

@app.route( '/log/<page>' )
def log( page ):

@app.route( '/showlogs' )
def showlogs():

What is the correct way to access those routes using get_url? I try to:

get_url( 'log', page=page )
get_url( 'showlogs' )

and the error iam receiving is:

[Sun Sep 23 00:35:21.013955 2018] [wsgi:error] [pid 13159] [remote 45.77.155.110:50978]   File "/usr/lib/python3.6/site-packages/bottle.py", line 766, in get_url
[Sun Sep 23 00:35:21.013971 2018] [wsgi:error] [pid 13159] [remote 45.77.155.110:50978]     location = self.router.build(routename, **kargs).lstrip('/')
[Sun Sep 23 00:35:21.013975 2018] [wsgi:error] [pid 13159] [remote 45.77.155.110:50978]   File "/usr/lib/python3.6/site-packages/bottle.py", line 403, in build
[Sun Sep 23 00:35:21.013978 2018] [wsgi:error] [pid 13159] [remote 45.77.155.110:50978]     if not builder: raise RouteBuildError("No route with that name.", _name)
[Sun Sep 23 00:35:21.013982 2018] [wsgi:error] [pid 13159] [remote 45.77.155.110:50978] bottle.RouteBuildError: ('No route with that name.', 'log')

Why get_url complains that there are no routes with that name when they are clearly are?!


Solution

  • (1) You haven't shown us your code, so we can't tell you what's wrong with it, but here's a working example of get_url. (Note that get_url is a method of the Bottle class, so you must use it as such.)

    from bottle import Bottle
    
    app = Bottle()
    
    @app.route('/log/<page>')
    def handle_log(page):
        return ['your page was: {}'.format(page)]
    
    @app.route('/showlogs')
    def handle_showlogs():
        return ['showing the logs...']
    
    print app.get_url('/showlogs')  # prints "/showlogs"
    print app.get_url('/log/<page>', page='123')  # prints "/log/123"
    print app.get_url('nope')  # raises RouteBuildError, as expected
    

    (2) Your last question,

    How am i supposed to access the endpoints?

    makes me wonder if this is an XY problem (because I'm not sure what "access" could mean here).

    If it is (in other words: if, now that you know how to successfully call get_url, you still can't do what you're trying to do), then please resolve this question and simply ask a new question that states your goal; we'll try to help with that.

    Hope that helps!