-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathapi.py
More file actions
99 lines (78 loc) · 2.49 KB
/
Copy pathapi.py
File metadata and controls
99 lines (78 loc) · 2.49 KB
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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
"""
'Hello World' app, basically lol. Will add a reaaaalll db later.
Copy pasta from https://github.com/python-restx/flask-restx
"""
from flask import Flask
from flask_restx import Api, Resource, fields
from collections import defaultdict
app = Flask(__name__)
api = Api(app, version='1.0', title='TraceMVC API',
description='A simple TraceMVC API',
)
ns = api.namespace('traces', description='Trace operations')
trace = api.model('Trace', {
'id': fields.Integer(readOnly=True, description='The trace unique identifier'),
'plus_codes': fields.String(required=True, description='pluscod.es')
})
class TraceDAO(object):
def __init__(self):
self.counter = 0
self.traces = []
def get(self, id):
for trace in self.traces:
if trace['id'] == id:
return trace
api.abort(404, "Trace {} doesn't exist".format(id))
def create(self, data):
trace = data
trace['id'] = self.counter = self.counter + 1
self.traces.append(trace)
return trace
def update(self, id, data):
trace = self.get(id)
trace.update(data)
return trace
def delete(self, id):
trace = self.get(id)
self.traces.remove(trace)
DAO = TraceDAO()
DAO.create({'trace': 'Build an API'})
DAO.create({'trace': '?????'})
DAO.create({'trace': 'profit!'})
@ns.route('/')
class TraceList(Resource):
'''Shows a list of all traces, and lets you POST to add new traces'''
@ns.doc('list_traces')
@ns.marshal_list_with(trace)
def get(self):
'''List all traces'''
return DAO.traces
@ns.doc('create_trace')
@ns.expect(trace)
@ns.marshal_with(trace, code=201)
def post(self):
'''Create a new trace'''
return DAO.create(api.payload), 201
@ns.route('/<int:id>')
@ns.response(404, 'Trace not found')
@ns.param('id', 'The trace identifier')
class Trace(Resource):
'''Show a single trace item and lets you delete them'''
@ns.doc('get_trace')
@ns.marshal_with(trace)
def get(self, id):
'''Fetch a given resource'''
return DAO.get(id)
@ns.doc('delete_trace')
@ns.response(204, 'Trace deleted')
def delete(self, id):
'''Delete a trace given its identifier'''
DAO.delete(id)
return '', 204
@ns.expect(trace)
@ns.marshal_with(trace)
def put(self, id):
'''Update a trace given its identifier'''
return DAO.update(id, api.payload)
if __name__ == '__main__':
app.run(debug=True)