首页 > 数据库 >flask MongoDB 很好例子

flask MongoDB 很好例子

时间:2022-09-22 23:45:41浏览次数:61  
标签:name author flask MongoDB id api 例子 mongodb book

逻辑图

image

代码

# from collections import namedtuple
from flask import Flask,make_response,jsonify,request
from flask_mongoengine import MongoEngine
# from api_constants import mongodb_user,mongodb_password
# from api_constants import *
# import api_constants

app=Flask(__name__)

database_name = "flaskAndMongo"
mongodb_user='flaskMongo'
mongodb_password='IcJo8rypM6OdPHU6'

# DB_URI = f"mongodb+srv://{api_constants.mongodb_user}:{api_constants.mongodb_password}@cluster0.3kcv6.mongodb.net/{database_name}?retryWrites=true&w=majority"
DB_URI = f"mongodb+srv://{mongodb_user}:{mongodb_password}@cluster0.3kcv6.mongodb.net/{database_name}?retryWrites=true&w=majority"

app.config["MONGODB_HOST"]=DB_URI

db = MongoEngine()
db.init_app(app)

"""
 Sample request body
 {
     "book_id" : 1,
     "name":"A game of thrones",
     "author":"George R Martin"
 }
"""

class Book(db.Document):
    book_id = db.IntField() 
    name = db.StringField()
    author =db.StringField()

    def to_json(self):
        #converts this document to JSON

        return {
            "book_id":self.book_id,
            "name":self.name,
            "author":self.author
        }

"""
api methods

POST /api/db_populate -> populate the db and returns 201 stuccess code (empty response body)

GET /api/books -> returns the details of all books (with code 200 success code)

POST /api/books -> creates a new book and returns 201 success code(empty response body)

GET /api/books3 ->returns the details of book 3 (with 200 success code if document found,404 if not found)

PUT /api/books/3 -> update author and name fields of book3 (with 204 success code)

DELETE /api/books/3 -> Deletes book 3 (with 204 success code)

"""

@app.route('/api/db_populate',methods=['POST'])
def db_populate():
    book1 = Book(
        book_id=1,
        name='A game of thrones',
        author='George Martin')
    book2 = Book(
        book_id=2,
        name='Lord of Rings',
        author='JRR Tolkein')

    book1.save()
    book2.save()

    return make_response("",201)
    

@app.route('/api/books',methods=['GET','POST'])
def api_books(self):
    if request.method == 'GET':
        books=[]
        for book in Book.objects:
            books.append(book)
        return make_response(jsonify(books),200) 
    elif request.method == 'POST':
        """
        Sample request body
        {
            "book_id" : 1,
            "name":"A game of thrones",
            "author":"George R Martin"
        }
        """
        content = request.json #convert to json
        book = Book(book_id=content['book_id'],
        name= content['name'],
        author=content['author'])
        book.save()
        return make_response("",201)
        
    

@app.route('/api/books/<book_id>',methods=['GET','PUT','DELETE'])
def api_each_book(book_id):
    if request.method == 'GET':
        book_obj = Book.objects(book_id=book_id).first()
        if book_obj:
            return make_response(jsonify(book_obj),200)
        else:
            return make_response("",404)
    elif request.method == 'PUT':
         """
        Sample request body
        {
            "book_id" : 1,
            "name":"A game of thrones",
            "author":"George R Martin"
        }
        """
         content = request.json #converts json data to dictionary
         book_obj = Book.objects(book_id=book_id).first()
         book_obj.update(author=content['author'] , name = content['name'])
         return make_response("",204)

    elif request.method == 'DELETE':
        book_obj = Book.objects(book_id=book_id).first()
        book_obj.delete()
        return make_response("",204)

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

标签:name,author,flask,MongoDB,id,api,例子,mongodb,book
From: https://www.cnblogs.com/zhuoss/p/16721224.html

相关文章

  • Flask学习笔记(二)-request请求对象+flask解析http请求数据
    一、flask请求对象requestrequest是flask框架的全局对象,你可以通过它来获得当前进入的请求数据,如果是在多线程环境下,flask可以保证你所使用的request对象就是当前这个线程......
  • Flask 学习-73.Flask-SQLAlchemy 分页查询paginate
    前言Flask-SQLAlchemy提供了一个分页查询方法paginate(),方便我们实现在后端查询分页。分页查询在django框架里面有个rest_framework.pagination分页器,只需简单的配......
  • Golang 使用 MongoDB 报错
    在使用MongoDB时,URI格式一般为:连接URImongodb://用户名:密码@127.0.0.1:27017//等同于mongodb://用户名:密码@127.0.0.1:27017/admin如果不指定数据库名,默认使......
  • Flask 学习-72.Flask-RESTX 自定义输出日期格式
    前言DateTime类型可以支持2种时间格式RFC822和ISO8601,如果需要输出自己想要的格式,需要自定义日期类型。日期格式DateTime类型可以支持2种时间格式RFC822和ISO......
  • mongodb学习经验
    1、ObjectId与String相互转换ObjectId类型—→String类型这个非常简单,直接强制类型转换就可以了_id=str(ObjectId('类型'))String类型—→ObjectId类型fromb......
  • Flask 学习-1.简介与环境准备
    前言Flask是由python开发的轻量的web框架,小巧,灵活,一个脚本就可以启动一个web项目,上手非常容易。Flask和Django框架对比Django:大而全,有一套完整的框架,但是耦合性高......
  • Flask 学习-71.Flask-RESTX 枚举类型Enum字段
    前言model中有枚举类型字段使用示例模型设计classTeachers(db.Model):__tablename__='teacher'#数据库表名id=db.Column(db.Integer,primary_key=T......
  • Node.js 的学习(四)分别连接MongoDB与MySQL数据库,实现增删查改功能
    一、Node.js访问MongoDB数据库MongoDB对许多平台都提供驱动可以访问数据库,如C#、Java、Node.js等。1.1、安装MongoDB访问驱动命令如下:全局安装驱动:npminstallmon......
  • fastapi使用mongodb的小demo
    关系图main.py#@bekbrace#FARMSTACKTutorial-Sunday13.06.2021fromfastapiimportFastAPI,HTTPExceptionfrommodelimportTodofromdatabaseimpor......
  • mongoDB 指令
    显示已有数据库显示当前所在位置切换到某一数据库没有则自动创建插入一条数据插入多条数据删除一条数据删除所有数据更新数据查找所有集合内数据删除一......