L.Br08 L.Br08 - 3 days ago 5
reST (reStructuredText) Question

Bottle wildcard filter for hex color code

I am trying to add a filter for hex color Codes (should take formats like: 0xFF0000 or FF0000) to my bottle application.

I followed this bottle tutorial https://bottlepy.org/docs/dev/routing.html:


You can add your own filters to the router. All you need is a function that returns three elements: A regular expression string, a callable to convert the URL fragment to a python value, and a callable that does the opposite. The filter function is called with the configuration string as the only parameter and may parse it as needed:


But everytime I call my function:

@app.route('/<color:hexa>')
def call(color):
....


I receive a 404:

Not found: '/0x0000FF'


Maybe I am blind but I just don't know what I am missing. Here is my filter:

def hexa_filter(config):
regexp = r'^(0[xX])?[a-fA-F0-9]+$'

def to_python(match):
return int(match, 0)


def to_url(hexNum):
return str(hexNum)

return regexp, to_python, to_url

app.router.add_filter('hexa', hexa_filter)

Answer

Problem makes ^ (and eventually $).

Your regex can be used as part of bigger regex which checks full url - so ^ (and sometimes $) inside bigger regex makes no sense.

from bottle import *

app = Bottle()

def hexa_filter(config):
    regexp = r'(0[xX])?[a-fA-F0-9]+'

    def to_python(match):
        return int(match, 16)

    def to_url(hexNum):
        return str(hexNum)

    return regexp, to_python, to_url

app.router.add_filter('hexa', hexa_filter)

@app.route('/<color:hexa>')
def call(color):
    return 'color: ' + str(color)

app.run(host='localhost', port=8000)
Comments