SlideShare a Scribd company logo
and Python

Mike Dirolf (@mdirolf)
PyMongo
(see also: MongoKit, Ming, MongoEngine, etc.)
API Basics
>>> from pymongo import Connection

>>> db = Connection().test_db

>>> db.test.insert({"x": 1})
ObjectId('4bdafd07e6fb1b351e000000')

>>> db.test.find_one()
{u'x': 1, u'_id':
ObjectId('4bdafd07e6fb1b351e000000')}
GridFS (setup)

>>>   from pymongo import Connection
>>>   import gridfs
>>>
>>>   db = Connection().gridfs_example
>>>   fs = gridfs.GridFS(db)
GridFS (before)
>>>   f = fs.open("hello.txt", "w")
>>>   f.write("hello ")
>>>   f.write("world")
>>>   f.close()

>>> g = fs.open("hello.txt")
>>> g.read()
'hello world'
>>> g.close()
GridFS (after)

>>> fs.put(“hello world”)

>>> file_id = fs.put("hello world")
>>> fs.get(file_id).read()
'hello world'
GridFS (after)

>>> myfile = fs.new_file(location=[-74, 40.74])
>>> myfile.write("hello ")
>>> myfile.write("world,")
>>> myfile.writelines([" and have a ", "good day!"])
>>> myfile.close()
>>> out = fs.get(myfile._id)
>>> out.read()
'hello world, and have a good day!'
>>> out.location
[-74, 40.740000000000002]
Commands (before)

>>> db.command({“buildinfo”: 1})

>>> db.command({“collstats”: collection})

>>> db.command(SON([(“filemd5”, object_id),
                    (“root”, file_root)]))
Commands (after)

>>> db.command(“buildinfo”)

>>> db.command(“collstats”, collection)

>>> db.command(“filemd5”, object_id,
               root=file_root)
Stored JS

>>> db.system_js.add1 = "function (x) { return x + 1; }"

>>> db.system_js.add1(5)
6.0

>>> del db.system_js.add1




     http://dirolf.com/2010/04/05/stored-javascript-in-mongodb-and-pymongo.html
PyMongo + mod_wsgi
Get involved!
http://github.com/mongodb/mongo-python-driver



and check out the Python workshop after lunch
?
Yes...
 ...but also sometimes no
Similar to                            +
• A lot of Django doesn’t depend on django.db:
 • URL dispatch, templates, I18N, caching, etc.
• Some things do:
 • Models
 • Auth
 • Sessions
 • Admin
settings.py
DATABASE_ENGINE = ''
DATABASE_NAME = ''
DATABASE_USER = ''
DATABASE_PASSWORD = ''
DATABASE_HOST = ''
DATABASE_PORT = ''

MIDDLEWARE_CLASSES = (
  'django.middleware.common.CommonMiddleware',
# 'django.contrib.sessions.middleware.SessionMiddleware',
# 'django.contrib.auth.middleware.AuthenticationMiddleware',
)

INSTALLED_APPS = (
# 'django.contrib.auth',
  'django.contrib.contenttypes',
# 'django.contrib.sessions',
  'django.contrib.sites',
)
Representing a Poll

{'question': 'Do MongoDB + Django <3 each other?',
 'pub_date': datetime.datetime(2010, 1, 21),
 'choices': [{'votes': 35, 'choice': 'Yes!'},
         {'votes': 2, 'choice': 'No...'}]}
models.py (PyMongo)
def save_poll(question):
  return db.polls.insert({"question": question,
                  "pub_date": datetime.utcnow()})

def all_polls():
  return db.polls.find()

def add_choice(poll_id, choice):
  db.polls.update({"_id": poll_id},
            {"$push": {"choices": {"choice": choice,
                            "votes": 0}}})

def add_vote(poll_id, choice):
  db.polls.update({"_id": poll_id},
            {"$inc": {"choices.%d.votes" % choice: 1}})
                                              http://api.mongodb.org/python
models.py (MongoKit)

class Poll(mongokit.Document):
   structure = {"question": str,
            "pub_date": datetime,
            "choices": [{"choice": str,
                    "votes": int}]}
   required_fields = ["question"]
   default_values = {"pub_date": datetime.utcnow}




                              http://bytebucket.org/namlook/mongokit
