forked from FrancescoXX/flask-crud-live
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathapp.py
85 lines (73 loc) · 2.63 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
from flask import Flask, request, jsonify, make_response
from flask_sqlalchemy import SQLAlchemy
from os import environ
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = environ.get('DB_URL')
db = SQLAlchemy(app)
class User(db.Model):
__tablename__ = 'users'
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True, nullable=False)
email = db.Column(db.String(120), unique=True, nullable=False)
def json(self):
return {'id': self.id,'username': self.username, 'email': self.email}
db.create_all()
#create a test route
@app.route('/test', methods=['GET'])
def test():
return make_response(jsonify({'message': 'test route'}), 200)
# create a user
@app.route('/users', methods=['POST'])
def create_user():
try:
data = request.get_json()
new_user = User(username=data['username'], email=data['email'])
db.session.add(new_user)
db.session.commit()
return make_response(jsonify({'message': 'user created'}), 201)
except e:
return make_response(jsonify({'message': 'error creating user'}), 500)
# get all users
@app.route('/users', methods=['GET'])
def get_users():
try:
users = User.query.all()
return make_response(jsonify([user.json() for user in users]), 200)
except e:
return make_response(jsonify({'message': 'error getting users'}), 500)
# get a user by id
@app.route('/users/<int:id>', methods=['GET'])
def get_user(id):
try:
user = User.query.filter_by(id=id).first()
if user:
return make_response(jsonify({'user': user.json()}), 200)
return make_response(jsonify({'message': 'user not found'}), 404)
except e:
return make_response(jsonify({'message': 'error getting user'}), 500)
# update a user
@app.route('/users/<int:id>', methods=['PUT'])
def update_user(id):
try:
user = User.query.filter_by(id=id).first()
if user:
data = request.get_json()
user.username = data['username']
user.email = data['email']
db.session.commit()
return make_response(jsonify({'message': 'user updated'}), 200)
return make_response(jsonify({'message': 'user not found'}), 404)
except e:
return make_response(jsonify({'message': 'error updating user'}), 500)
# delete a user
@app.route('/users/<int:id>', methods=['DELETE'])
def delete_user(id):
try:
user = User.query.filter_by(id=id).first()
if user:
db.session.delete(user)
db.session.commit()
return make_response(jsonify({'message': 'user deleted'}), 200)
return make_response(jsonify({'message': 'user not found'}), 404)
except e:
return make_response(jsonify({'message': 'error deleting user'}), 500)