使用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
相关推荐
蓝纹绿茶5 分钟前
Python程序使用了Ffmpeg,结束程序后,文件夹中仍然生成音频、视频文件
python·ubuntu·ffmpeg·音视频
mahuifa13 分钟前
OpenCV 开发 -- 图像基本处理
人工智能·python·opencv·计算机视觉
土了个豆子的21 分钟前
03.缓存池
开发语言·前端·缓存·visualstudio·c#
少男的脸红藏不住心事25 分钟前
GD32入门到实战35--485实现OTA
数据库·mongodb·nosql
_extraordinary_34 分钟前
Java 多线程(一)
java·开发语言
爱喝水的鱼丶42 分钟前
SAP-ABAP: ABAP ASSIGN COMPONENT 语句详解:动态字段符号的利器作用用法示例详解
运维·开发语言·sap·abap·开发经验·动态字段符号
一个java开发1 小时前
distributed.client.Client 用户可调用函数分析
大数据·python
励志不掉头发的内向程序员1 小时前
C++进阶——多态
开发语言·c++·学习
eqwaak01 小时前
Matplotlib 动态显示详解:技术深度与创新思考
网络·python·网络协议·tcp/ip·语言模型·matplotlib
007php0071 小时前
某大厂MySQL面试之SQL注入触点发现与SQLMap测试
数据库·python·sql·mysql·面试·职场和发展·golang