Created
August 17, 2020 20:03
-
-
Save dunossauro/ef471bd6e44e297f53f7515b68e7756e to your computer and use it in GitHub Desktop.
todo list using flask restx
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from flask import Flask, jsonify, abort, request, make_response, url_for | |
from flask_restx import Api, Namespace, Resource, fields | |
app = Flask(__name__, static_url_path='') | |
api = Api( | |
app, | |
'todos', | |
description='Operações ligadas as suas tarefas', | |
) | |
ns = Namespace('todos', description='Operações ligadas as suas tarefas') | |
api.add_namespace(ns) | |
todo = api.model( | |
'Todo', | |
{ | |
'id': fields.Integer( | |
readonly=True, description='Identificador único da tarefa' | |
), | |
'title': fields.String(required=True, description='Nome da tarefa'), | |
'description': fields.String( | |
required=True, description='Descrição da tarefa' | |
), | |
'done': fields.Boolean( | |
required=True, description='A tarefa está concluída?' | |
), | |
}, | |
) | |
@app.errorhandler(400) | |
def not_found(error): | |
return make_response(jsonify({'error': 'Bad request'}), 400) | |
@app.errorhandler(404) | |
def not_found(error): | |
return make_response(jsonify({'error': 'Not found'}), 404) | |
tasks = [ | |
{ | |
'id': 1, | |
'title': 'Dormir', | |
'description': 'pq é bom', | |
'state': False | |
} | |
] | |
class TodoDAO(object): | |
def __init__(self): | |
self.counter = 0 | |
self.todos = [] | |
def get(self, id): | |
for todo in self.todos: | |
if todo['id'] == id: | |
return todo | |
api.abort(404, "Todo {} doesn't exist".format(id)) | |
def create(self, data): | |
todo = data | |
todo['id'] = self.counter = self.counter + 1 | |
self.todos.append(todo) | |
return todo | |
def update(self, id, data): | |
todo = self.get(id) | |
todo.update(data) | |
return todo | |
def delete(self, id): | |
todo = self.get(id) | |
self.todos.remove(todo) | |
DAO = TodoDAO() | |
@ns.route('/api/tasks') | |
class TodoList(Resource): | |
@ns.doc('Batatinha frita') | |
@ns.marshal_list_with(todo, code=200) | |
def get(self): | |
return DAO.todos | |
@ns.marshal_with(todo, code=201) | |
@ns.expect(todo) | |
def post(self): | |
return DAO.create(api.payload), 201 | |
@ns.route('/api/tasks/<int:task_id>') | |
class Todo(Resource): | |
@ns.marshal_with(todo) | |
def get(self, task_id): | |
return DAO.get(id) | |
@ns.marshal_with(todo) | |
def delete(self, task_id): | |
DAO.delete(id) | |
return '', 204 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment