使用flask_mongoengine库连接mongo数据库

首先安装flask_mongoengine库:

pip install flask_mongoengine

使用flask_mongoengine库连接mongo数据库_第1张图片

使用Flask框架运行程序

注意:生成的集合名称是类名的小写字母

示例代码:

import datetime

from bson.json_util import dumps
from flask import Flask, Response, request
from flask_mongoengine import MongoEngine

app = Flask(__name__)
db = MongoEngine()


class Movie(db.Document):
    name = db.StringField(required=True, unique=True)
    casts = db.ListField(db.StringField(), required=True)
    genres = db.ListField(db.StringField(), required=True)
    created_at = db.DateTimeField(default=datetime.datetime.utcnow)


@app.route('/movies')
def get_movies():
    movies = Movie.objects()
    movies_list = []
    for movie in movies:
        movie_dict = movie.to_mongo().to_dict()
        movie_dict['created_at'] = movie.created_at.isoformat()
        movies_list.append(movie_dict)
    movies_json = dumps(movies_list)
    return Response(movies_json, mimetype="application/json", status=200)


@app.route('/movies', methods=['POST'])
def add_movie():
    body = request.get_json()
    movie = Movie(**body).save()
    id = movie.id
    return {'id': str(id)}, 200


if __name__ == '__main__':
    app.config['MONGODB_SETTINGS'] = {
        'host': 'mongodb://root:[email protected]:27017/test-movie?authSource=admin&retryWrites=true&w=majority'
    }

    db.init_app(app)
    app.run()

程序运行后,使用postman工具多次发起post请求往数据库写数据:

使用flask_mongoengine库连接mongo数据库_第2张图片

 然后在网页上执行get请求:

使用flask_mongoengine库连接mongo数据库_第3张图片

 查看数据库数据生成情况:

使用flask_mongoengine库连接mongo数据库_第4张图片

使用flask_mongoengine库连接mongo数据库_第5张图片

上述程序启动后,使用脚本生成大量的数据:

import requests
import json

url = "http://127.0.0.1:5000/movies"
headers = {
  'Content-Type': 'application/json'
}
for i in range(5, 100):
    payload = json.dumps({
      "name": f"dgw{i}",
      "casts": [
        f"aaa{i}",
        f"bbb{i}"
      ],
      "genres": [
        f"ccc{i}",
        f"ddd{i}"
      ]
    })

    response = requests.request("POST", url, headers=headers, data=payload)

    print(response.text)

使用flask_mongoengine库连接mongo数据库_第6张图片

你可能感兴趣的:(Mongodb数据库,flask,python,后端)