models.py (Ming)
class Poll(ming.Document):

  class __mongometa__:
     session = session
     name = "polls"

  _id = ming.Field(ming.schema.ObjectId)
  question = ming.Field(str, required=True)
  pub_date = ming.Field(datetime.datetime,
           if_missing=datetime.datetime.utcnow)
  choices = ming.Field([{"choice": str,
                 "votes": int}])

                                http://merciless.sourceforge.net/
mango - sessions and auth


•   Full sessions support
•   mango provided User class
    •   supports is_authenticated(), set_password(), etc.




                                   http://github.com/vpulim/mango
mango - sessions and auth


SESSION_ENGINE = 'mango.session'
AUTHENTICATION_BACKENDS = ('mango.auth.Backend',)
MONGODB_HOST = 'localhost'
MONGODB_PORT = None
MONGODB_NAME = 'mydb'




                            http://github.com/vpulim/mango
What about admin?

• No great solution... yet.
• Could replace admin app like mango does
  for sessions / auth
• Or...
Supporting MongoDB
    in django.db

More Related Content

What's hot (20)

ODP
Aggregation Framework in MongoDB Overview Part-1
Anuj Jain
 
PDF
Aggregation Framework MongoDB Days Munich
Norberto Leite
 
PPTX
Back to Basics Webinar 5: Introduction to the Aggregation Framework
MongoDB
 
ODP
Python and MongoDB
Christiano Anderson
 
PDF
MongoDB Aggregation Framework
Caserta
 
PDF
Data Processing and Aggregation with MongoDB
MongoDB
 
KEY
MongoDB Aggregation Framework
Tyler Brock
 
PDF
NOSQL: il rinascimento dei database?
Paolo Bernardi
 
PPTX
Webinaire 2 de la série « Retour aux fondamentaux » : Votre première applicat...
MongoDB
 
PPTX
The Aggregation Framework
MongoDB
 
PDF
Mongodb workshop
Harun Yardımcı
 
PPTX
Back to Basics, webinar 2: La tua prima applicazione MongoDB
MongoDB
 
PPTX
Back to Basics: My First MongoDB Application
MongoDB
 
PDF
20110514 mongo dbチューニング
Yuichi Matsuo
 
PDF
MongoDB dla administratora
3camp
 
