zoukankan      html  css  js  c++  java
  • Python Mongodb接口

    Python Mongodb接口

    MongoDB 是一个基于分布式文件存储的数据库。由 C++ 语言编写。旨在为 WEB 应用提供可扩展的高性能数据存储解决方案。

    同时,MongoDB 是一个介于关系数据库和非关系数据库之间的产品,是NoSQL的优秀实现。

    本文记录使用PyMongo模块,用Python调用MongoDB

    工具类实现

    from pymongo import MongoClient
    
    mongodb_name = 'dev_map'
    client = MongoClient("mongodb://localhost:27017")
    mongua = client[mongodb_name]
    
    
    def timestamp(cls):
        import time
        return int(time.time())
    
    
    class ModelUtil(): 
    
        @classmethod
        def add(cls, table_name, item):
            table = mongua[table_name]
            item["deleted"] = False
            ts = timestamp()
            item["created_time"] = ts
            item["updated_time"] = ts
            
            table.insert_one(item)
    
        @classmethod
        def delete(cls, table_name, conditions):
            item = cls.query(table_name, conditions)
            item["deleted"] = True
            cls.update(table_name, item)
    
        @classmethod    
        def query(cls, table_name, conditions):
            table = mongua[table_name]
            item = table.find_one(conditions)
            return item
    
        @classmethod
        def exists(cls, table_name, conditions):
            table = mongua[table_name]
            item = table.find_one(conditions)
            return item is not None
    
        @classmethod
        def update(cls, table_name, item):
            table = mongua[table_name]
            item["updated_time"] = timestamp()
            table.save(item)
    

    小结

    使用MongDB,一方面可以像表格一样访问数据集合,另一方面,条目的类型可以是类似JSON的非结构化数据,而且正好对应Python中的dict,因此使用及其方便

  • 相关阅读:
    playbook实现httpd服务安装与配置
    Ansible介绍与安装使用
    Servlet 连接mysql数据库
    day04作业
    day03python作业
    正式课第一天作业
    函数
    周作业
    数据类型
    day03作业
  • 原文地址:https://www.cnblogs.com/fanghao/p/8972239.html
Copyright © 2011-2022 走看看