首页 > 解决方案 > 如何使用邮递员中的请求表单将数据发送到 mongodb compass?

问题描述

from flask import Flask, Response, request
import json
import pymongo

app = Flask(__name__)


try:
    #connect to mongo
    mongo = pymongo.MongoClient(host="localhost", 
    port=27017, 
    serverSelectionTimeoutMS = 1000) #serverSelec.... will allow us to catch exception
    
    #creating database variable, connecting to mongo client and the database we want to use
    db = mongo.cloud_ninja
    mongo.server_info()#trigger exception if cannot connect to database
except:
    print("ERROR = Cannot connect to db")

@app.route("/users", methods = ['POST'])
def created_user():
    try:
        intern = {"firstname" : request.form["name"], "lastname" : request.form["lastname"]}
        #intern = {"firstname" : "Dave Lyndrex", "lastname" : "Millan"}
        dbResponse = db.interns.insert_one(intern)#get a response, from the db(cloud_ninja). interns(collection)-it will create automatically... and insert the intern which is a json object
        print(dbResponse.inserted_id) 
     #   for attr in dir(dbResponse):#key that we use from the db response
      #      print(attr) 
        return Response(
            response= json.dumps({"Message": "user created",
             "id":f"{dbResponse.inserted_id}"
             }), #i will tell the client that I will pass a data
            status=200,
            mimetype="aplication.json" #to pass a json data
        )
    except Exception as ex:
        print(ex)
   
    
if __name__ == "__main__":
    app.run(port=80, debug=True)

标签: pythonpymongoflask-restfulmongodb-compass

解决方案


推荐阅读