-
Notifications
You must be signed in to change notification settings - Fork 0
/
hello_2.py
79 lines (66 loc) · 1.96 KB
/
hello_2.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
from flask import Flask, jsonify, request
app = Flask(__name__)
stores = [
{
'name': 'My Cool Store',
'items': [
{
'name': 'My Item',
'price': 15.99
}
]
}
]
# From server perspective:
# POST - used to receive data
# GET - used to send data back
# PUT - make sure something is there
# DELETE - remove something
# POST /store data: {name:}
@app.route('/store', methods=['POST'])
def createStore():
requestData = request.get_json()
newStore = {
'name': requestData['name'],
'items': []
}
stores.append(newStore)
return jsonify(newStore)
# GET /store/<string:name>
@app.route('/store/<string:name>', methods=['GET']) # http://127.0.0.1:5000/store/some_name
def getStore(name):
# Iterate over stores
for store in stores:
if store['name'] == name:
return jsonify(store)
return jsonify({'message': 'No store was found.'})
# if the store name matches, return it
# if none match, return an error
# GET /store
@app.route('/store')
def getStores():
return jsonify({'stores': stores})
# POST /store/<string:name>/item {name:, price:}
@app.route('/store/<string:name>/item', methods=['POST'])
def createItemInStore(name):
requestData = request.get_json()
for store in stores:
if store['name'] == name:
newItem = {
'name': requestData['name'],
'price': requestData['price']
}
store['item'].append(newItem)
return jsonify(store)
return jsonify({'message': 'No store was found.'})
# GET /store/<string:name>/item
@app.route('/store/<string:name>/item', methods=['GET'])
def getItemsInStore(name):
for store in stores:
if store['name'] == name:
return jsonify( {'items': store['items']} )
return jsonify({'message': 'No store was found.'})
@app.route('/')
def home():
return "Hello User!"
app.run(port=5000)