DRYな備忘録

Don't Repeat Yourself.

PythonでmongoDBにアクセス【pymongo】【pip】【Python2.6.6】

Goal

  • pythonファイルからmongoDBにwrite
  • pythonファイルからmongoDBをread

Reference

Log

pymongoってのがあるっぽい

% pip search pymongo
pymongo                   - Python driver for MongoDB <http://www.mongodb.org>
kale                      - Tiny PyMongo model layer
Flask-PyMongo             - PyMongo support for Flask applications
mongate                   - A client library for Sleepy Mongoose that provides the same interface as Pymongo. With support for batch operations.
ScrapyMongoDB             - Scrapy pipeline which allow you to store scrapy items in MongoDB database.
mongo                     - Minimalistic pymongo object wrapper
mogo                      - Simple PyMongo "schema-less" object wrapper
pymongo-bongo             - Sytax sugar for PyMongo and MongoDB <http://www.mongodb.org>
PyMongo-Frisk             - Wrapper for PyMongo Connection that offers additional application level monitoring. When connecting to multiple MongoDB servers, allows you to verify
                            connectivity to MongoDB slave servers.
pymw                      - This is a high abastract architecture with pymongo
MongoBit                  - Simple pymongo orm
mongomock                 - Fake pymongo stub for testing simple MongoDB-dependent code
kpages                    - kpages is helper for you web app ,active on tornado, pymongo,redis
pymongolab                - PyMongoLab is a client library for MongoLab REST API
IPyMongo                  - IPython extension and wrapper for using with MongoDB
pymongo-pubsub            - A publish-subscribe pattern implementation for pymongo
pyliquib                  - A MongoDB migration tool with pymongo inspired by Liquibase
conmongo                  - A Flask microplugin based on pymongo
pymongo_hadoop            - UNKNOWN
pymongo3                  - Python driver for MongoDB <http://www.mongodb.org>
CherrypyMongoDB           - MongoDb Tool For Cherrypy
%
# あーんこれの1番上か
% sudo pip install pymongo
[sudo] password for otiai10:
Downloading/unpacking pymongo
  Downloading pymongo-2.5.2.tar.gz (303kB): 303kB downloaded
  Running setup.py egg_info for package pymongo
Installing collected packages: pymongo
  Running setup.py install for pymongo
    building 'bson._cbson' extension
    gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fPIC -Ibson -I/usr/include/python2.6 -c bson/_cbsonmodule.c -o build/temp.linux-i686-2.6/bson/_cbsonmodule.o
    gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fPIC -Ibson -I/usr/include/python2.6 -c bson/time64.c -o build/temp.linux-i686-2.6/bson/time64.o
    gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fPIC -Ibson -I/usr/include/python2.6 -c bson/buffer.c -o build/temp.linux-i686-2.6/bson/buffer.o
    gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fPIC -Ibson -I/usr/include/python2.6 -c bson/encoding_helpers.c -o build/temp.linux-i686-2.6/bson/encoding_helpers.o
    gcc -pthread -shared -Wl,-O1 -Wl,-Bsymbolic-functions build/temp.linux-i686-2.6/bson/_cbsonmodule.o build/temp.linux-i686-2.6/bson/time64.o build/temp.linux-i686-2.6/bson/buffer.o build/temp.linux-i686-2.6/bson/encoding_helpers.o -o build/lib.linux-i686-2.6/bson/_cbson.so
    building 'pymongo._cmessage' extension
    gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fPIC -Ibson -I/usr/include/python2.6 -c pymongo/_cmessagemodule.c -o build/temp.linux-i686-2.6/pymongo/_cmessagemodule.o
    gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fPIC -Ibson -I/usr/include/python2.6 -c bson/buffer.c -o build/temp.linux-i686-2.6/bson/buffer.o
    gcc -pthread -shared -Wl,-O1 -Wl,-Bsymbolic-functions build/temp.linux-i686-2.6/pymongo/_cmessagemodule.o build/temp.linux-i686-2.6/bson/buffer.o -o build/lib.linux-i686-2.6/pymongo/_cmessage.so
Successfully installed pymongo
Cleaning up...
%

# 確認

% pip list | grep pymongo
pymongo (2.5.2)
% python
Python 2.6.6 (r266:84292, Dec 27 2010, 00:02:40)
[GCC 4.4.5] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import pymongo
>>> exit()
%

# 入ってるしimportできる

ではミニマムなアプリケーション書く

構成

.
|-- minimum.py
`-- system
    |-- __init__.py
    `-- conf.py

1 directory, 3 files

minimum.py

from pymongo import MongoClient
from system import conf

client = MongoClient(conf.mongo['host'],conf.mongo['port'])

db = client.test
collection = db.hoge

def find_all_test():
  print 'found >>>'
  for m in collection.find():
    print m
  return collection.find()

def find_with_condition_test(condi):
  print 'found by condition >>>'
  for m in collection.find(condi):
    print m
  return collection.find(condi)

def insert_test(k_v_obj):
  print 'inserted >>>'
  res = collection.insert(k_v_obj)
  print res
  return res

def update_test(mongo_obj):
  print 'updated >>>'
  res = collection.save(mongo_obj)
  print res
  return res

def initialize():
  print 'initialize test!!'
  all_member = collection.find()
  for m in all_member:
    print collection.remove(m)

if __name__ == '__main__':

  initialize()

  # insert new
  rit = {'name' : 'Ritsu', 'birthday' : '08-21'}
  mio = {'name' : 'Mio',   'birthday' : '01-15'}
  insert_test(rit)
  insert_test(mio)

  find_all_test()

  # insert new
  yui = {'name' : 'Yui',   'birthday' : '11-27'}
  mug = {'name' : 'Mugi',  'birthday' : '07-02'}
  azu = {'name' : 'Azu',   'birthday' : '11-11'}
  insert_test(yui)
  insert_test(mug)
  insert_test(azu)

  found_member = find_all_test()

  for m in found_member:
    if m['name'] == 'Ritsu':
      m['is_my_wife'] = True
      # update
      update_test(m)

  find_all_test()

  # find by condition
  find_with_condition_test({'is_my_wife':True})

で、その結果

f:id:otiai10:20130714144707p:plain

is_my_wifeのようにプロパティをカジュアルに追加できるの勝手が良いですね

memo

秘書たんのDBがmongodbなので。バックエンドをNode.jsからPythonに置き換えるプロジェクト進行中