Bottle框架中的@ get,@ post是什么?

问题描述 投票:-1回答:1

我将按照教程在Bottle框架中构建REST API。装饰器@get@post经常使用,我想知道它们的作用,它们是另一个代码的缩写吗?如果可以,有人可以提供吗?

from bottle import run, get, post, request, delete

animals = [{'name' : 'Ellie', 'type' : 'Elephant'}, 
            {'name' : 'Python', 'type' : 'Snake'},
            {'name' : 'Zed', 'type' : 'Zebra'}]

@get('/')
def docs():
    return {'<h1>request and post to these endpoints<br> /animals <br> /animals/name </h1>'}

@get('/animal')
def getAll():   
    return {'animals' : animals}

@get('/animal/<name>')
def getOne(name):
    the_animal = [animal for animal in animals if animal['name'] == name]
    return {'animal' : the_animal[0]}

@post('/animal')
def addOne():
    new_animal = {'name' : request.json.get('name'), 'type' : request.json.get('type')}
    animals.append(new_animal)
    return {'animals' : animals}

@delete('/animal/<name>')
def removeOne(name):
    the_animal = [animal for animal in animals if animal['name'] == name]
    animals.remove(the_animal[0])
    return {'animals' : animals}

run(reloader=True, debug=True)
python python-3.x python-2.7 bottle
1个回答
0
投票

它们是route功能的简写。它们的名称反映了装饰函数应该处理的HTTP请求方法(GET,POST,DELETE等)。 Bottle的“ hello world”教程包含有关方法及其各自的装饰器的route

HTTP协议为不同的任务定义了几种请求方法(有时称为“动词”)。 GET是所有路由的默认设置,未指定其他方法。这些路由将仅匹配GET请求。要处理其他方法,例如POST,PUT,DELETE或PATCH,请在route()装饰器中添加方法关键字参数,或使用五个替代装饰器之一:get(),post(),put(),delete()或patch()。

© www.soinside.com 2019 - 2024. All rights reserved.