2016-11-30 88 views
0

我想添加一個過濾器的十六進制顏色代碼(應採取格式,如:0xFF0000或FF0000)到我的瓶應用程序。十六進制顏色代碼瓶通配符過濾器

我跟着這瓶教程https://bottlepy.org/docs/dev/routing.html

您可以添加您自己的過濾器到路由器。您只需要一個返回三個元素的函數:一個正則表達式字符串,一個可將URL片段轉換爲python值的可調用對象,以及一個可調用的對象。過濾函數被調用,配置字符串作爲唯一的參數,並可以解析它需要:

但每次我打電話給我的功能:

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

我收到了404:

Not found: '/0x0000FF' 

也許我是盲人,但我只是不知道我缺少什麼。這裏是我的過濾器:

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) 

回答

0

問題使得^(最終$)。

您的正則表達式可以用作檢查完整url的更大正則表達式的一部分 - 所以^(有時$)在更大的正則表達式中是沒有意義的。

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) 
+0

太棒了,謝謝!完美的作品!我可能不得不多花一點時間! –

相關問題