-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
101 lines (76 loc) · 2.75 KB
/
main.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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
from flask import Flask, request, jsonify, make_response
from flask_sqlalchemy import SQLAlchemy
from marshmallow import fields
from marshmallow_sqlalchemy import ModelSchema
from flask_migrate import Migrate
# DB Config
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://username_db:password_db@localhost/name_of_db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
Migrate(app, db, compare_type=True)
# Model
class Todo(db.Model):
__tablename__ = "todos"
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(20))
todo_description = db.Column(db.String(100))
def create(self):
db.session.add(self)
db.session.commit()
return self
def __init__(self, title, todo_description):
self.title = title
self.todo_description = todo_description
def __repr__(self):
return f"{self.id}"
db.create_all()
class TodoSchema(ModelSchema):
class Meta(ModelSchema.Meta):
model = Todo
sqla_session = db.session
id = fields.Number(dump_only=True)
title = fields.String(required=True)
todo_description = fields.String(required=True)
@app.route('/api/v1/todo-list', methods=['GET'])
def index():
get_todos = Todo.query.all()
todo_schema = TodoSchema(many=True)
todos = todo_schema.dump(get_todos)
return make_response(jsonify({"todos": todos}))
@app.route('/api/v1/todo-detail/<id>', methods=['GET'])
def get_todo_by_id(id):
get_todo = Todo.query.get(id)
todo_schema = TodoSchema()
todo = todo_schema.dump(get_todo)
return make_response(jsonify({"todo": todo}))
@app.route('/api/v1/todo/<id>', methods=['PUT'])
def update_todo_by_id(id):
data = request.get_json()
get_todo = Todo.query.get(id)
if get_todo is None:
return make_response(jsonify("data not found", 404))
if data.get('title'):
get_todo.title = data['title']
if data.get('todo_description'):
get_todo.todo_description = data['todo_description']
db.session.add(get_todo)
db.session.commit()
todo_schema = TodoSchema(only=['id', 'title', 'todo_description'])
todo = todo_schema.dump(get_todo)
return make_response(jsonify({"todo": todo}))
@app.route('/api/v1/todo/<id>', methods=['DELETE'])
def delete_todo_by_id(id):
get_todo = Todo.query.get(id)
db.session.delete(get_todo)
db.session.commit()
return make_response("successfully deleted", 204)
@app.route('/api/v1/todo', methods=['POST'])
def create_todo():
data = request.get_json()
todo_schema = TodoSchema()
todo = todo_schema.load(data)
result = todo_schema.dump(todo.create())
return make_response(jsonify({"todo": result}), 200)
if __name__ == "__main__":
app.run(debug=True)