/
app.py
94 lines (73 loc) · 2.85 KB
/
app.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
import json
from flask import Flask, request, jsonify, render_template
from flask_script import Manager
from flask_migrate import Migrate, MigrateCommand
from flask_cors import CORS
from models import db, Contact
app = Flask(__name__)
app.url_map.strict_slashes = False
app.config['DEBUG'] = True
app.config['ENV'] = 'development'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///database.db'
db.init_app(app)
Migrate(app, db)
manager = Manager(app)
manager.add_command("db", MigrateCommand)
@app.route('/')
def root():
return render_template('index.html')
@app.route("/api/contacts", methods=['GET', 'POST'])
@app.route("/api/contacts/<int:id>", methods=['GET', 'PUT', 'DELETE'])
@app.route("/api/contacts/name/<name>", methods=['GET'])
def contacts(id = None, name = None):
if request.method == 'GET':
if name is not None:
#contact = Contact.query.filter_by(name="Paul Guzmán").first()
#contacts = Contact.query.filter(Contact.name.like("%"+name+"%")).all()
#print(contact)
return jsonify(contact.serialize()), 200
if id is not None:
contact = Contact.query.get(id)
if contact:
return jsonify(contact.serialize()), 200
else:
return jsonify({"msg": "Contact not found"}), 404
else:
contacts = Contact.query.all()
contacts = list(map(lambda contact: contact.serialize(), contacts))
return jsonify(contacts), 200
if request.method == 'POST':
name = request.json.get("name", None)
phone = request.json.get("phone", None)
if not name:
return jsonify({"msg": "Name is required"}), 400
if not phone:
return jsonify({"msg": "Phone is required"}), 400
contact = Contact()
contact.name = name
contact.phone = json.dumps(phone)
contact.save()
return jsonify(contact.serialize()), 201
if request.method == 'PUT':
name = request.json.get("name", None)
phone = request.json.get("phone", None)
if not name:
return jsonify({"msg": "Name is required"}), 400
if not phone:
return jsonify({"msg": "Phone is required"}), 400
contact = Contact.query.get(id)
if not contact:
return jsonify({"msg": "Contact not found"}), 404
contact.name = name
contact.phone = json.dumps(phone)
contact.update()
return jsonify(contact.serialize()), 200
if request.method == 'DELETE':
contact = Contact.query.get(id)
if not contact:
return jsonify({"msg": "Contact not found"}), 404
contact.delete()
return jsonify({"success": "Contact was deleted"}), 200
if __name__ == "__main__":
manager.run()