flask restx full example

Solutions on MaxInterview for flask restx full example by the best coders in the world

showing results for - "flask restx full example"
Cierra
08 Jan 2021
1from flask import Flask
2from flask_restx import Api, Resource, fields
3from werkzeug.middleware.proxy_fix import ProxyFix
4
5app = Flask(__name__)
6app.wsgi_app = ProxyFix(app.wsgi_app)
7api = Api(app, version='1.0', title='TodoMVC API',
8    description='A simple TodoMVC API',
9)
10
11ns = api.namespace('todos', description='TODO operations')
12
13todo = api.model('Todo', {
14    'id': fields.Integer(readonly=True, description='The task unique identifier'),
15    'task': fields.String(required=True, description='The task details')
16})
17
18
19class TodoDAO(object):
20    def __init__(self):
21        self.counter = 0
22        self.todos = []
23
24    def get(self, id):
25        for todo in self.todos:
26            if todo['id'] == id:
27                return todo
28        api.abort(404, "Todo {} doesn't exist".format(id))
29
30    def create(self, data):
31        todo = data
32        todo['id'] = self.counter = self.counter + 1
33        self.todos.append(todo)
34        return todo
35
36    def update(self, id, data):
37        todo = self.get(id)
38        todo.update(data)
39        return todo
40
41    def delete(self, id):
42        todo = self.get(id)
43        self.todos.remove(todo)
44
45
46DAO = TodoDAO()
47DAO.create({'task': 'Build an API'})
48DAO.create({'task': '?????'})
49DAO.create({'task': 'profit!'})
50
51
52@ns.route('/')
53class TodoList(Resource):
54    '''Shows a list of all todos, and lets you POST to add new tasks'''
55    @ns.doc('list_todos')
56    @ns.marshal_list_with(todo)
57    def get(self):
58        '''List all tasks'''
59        return DAO.todos
60
61    @ns.doc('create_todo')
62    @ns.expect(todo)
63    @ns.marshal_with(todo, code=201)
64    def post(self):
65        '''Create a new task'''
66        return DAO.create(api.payload), 201
67
68
69@ns.route('/<int:id>')
70@ns.response(404, 'Todo not found')
71@ns.param('id', 'The task identifier')
72class Todo(Resource):
73    '''Show a single todo item and lets you delete them'''
74    @ns.doc('get_todo')
75    @ns.marshal_with(todo)
76    def get(self, id):
77        '''Fetch a given resource'''
78        return DAO.get(id)
79
80    @ns.doc('delete_todo')
81    @ns.response(204, 'Todo deleted')
82    def delete(self, id):
83        '''Delete a task given its identifier'''
84        DAO.delete(id)
85        return '', 204
86
87    @ns.expect(todo)
88    @ns.marshal_with(todo)
89    def put(self, id):
90        '''Update a task given its identifier'''
91        return DAO.update(id, api.payload)
92
93
94if __name__ == '__main__':
95    app.run(debug=True)
96