-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCRUD.py
More file actions
106 lines (86 loc) · 2.82 KB
/
Copy pathCRUD.py
File metadata and controls
106 lines (86 loc) · 2.82 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
100
101
102
103
104
105
106
from flask import Flask, request, jsonify
app = Flask(__name__)
class Material:
def __init__(self, id, name, qtde):
self.id = id
self.name = name
self.qtde = qtde
@staticmethod
def buscar_material_por_id(id):
for material in materiais:
if material.id == id:
return material
return None
materiais = []
material_id_counter = 0
@app.route('/materiais', methods=['GET'])
def listar_materiais():
response = []
for i, material in enumerate(materiais):
data = {
'id': material.id,
'name': material.name,
'qtde': material.qtde
}
response.append(data)
return jsonify(response), 200
@app.route('/materiais', methods=['POST'])
def criar_material():
data = request.get_json()
nome = data['material']['name']
qtde = data['material']['qtde']
global material_id_counter
material_id_counter += 1
material = Material(material_id_counter, nome, qtde)
materiais.append(material)
response = {'message': 'Material criado com sucesso!'}
return jsonify(response), 201
@app.route('/materiais/<int:id>', methods=['GET'])
def buscar_material(id):
material = Material.buscar_material_por_id(id)
if material:
response = {'material': {
'id': material.id,
'name': material.name,
'qtde': material.qtde
}}
return jsonify(response), 200
else:
return jsonify({'message': 'Material não encontrado'}), 404
@app.route('/materiais/<int:id>', methods=['PUT'])
def alterar_material(id):
data = request.get_json()
nome = data['material']['name']
qtde = data['material']['qtde']
material = Material.buscar_material_por_id(id)
if material:
material.name = nome
material.qtde = qtde
response = {
'material': {
'id': material.id,
'name': material.name,
'qtde': material.qtde
}
}
return jsonify(response), 200
else:
return jsonify({'message': 'Material não encontrado'}), 404
@app.route('/materiais/<int:id>', methods=['DELETE'])
def remover_material(id):
material = Material.buscar_material_por_id(id)
if material:
materiais.remove(material)
response = []
for i, material in enumerate(materiais):
data = {
'id': material.id,
'name': material.name,
'qtde': material.qtde
}
response.append(data)
return jsonify(response), 200
else:
return jsonify({'message': 'Material não encontrado'}), 404
if __name__ == '__main__':
app.run()