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






你可能感興趣的文章

Arrays.sort() vs Collections.sort()

Arrays.sort() vs Collections.sort()

DAY8:Odd or Even?

DAY8:Odd or Even?

[Note] JS: Function 觀念

[Note] JS: Function 觀念






留言討論