In a simple REST service in the last article, our data is stored in the file. This can be cumbersome, every request needs to be read, file-writing, etc. A better way is to use a database (MongoDB)

MongoDB is a popular database, but unlike other databases it’s classified as a NoSQL database program (MongoDB uses JSON-like documents with schema).

Related course: Python Flask: Create Web Apps with Flask

Creating data models

Models

Now that we want to use the database to save data, we can use the native pymongo to operate MongoDB, but here we need to simplify our operations, so we need to create data models.

The main function of the data model is to show which fields our data contains, what type each field is, what is the attribute (unique, or one of several fixed values), and so on.This can help us to know the information of our data at all times when operating data, even if we don’t look at the data in the database.

Here we are introducing the Flask extension of the MongoDB: MongoEngine. You can use MongoEngine independently without relying on the Flask, but you can use it in combination with Flask.

To use MongoEngine in Flask, first we need to configure MongoDB’s information in Flask before we initialize the MongoEngine with our server, so that we connect the database and the server, which can be said in code:

1
2
3
4
5
6
7
app.config['MONGODB_SETTINGS'] = {
'db': 'your_database',
'host': 'localhost',
'port': 27017
}
db = MongoEngine()
db.init_app(app)

After you configure the mongodb information, you can create a data model using MongoEngine.

We create a model with only two fields, name and email:

1
2
3
class User(db.Document):
name = db.StringField()
email = db.StringField()

In this way, our data model is created, and the entire complete code is:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#!/usr/bin/env python
# encoding: utf-8
from flask import Flask
from flask_mongoengine import MongoEngine

app = Flask(__name__)

app.config['MONGODB_SETTINGS'] = {
'db': 'your_database',
'host': 'localhost',
'port': 27017
}
db = MongoEngine()
db.init_app(app)

class User(db.Document):
name = db.StringField()
email = db.StringField()

if __name__ == "__main__":
app.run(debug=True)

Related course: Python Flask: Create Web Apps with Flask

Access data

Queries

The next thing is to explain how the data in the database can be edited and edited through the Model.

It is very simple to query the update and delete of the MongoEngine, such as queries, we can use:

1
User.objects(name="alice").first()

This statement queried the user whose name in the database was alice. Let’s analyze how the statement was queried.

First the User.objects, the User here, we already know that it is our Model, and since User has already been Model, why is it still object-like?

That is because the User is the Model, because the Model itself only represents the data structure.

What does it have to do with our queries?

An object represents all the data for a record in the User table.

In this way, we query a User object.

Add query

The addition of new records is even simpler. For example, I would like to insert a user with a name of laura, email = [email protected], so we can write this:

1
User(name='laura', email='[email protected]').save()

It’s that simple, first of all, we wanted to create a User object, and then call the save method.

Delete query

If we want to delete a record, we need to find this record to be deleted first. It’s like this in MongoEngine, if we want to delete a record, we want to find it and use the query:

1
user = User.objects(name="alice").first()

Once found, it is easy to invoke the delete method to:

1
user.delete()

In this way, we will delete the user alice.

Update

As with updating and deleting, if we need to update a record, we also need to find him first, assuming we need to update laura’s mailbox to: laura @outlook.com, so we can write this:

1
2
user = User.objects(name="alice").first()
user.update(email="[email protected]")

The first statement the query, the second statement uses the update method, directly passing the attribute needing to be modified and the changed value as the parameter.

MongoDB example

The complete code is like this, and we know how to use the model to make additions and deletions, and then we apply this knowledge to our REST service, and the code after rewriting is as follows:

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
#!/usr/bin/env python
# encoding: utf-8
import json
from flask import Flask, request, jsonify
from flask_mongoengine import MongoEngine

app = Flask(__name__)
app.config['MONGODB_SETTINGS'] = {
'db': 'your_database',
'host': 'localhost',
'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=['PUT'])
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=['POST'])
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)

The script uses all of the CRUD methods we introduced.

Related course: Python Flask: Create Web Apps with Flask