0

我想用 Sanic ( https://github.com/huge-success/sanic ) 做一个 API REST 并且我坚持使用正则表达式。

我有这个端点:api/foo/<string_with_or_without_slashes>/bar/<string>/baz

我的python代码是:

from sanic import Sanic                                                                                                                                                                  
from sanic.response import json                                                                                                                                                          

app = Sanic()                                                                                                                                                                            

@app.route('/api/foo/<foo_id:[^/].*?>/baz')                                                                                                                                              
async def test1(request, foo_id):                                                                                                                                                        
    return json({'test1': foo_id})                                                                                                                                                       

@app.route('/api/foo/<foo_id:[^/].*?>/bar/<bar_id>/baz')                                                                                                                                 
async def test2(request, foo_id, bar_id):                                                                                                                                                 
    return json({'test2': f'{foo_id}:{bar_id}'})                                                                                                                                         

if __name__ == '__main__':                                                                                                                                                               
    app.run(host='0.0.0.0', port=8000)          

如果我做:

$ curl -i http://localhost:8000/api/foo/aa/bar/bb/baz
{"test1":"aa\/bar\/bb"} 

$ curl -i http://localhost:8000/api/foo/a/a/bar/bb/baz

test1当我想调用test2函数时,它总是被调用。

你能帮助我吗?非常感谢!:)

4

1 回答 1

1

两条路由都匹配您的测试请求,并在使用第一个匹配路由时执行(请参阅GitHub 上的此问题test1

因为您的第一条路线比第二条路线更通用,您可以在test2之前定义test1

from sanic import Sanic
from sanic.response import json

app = Sanic()

@app.route('/api/foo/<foo_id:[^/].*?>/bar/<bar_id>/baz')
async def test2(request, foo_id, bar_id):
    return json({'test2': f'{foo_id}:{bar_id}'})

@app.route('/api/foo/<foo_id:[^/].*?>/baz')
async def test1(request, foo_id):
    return json({'test1': foo_id})

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=8000)
于 2019-09-23T20:56:16.163 回答