How Dynamic Routing Filters Work in the Bottle Framework

Asked 2 months ago, Updated 2 months ago, 3 views

I'm using a tutorial from Python's web application framework, Bottle, but it's stuck in the Dynamic Routing filter.

Specifically, execute the following code:

 from bottle import route, run, template

@route('/object/<id:int>')
def callback (id):
    assert is instance(id, int)

@route('/show/<name:re:[a-z]+')
def callback (name):
    assert name.isalpha()

@route('/static/<path:path>')
def callback (path):
    return static_file (path, null)

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

Then, when you access http://localhost:8080/object/192 from your browser:

192 object

If you look at Python's official document, isinstance() returns True or False as a return value, so I think it is correct to print True. Is 192 object correct?If not, I would appreciate it if you could point out any errors in the code provided.

Thank you for your cooperation.

python bottle

2022-09-30 11:48

1 Answers

@route('/<action>/<user>') routing.
Because @route('/object/<id:int>'), the previously described user_api function is called.
You can remove @route('/<action>/>user>') or write this user_api function after the callback function.

Also, assert returns an error only if it is an error.
If you want to return True, False, you must return a string such as return str(isinstance(id, int)) to see it correctly.

 from bottle import route, run, template

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

@route('/')
@route('/hello/<name>')
defgreet(name='Stranger'):
    return template ('Hello {{name}}, how are you?', name=name)

@route('/wiki/<pagename>')
def show_wiki_page(pagename):
    return template ('Now you see the {{pagename}} wiki.', pagename=pagename)

@route('/<action>/<user>')# Batting
def user_api(action, user):
    return template ('{{user}}{action}}', user=user, action=action)

@route('/object/<id:int>')
def callback (id):
    assert isinstance(id, int)# Returns error when incorrect
    return str(isinstance(id, int))# Returns True, False

@route('/show/<name:re:[a-z]+')
def callback (name):
    assert name.isalpha()

@route('/static/<path:path>')
def callback (path):
    return static_file (path, null)

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

I edited this post based on @metropolis's comment and posted it as community wiki.I edited this post based on @metropolis's Comment and posted it as Community Wiki.


2022-09-30 11:48

If you have any answers or tips


© 2022 OneMinuteCode. All rights reserved.