PDF
MongoDB World 2019: Exploring your MongoDB Data with Pirates (R) and Snakes (...
MongoDB
 
PPTX
Webinar: Getting Started with MongoDB - Back to Basics
MongoDB
 
PPTX
The Aggregation Framework
MongoDB
 
PDF
Analytics with MongoDB Aggregation Framework and Hadoop Connector
Henrik Ingo
 
PPTX
MongoDB World 2016 : Advanced Aggregation
Joe Drumgoole
 
Aggregation Framework in MongoDB Overview Part-1
Anuj Jain
 
Aggregation Framework MongoDB Days Munich
Norberto Leite
 
Back to Basics Webinar 5: Introduction to the Aggregation Framework
MongoDB
 
Python and MongoDB
Christiano Anderson
 
MongoDB Aggregation Framework
Caserta
 
Data Processing and Aggregation with MongoDB
MongoDB
 
MongoDB Aggregation Framework
Tyler Brock
 
NOSQL: il rinascimento dei database?
Paolo Bernardi
 
Webinaire 2 de la série « Retour aux fondamentaux » : Votre première applicat...
MongoDB
 
The Aggregation Framework
MongoDB
 
Mongodb workshop
Harun Yardımcı
 
Back to Basics, webinar 2: La tua prima applicazione MongoDB
MongoDB
 
Back to Basics: My First MongoDB Application
MongoDB
 
20110514 mongo dbチューニング
Yuichi Matsuo
 
MongoDB dla administratora
3camp
 
MongoDB World 2019: Exploring your MongoDB Data with Pirates (R) and Snakes (...
MongoDB
 
Webinar: Getting Started with MongoDB - Back to Basics
MongoDB
 
The Aggregation Framework
MongoDB
 
Analytics with MongoDB Aggregation Framework and Hadoop Connector
Henrik Ingo
 
MongoDB World 2016 : Advanced Aggregation
Joe Drumgoole
 

Similar to Python Development (MongoSF) (20)

KEY
Inside PyMongo - MongoNYC
Mike Dirolf
 
KEY
MongoDB hearts Django? (Django NYC)
Mike Dirolf
 
KEY
MongoDB at ZPUGDC
Mike Dirolf
 
PPT
Rapid and Scalable Development with MongoDB, PyMongo, and Ming
Rick Copeland
 
PDF
REST Web API with MongoDB
MongoDB
 
PPTX
Rapid and Scalable Development with MongoDB, PyMongo, and Ming
Rick Copeland
 
PPTX
Dev Jumpstart: Build Your First App with MongoDB
MongoDB
 
KEY
MongoDB NYC Python
Mike Dirolf
 
KEY
Round pegs and square holes
Daniel Greenfeld
 
PDF
MongoDB: a gentle, friendly overview
Antonio Pintus
 
PDF
Building your first app with MongoDB
Norberto Leite
 
KEY
MongoDB EuroPython 2009
Mike Dirolf
 
PPTX
Dev Jumpstart: Building Your First App
MongoDB
 
PDF
MongoDB World 2016: From the Polls to the Trolls: Seeing What the World Think...
MongoDB
 
PDF
Pyconie 2012
Yaqi Zhao
 
PDF
Back to Basics 2017: Mí primera aplicación MongoDB
MongoDB
 
PPTX
Ankur py mongo.pptx
Ankur Raina
 
PPT
Allura - an Open Source MongoDB Based Document Oriented SourceForge
Rick Copeland
 
PPT
9. Document Oriented Databases
Fabio Fumarola
 
KEY
MongoDB at RuPy
Mike Dirolf
 
Inside PyMongo - MongoNYC
Mike Dirolf
 
MongoDB hearts Django? (Django NYC)
Mike Dirolf
 
MongoDB at ZPUGDC
Mike Dirolf
 
Rapid and Scalable Development with MongoDB, PyMongo, and Ming
Rick Copeland
 
REST Web API with MongoDB
MongoDB
 
Rapid and Scalable Development with MongoDB, PyMongo, and Ming
Rick Copeland
 
Dev Jumpstart: Build Your First App with MongoDB
MongoDB
 
MongoDB NYC Python
Mike Dirolf
 
Round pegs and square holes
Daniel Greenfeld
 
MongoDB: a gentle, friendly overview
Antonio Pintus
 
Building your first app with MongoDB
Norberto Leite
 
MongoDB EuroPython 2009
Mike Dirolf
 
Dev Jumpstart: Building Your First App
MongoDB
 
MongoDB World 2016: From the Polls to the Trolls: Seeing What the World Think...
MongoDB
 
Pyconie 2012
Yaqi Zhao
 
Back to Basics 2017: Mí primera aplicación MongoDB
MongoDB
 
Ankur py mongo.pptx
Ankur Raina
 
Allura - an Open Source MongoDB Based Document Oriented SourceForge
Rick Copeland
 
9. Document Oriented Databases
Fabio Fumarola
 
MongoDB at RuPy
Mike Dirolf
 
Ad

More from Mike Dirolf (12)

PDF
FrozenRails Training
Mike Dirolf
 
PDF
MongoDB at FrozenRails
Mike Dirolf
 
PDF
Introduction to MongoDB
Mike Dirolf
 
KEY
MongoDB: How it Works
Mike Dirolf
 
KEY
MongoDB at CodeMash 2.0.1.0
Mike Dirolf
 
PDF
MongoDB at RubyConf
Mike Dirolf
 
KEY
MongoDB at RubyEnRails 2009
Mike Dirolf
 
KEY
MongoDB Strange Loop 2009
Mike Dirolf
 
KEY
MongoDB Hadoop DC
Mike Dirolf
 
KEY
MongoDB London PHP
Mike Dirolf
 
KEY
MongoDB SF Python
Mike Dirolf
 
KEY
MongoDB SF Ruby
Mike Dirolf
 
FrozenRails Training
Mike Dirolf
 
MongoDB at FrozenRails
Mike Dirolf
 
Introduction to MongoDB
Mike Dirolf
 
MongoDB: How it Works
Mike Dirolf
 
MongoDB at CodeMash 2.0.1.0
Mike Dirolf
 
MongoDB at RubyConf
Mike Dirolf
 
MongoDB at RubyEnRails 2009
Mike Dirolf
 
MongoDB Strange Loop 2009
Mike Dirolf
 
MongoDB Hadoop DC
Mike Dirolf
 
MongoDB London PHP
Mike Dirolf
 
MongoDB SF Python
Mike Dirolf
 
MongoDB SF Ruby
Mike Dirolf
 
Ad

Recently uploaded (20)

PDF
“Squinting Vision Pipelines: Detecting and Correcting Errors in Vision Models...
Edge AI and Vision Alliance
 
PPTX
Talbott's brief History of Computers for CollabDays Hamburg 2025
Talbott Crowell
 
PDF
NASA A Researcher’s Guide to International Space Station : Fundamental Physics
Dr. PANKAJ DHUSSA
 
PPTX
Role_of_Artificial_Intelligence_in_Livestock_Extension_Services.pptx
DrRajdeepMadavi
 
PPTX
MuleSoft MCP Support (Model Context Protocol) and Use Case Demo
shyamraj55
 
PDF
NASA A Researcher’s Guide to International Space Station : Earth Observations
Dr. PANKAJ DHUSSA
 
PDF
“ONNX and Python to C++: State-of-the-art Graph Compilation,” a Presentation ...
Edge AI and Vision Alliance
 
PDF
Linux schedulers for fun and profit with SchedKit
Alessio Biancalana
 
PDF
How do you fast track Agentic automation use cases discovery?
DianaGray10
 
PDF
What’s my job again? Slides from Mark Simos talk at 2025 Tampa BSides
Mark Simos
 
PPTX
Mastering ODC + Okta Configuration - Chennai OSUG
HathiMaryA
 
PDF
ICONIQ State of AI Report 2025 - The Builder's Playbook
Razin Mustafiz
 
PDF
99 Bottles of Trust on the Wall — Operational Principles for Trust in Cyber C...
treyka
 
PPTX
The Project Compass - GDG on Campus MSIT
dscmsitkol
 
PDF
Bharatiya Antariksh Hackathon 2025 Idea Submission PPT.pdf
ghjghvhjgc
 
PDF
Go Concurrency Real-World Patterns, Pitfalls, and Playground Battles.pdf
Emily Achieng
 
PDF
Modern Decentralized Application Architectures.pdf
Kalema Edgar
 
PDF
NLJUG Speaker academy 2025 - first session
Bert Jan Schrijver
 
PDF
UiPath DevConnect 2025: Agentic Automation Community User Group Meeting
DianaGray10
 
PDF
“NPU IP Hardware Shaped Through Software and Use-case Analysis,” a Presentati...
Edge AI and Vision Alliance
 
“Squinting Vision Pipelines: Detecting and Correcting Errors in Vision Models...
Edge AI and Vision Alliance
 
Talbott's brief History of Computers for CollabDays Hamburg 2025
Talbott Crowell
 
NASA A Researcher’s Guide to International Space Station : Fundamental Physics
Dr. PANKAJ DHUSSA
 
Role_of_Artificial_Intelligence_in_Livestock_Extension_Services.pptx
DrRajdeepMadavi
 
MuleSoft MCP Support (Model Context Protocol) and Use Case Demo
shyamraj55
 
NASA A Researcher’s Guide to International Space Station : Earth Observations
Dr. PANKAJ DHUSSA
 
“ONNX and Python to C++: State-of-the-art Graph Compilation,” a Presentation ...
Edge AI and Vision Alliance
 
Linux schedulers for fun and profit with SchedKit
Alessio Biancalana
 
How do you fast track Agentic automation use cases discovery?
DianaGray10
 
What’s my job again? Slides from Mark Simos talk at 2025 Tampa BSides
Mark Simos
 
Mastering ODC + Okta Configuration - Chennai OSUG
HathiMaryA
 
ICONIQ State of AI Report 2025 - The Builder's Playbook
Razin Mustafiz
 
99 Bottles of Trust on the Wall — Operational Principles for Trust in Cyber C...
treyka
 
The Project Compass - GDG on Campus MSIT
dscmsitkol
 
Bharatiya Antariksh Hackathon 2025 Idea Submission PPT.pdf
ghjghvhjgc
 
Go Concurrency Real-World Patterns, Pitfalls, and Playground Battles.pdf
Emily Achieng
 
Modern Decentralized Application Architectures.pdf
Kalema Edgar
 
NLJUG Speaker academy 2025 - first session
Bert Jan Schrijver
 
UiPath DevConnect 2025: Agentic Automation Community User Group Meeting
DianaGray10
 
“NPU IP Hardware Shaped Through Software and Use-case Analysis,” a Presentati...
Edge AI and Vision Alliance
 

Python Development (MongoSF)

  • 2. PyMongo (see also: MongoKit, Ming, MongoEngine, etc.)
  • 3. API Basics >>> from pymongo import Connection >>> db = Connection().test_db >>> db.test.insert({"x": 1}) ObjectId('4bdafd07e6fb1b351e000000') >>> db.test.find_one() {u'x': 1, u'_id': ObjectId('4bdafd07e6fb1b351e000000')}
  • 4. GridFS (setup) >>> from pymongo import Connection >>> import gridfs >>> >>> db = Connection().gridfs_example >>> fs = gridfs.GridFS(db)
  • 5. GridFS (before) >>> f = fs.open("hello.txt", "w") >>> f.write("hello ") >>> f.write("world") >>> f.close() >>> g = fs.open("hello.txt") >>> g.read() 'hello world' >>> g.close()
  • 6. GridFS (after) >>> fs.put(“hello world”) >>> file_id = fs.put("hello world") >>> fs.get(file_id).read() 'hello world'
  • 7. GridFS (after) >>> myfile = fs.new_file(location=[-74, 40.74]) >>> myfile.write("hello ") >>> myfile.write("world,") >>> myfile.writelines([" and have a ", "good day!"]) >>> myfile.close() >>> out = fs.get(myfile._id) >>> out.read() 'hello world, and have a good day!' >>> out.location [-74, 40.740000000000002]
  • 8. Commands (before) >>> db.command({“buildinfo”: 1}) >>> db.command({“collstats”: collection}) >>> db.command(SON([(“filemd5”, object_id), (“root”, file_root)]))
  • 9. Commands (after) >>> db.command(“buildinfo”) >>> db.command(“collstats”, collection) >>> db.command(“filemd5”, object_id, root=file_root)
  • 10. Stored JS >>> db.system_js.add1 = "function (x) { return x + 1; }" >>> db.system_js.add1(5) 6.0 >>> del db.system_js.add1 http://dirolf.com/2010/04/05/stored-javascript-in-mongodb-and-pymongo.html
  • 13. ?
  • 14. Yes... ...but also sometimes no
  • 15. Similar to + • A lot of Django doesn’t depend on django.db: • URL dispatch, templates, I18N, caching, etc. • Some things do: • Models • Auth • Sessions • Admin
  • 16. settings.py DATABASE_ENGINE = '' DATABASE_NAME = '' DATABASE_USER = '' DATABASE_PASSWORD = '' DATABASE_HOST = '' DATABASE_PORT = '' MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', # 'django.contrib.sessions.middleware.SessionMiddleware', # 'django.contrib.auth.middleware.AuthenticationMiddleware', ) INSTALLED_APPS = ( # 'django.contrib.auth', 'django.contrib.contenttypes', # 'django.contrib.sessions', 'django.contrib.sites', )
  • 17. Representing a Poll {'question': 'Do MongoDB + Django <3 each other?', 'pub_date': datetime.datetime(2010, 1, 21), 'choices': [{'votes': 35, 'choice': 'Yes!'}, {'votes': 2, 'choice': 'No...'}]}
  • 18. models.py (PyMongo) def save_poll(question): return db.polls.insert({"question": question, "pub_date": datetime.utcnow()}) def all_polls(): return db.polls.find() def add_choice(poll_id, choice): db.polls.update({"_id": poll_id}, {"$push": {"choices": {"choice": choice, "votes": 0}}}) def add_vote(poll_id, choice): db.polls.update({"_id": poll_id}, {"$inc": {"choices.%d.votes" % choice: 1}}) http://api.mongodb.org/python
  • 19. models.py (MongoKit) class Poll(mongokit.Document): structure = {"question": str, "pub_date": datetime, "choices": [{"choice": str, "votes": int}]} required_fields = ["question"] default_values = {"pub_date": datetime.utcnow} http://bytebucket.org/namlook/mongokit
  • 20. models.py (Ming) class Poll(ming.Document): class __mongometa__: session = session name = "polls" _id = ming.Field(ming.schema.ObjectId) question = ming.Field(str, required=True) pub_date = ming.Field(datetime.datetime, if_missing=datetime.datetime.utcnow) choices = ming.Field([{"choice": str, "votes": int}]) http://merciless.sourceforge.net/
  • 21. mango - sessions and auth • Full sessions support • mango provided User class • supports is_authenticated(), set_password(), etc. http://github.com/vpulim/mango
  • 22. mango - sessions and auth SESSION_ENGINE = 'mango.session' AUTHENTICATION_BACKENDS = ('mango.auth.Backend',) MONGODB_HOST = 'localhost' MONGODB_PORT = None MONGODB_NAME = 'mydb' http://github.com/vpulim/mango
  • 23. What about admin? • No great solution... yet. • Could replace admin app like mango does for sessions / auth • Or...
  • 24. Supporting MongoDB in django.db