使用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
相关推荐
细节控菜鸡几秒前
【2025最新】ArcGIS for JS 范围裁剪(只保留特定区域显示),实现精准地理范围聚焦
开发语言·javascript·arcgis
CodeCraft Studio8 分钟前
Excel处理控件Aspose.Cells教程:使用 Python 将 HTML 转换为 Excel
python·html·excel·aspose·aspose.cells·html转excel
一根甜苦瓜15 分钟前
Go语言Slice的一道骚题
开发语言·后端·golang
驰羽23 分钟前
[GO]Go语言泛型详解
开发语言·golang·xcode
NPE~23 分钟前
[手写系列]Go手写db — — 第五版(实现数据库操作模块)
开发语言·数据库·后端·golang·教程·手写系列·手写数据库
润 下24 分钟前
C语言——深入解析C语言指针:从基础到实践从入门到精通(二)
c语言·开发语言·经验分享·笔记·学习·程序人生
王中阳Go31 分钟前
Python 的 PyPy 能追上 Go 的性能吗?
后端·python·go
Goboy40 分钟前
控制仙术流程 - 抉择与循环的艺术
后端·python
布伦鸽42 分钟前
C# WPF DataGrid使用Observable<Observable<object>类型作为数据源
开发语言·c#·wpf
麦麦大数据1 小时前
F024 vue+flask电影知识图谱推荐系统vue+neo4j +python实现
vue.js·python·flask·知识图谱·推荐算法·电影推荐