-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.py
59 lines (52 loc) · 1.52 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
import json
from flask import Flask, request, jsonify
from flask_mongoengine import MongoEngine
app = Flask(__name__)
app.config['MONGODB_SETTINGS'] = {
'db': 'test',
'host': '172.17.0.2',
'port': 27017
}
db = MongoEngine()
db.init_app(app)
class User(db.Document):
name = db.StringField()
email = db.StringField()
def to_json(self):
return {"name": self.name,
"email": self.email}
@app.route('/', methods=['GET'])
def query_records():
name = request.args.get('name')
user = User.objects(name=name).first()
if not user:
return jsonify({'error': 'data not found'})
else:
return jsonify(user.to_json())
@app.route('/', methods=['POST'])
def create_record():
record = json.loads(request.data)
user = User(name=record['name'],
email=record['email'])
user.save()
return jsonify(user.to_json())
@app.route('/', methods=['PUT'])
def update_record():
record = json.loads(request.data)
user = User.objects(name=record['name']).first()
if not user:
return jsonify({'error': 'data not found'})
else:
user.update(email=record['email'])
return jsonify(user.to_json())
@app.route('/', methods=['DELETE'])
def delete_record():
record = json.loads(request.data)
user = User.objects(name=record['name']).first()
if not user:
return jsonify({'error': 'data not found'})
else:
user.delete()
return jsonify(user.to_json())
if __name__ == "__main__":
app.run(debug=True, host='0.0.0.0')