-
Notifications
You must be signed in to change notification settings - Fork 0
/
first.py
64 lines (50 loc) · 1.93 KB
/
first.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
from flask import Flask, request
from flask_restful import Resource, Api, reqparse
from flask_jwt import JWT, jwt_required, current_identity
from security import authenticate, identity
app = Flask(__name__)
app.config['PROPAGATE_EXCEPTIONS'] = True # To allow flask propagating exception even if debug is set to false on app
app.secret_key = 'vbmm'
api = Api(app)
jwt = JWT(app, authenticate, identity)
items = []
class Item(Resource):
parser = reqparse.RequestParser()
parser.add_argument('price',
type=float,
required=True,
help="This field cannot be left blank!"
)
@jwt_required()
def get(self, name):
return {'item': next(filter(lambda x: x['name'] == name, items), None)}
def post(self, name):
if next(filter(lambda x: x['name'] == name, items), None) is not None:
return {'message': "An item with name '{}' already exists.".format(name)}
data = Item.parser.parse_args()
item = {'name': name, 'price': data['price']}
items.append(item)
return item
@jwt_required()
def delete(self, name):
global items
items = list(filter(lambda x: x['name'] != name, items))
return {'message': 'Item deleted'}
@jwt_required()
def put(self, name):
data = Item.parser.parse_args()
# Once again, print something not in the args to verify everything works
item = next(filter(lambda x: x['name'] == name, items), None)
if item is None:
item = {'name': name, 'price': data['price']}
items.append(item)
else:
item.update(data)
return item
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(debug=True) # important to mention debug=True