使用python搭建mongodb操作服务

搭建python服务

python 复制代码
from flask import Flask, request, jsonify
from pymongo import MongoClient

app = Flask(__name__)

# 配置MongoDB连接
client = MongoClient('mongodb://localhost:27017/')

def get_collection(db_name, collection_name):
    db = client[db_name]
    collection = db[collection_name]
    return collection

# 插入一条记录
@app.route('/insert_one', methods=['POST'])
def insert_one():
    data = request.json
    db_name = data.pop('db')
    collection_name = data.pop('collection')
    collection = get_collection(db_name, collection_name)
    result = collection.insert_one(data)
    return jsonify({'inserted_id': str(result.inserted_id)})

# 插入多条记录
@app.route('/insert_many', methods=['POST'])
def insert_many():
    data = request.json
    db_name = data.pop('db')
    collection_name = data.pop('collection')
    documents = data.pop('documents')
    collection = get_collection(db_name, collection_name)
    result = collection.insert_many(documents)
    return jsonify({'inserted_ids': [str(id) for id in result.inserted_ids]})

# 查找一条记录
@app.route('/find_one', methods=['GET'])
def find_one():
    db_name = request.args.get('db')
    collection_name = request.args.get('collection')
    query = request.args.to_dict()
    query.pop('db')
    query.pop('collection')
    collection = get_collection(db_name, collection_name)
    result = collection.find_one(query)
    if result:
        result['_id'] = str(result['_id'])
    return jsonify(result)

# 查找多条记录
@app.route('/find', methods=['GET'])
def find():
    db_name = request.args.get('db')
    collection_name = request.args.get('collection')
    query = request.args.to_dict()
    query.pop('db')
    query.pop('collection')
    collection = get_collection(db_name, collection_name)
    results = collection.find(query)
    result_list = []
    for result in results:
        result['_id'] = str(result['_id'])
        result_list.append(result)
    return jsonify(result_list)

# 统计记录数
@app.route('/count', methods=['GET'])
def count():
    db_name = request.args.get('db')
    collection_name = request.args.get('collection')
    query = request.args.to_dict()
    query.pop('db')
    query.pop('collection')
    collection = get_collection(db_name, collection_name)
    count = collection.count_documents(query)
    return jsonify({'count': count})

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

启用python正式服务

  • 首先安装Gunicorn:

    bash 复制代码
    pip install gunicorn
  • 运行你的Flask应用:

    bash 复制代码
    gunicorn -w 4 -b 0.0.0.0:8000 app:app

    这里,-w 4 表示使用4个工作进程,-b 0.0.0.0:8000 表示绑定到所有网络接口的8000端口,app:app 表示Flask应用的入口点(文件名是app.py,里面的Flask实例名称是app)。

测试代码

bash 复制代码
curl -X POST -H "Content-Type: application/json" -d '{"db": "your_database", "collection": "your_collection", "name": "John Doe", "age": 30}' http://localhost:8000/insert_one
相关推荐
云上空2 分钟前
C#初级知识总结
开发语言·c#
Ankie Wan6 分钟前
notepad++技巧:查找和替换:扩展 or 正则表达式
python·正则表达式·notepad++
带娃的IT创业者6 分钟前
《AI大模型趣味实战》智能Agent和MCP协议的应用实例:搭建一个能阅读DOC文件并实时显示润色改写过程的Python Flask应用
人工智能·python·flask
JavaEdge在掘金13 分钟前
启动nginx报错,80 failed (97: Address family not supported by protocol)
python
纪元A梦20 分钟前
华为OD机试真题——绘图机器(2025A卷:100分)Java/python/JavaScript/C++/C/GO最佳实现
java·javascript·c++·python·华为od·go·华为od机试题
钢铁男儿23 分钟前
C# 深入理解类:面向对象编程的核心数据结构
开发语言·数据结构·c#
程序员小远32 分钟前
接口测试和单元测试详解
自动化测试·软件测试·python·测试工具·单元测试·测试用例·接口测试
Tech Synapse41 分钟前
电商商品推荐系统实战:基于TensorFlow Recommenders构建智能推荐引擎
人工智能·python·tensorflow
聿小翼1 小时前
selenium-wire 与 googletrans 的爱恨情仇
python
咖啡调调。1 小时前
模板引擎语法-算术运算
python·django·sqlite