03. 建立items resource


from flask import Flask
from flask_restful import Resource, Api

app = Flask(__name__)
api = Api(app)

items = []

# Every resource is a class
class Item(Resource):
    def get(self, name):
        for item in items:
            if item['name'] == name:
                return item
        return {'item': None}, 404

    def post(self, name):
        item = {'name': name, 'price': 12.00}
        items.append(item)
        return item, 201

api.add_resource(Item, '/item/<string:name>')

if __name__ == '__main__':
    app.run(port=5000, debug=True)
from flask import Flask, request
from flask_restful import Resource, Api

app = Flask(__name__)
api = Api(app)

items = []

# Every resource is a class
class Item(Resource):
    def get(self, name):
        for item in items:
            if item['name'] == name:
                return item
        return {'item': None}, 404

    def post(self, name):
        data = request.get_json(silent=True)
        item = {'name': name, 'price': data['price']}
        items.append(item)
        return item, 201

class ItemList(Resource):
    def get(self):
        return {'items': items}

api.add_resource(Item, '/item/<string:name>')
api.add_resource(ItemList, '/items')

if __name__ == '__main__':
    app.run(port=5000, debug=True)
#Flask #Python #REST







你可能感興趣的文章

Day00 - CERN ROOT 教學 | 動機、這是什麼

Day00 - CERN ROOT 教學 | 動機、這是什麼

[23] 強制轉型 - 明確的強制轉型、Strings <> Numbers、日期轉 Number、位元運算子

[23] 強制轉型 - 明確的強制轉型、Strings <> Numbers、日期轉 Number、位元運算子

D61_W8 (1 of 61)

D61_W8 (1 of 61)






留言討論