SlideShare a Scribd company logo
1 of 31
Inside PyMongo

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')
}
In 1.6
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)
PyMongo + mod_wsgi
Stored JS (1.5)

>>> 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
In 1.6+
$slice and
           Field Negation

>>> db.test.find(fields=[“foo”])

>>> db.test.find(fields={“foo”: 0})

>>> db.test.find(fields={“foo”: {“$slice”: -2}})
y2038
Aware Datetimes
max_scan


>>> db.test.find({“x”: 1}).max_scan(25)
as_class
>>> c = Connection()
>>> c.db.test.save({"x": 1})
ObjectId('4bf6a71be6fb1b4bce000000')

>>> c.db.test.find_one()
{u'x': 1, u'_id': ObjectId('4bf6a71be6fb1b4bce000000')}

>>> c.db.test.find_one(as_class=SON)
SON([(u'_id', ObjectId('4bf6a71be6fb1b4bce000000')), (u'x', 1)])

>>> c.document_class=SON
>>> c.db.test.find_one()
SON([(u'_id', ObjectId('4bf6a71be6fb1b4bce000000')), (u'x', 1)])
Get involved!
http://github.com/mongodb/mongo-python-driver
?
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

Smarter Testing with Spock
Smarter Testing with SpockSmarter Testing with Spock
Smarter Testing with Spock
Dmitry Voloshko
 
Advanced Java Practical File
Advanced Java Practical FileAdvanced Java Practical File
Advanced Java Practical File
Soumya Behera
 
33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good Tests33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good Tests
Tomek Kaczanowski
 

What's hot (20)

TDD Training
TDD TrainingTDD Training
TDD Training
 
Spock Framework
Spock FrameworkSpock Framework
Spock Framework
 
Spock Testing Framework - The Next Generation
Spock Testing Framework - The Next GenerationSpock Testing Framework - The Next Generation
Spock Testing Framework - The Next Generation
 
GMock framework
GMock frameworkGMock framework
GMock framework
 
report
reportreport
report
 
Redux for ReactJS Programmers
Redux for ReactJS ProgrammersRedux for ReactJS Programmers
Redux for ReactJS Programmers
 
Java practical(baca sem v)
Java practical(baca sem v)Java practical(baca sem v)
Java practical(baca sem v)
 
Smarter Testing With Spock
Smarter Testing With SpockSmarter Testing With Spock
Smarter Testing With Spock
 
Spock Framework
Spock FrameworkSpock Framework
Spock Framework
 
ES3-2020-P3 TDD Calculator
ES3-2020-P3 TDD CalculatorES3-2020-P3 TDD Calculator
ES3-2020-P3 TDD Calculator
 
Smarter Testing with Spock
Smarter Testing with SpockSmarter Testing with Spock
Smarter Testing with Spock
 
JS and patterns
JS and patternsJS and patterns
JS and patterns
 
The Ring programming language version 1.6 book - Part 184 of 189
The Ring programming language version 1.6 book - Part 184 of 189The Ring programming language version 1.6 book - Part 184 of 189
The Ring programming language version 1.6 book - Part 184 of 189
 
Unit testing with Spock Framework
Unit testing with Spock FrameworkUnit testing with Spock Framework
Unit testing with Spock Framework
 
Spock framework
Spock frameworkSpock framework
Spock framework
 
Advanced Java Practical File
Advanced Java Practical FileAdvanced Java Practical File
Advanced Java Practical File
 
2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests
 
Example First / A Sane Test-Driven Approach to Programming
Example First / A Sane Test-Driven Approach to ProgrammingExample First / A Sane Test-Driven Approach to Programming
Example First / A Sane Test-Driven Approach to Programming
 
Java Generics - by Example
Java Generics - by ExampleJava Generics - by Example
Java Generics - by Example
 
33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good Tests33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good Tests
 

Viewers also liked

InnoDB architecture and performance optimization (Пётр Зайцев)
InnoDB architecture and performance optimization (Пётр Зайцев)InnoDB architecture and performance optimization (Пётр Зайцев)
InnoDB architecture and performance optimization (Пётр Зайцев)
Ontico
 
Methods of Sharding MySQL
Methods of Sharding MySQLMethods of Sharding MySQL
Methods of Sharding MySQL
Laine Campbell
 
The InnoDB Storage Engine for MySQL
The InnoDB Storage Engine for MySQLThe InnoDB Storage Engine for MySQL
The InnoDB Storage Engine for MySQL
Morgan Tocker
 

Viewers also liked (18)

InnoDB architecture and performance optimization (Пётр Зайцев)
InnoDB architecture and performance optimization (Пётр Зайцев)InnoDB architecture and performance optimization (Пётр Зайцев)
InnoDB architecture and performance optimization (Пётр Зайцев)
 
排队论及其应用浅析
排队论及其应用浅析排队论及其应用浅析
排队论及其应用浅析
 
Indexing
IndexingIndexing
Indexing
 
Linux performance tuning & stabilization tips (mysqlconf2010)
Linux performance tuning & stabilization tips (mysqlconf2010)Linux performance tuning & stabilization tips (mysqlconf2010)
Linux performance tuning & stabilization tips (mysqlconf2010)
 
Performance Schema for MySQL troubleshooting
Performance Schema for MySQL troubleshootingPerformance Schema for MySQL troubleshooting
Performance Schema for MySQL troubleshooting
 
Mvcc (oracle, innodb, postgres)
Mvcc (oracle, innodb, postgres)Mvcc (oracle, innodb, postgres)
Mvcc (oracle, innodb, postgres)
 
Methods of Sharding MySQL
Methods of Sharding MySQLMethods of Sharding MySQL
Methods of Sharding MySQL
 
MongoDB WiredTiger Internals
MongoDB WiredTiger InternalsMongoDB WiredTiger Internals
MongoDB WiredTiger Internals
 
淺入淺出 MySQL & PostgreSQL
淺入淺出 MySQL & PostgreSQL淺入淺出 MySQL & PostgreSQL
淺入淺出 MySQL & PostgreSQL
 
MongoDB: How it Works
MongoDB: How it WorksMongoDB: How it Works
MongoDB: How it Works
 
The InnoDB Storage Engine for MySQL
The InnoDB Storage Engine for MySQLThe InnoDB Storage Engine for MySQL
The InnoDB Storage Engine for MySQL
 
MongodB Internals
MongodB InternalsMongodB Internals
MongodB Internals
 
MyRocks Deep Dive
MyRocks Deep DiveMyRocks Deep Dive
MyRocks Deep Dive
 
MySQL Performance Tuning. Part 1: MySQL Configuration (includes MySQL 5.7)
MySQL Performance Tuning. Part 1: MySQL Configuration (includes MySQL 5.7)MySQL Performance Tuning. Part 1: MySQL Configuration (includes MySQL 5.7)
MySQL Performance Tuning. Part 1: MySQL Configuration (includes MySQL 5.7)
 
MySQL Atchitecture and Concepts
MySQL Atchitecture and ConceptsMySQL Atchitecture and Concepts
MySQL Atchitecture and Concepts
 
MySQL Sharding: Tools and Best Practices for Horizontal Scaling
MySQL Sharding: Tools and Best Practices for Horizontal ScalingMySQL Sharding: Tools and Best Practices for Horizontal Scaling
MySQL Sharding: Tools and Best Practices for Horizontal Scaling
 
SSD Deployment Strategies for MySQL
SSD Deployment Strategies for MySQLSSD Deployment Strategies for MySQL
SSD Deployment Strategies for MySQL
 
Inside MongoDB: the Internals of an Open-Source Database
Inside MongoDB: the Internals of an Open-Source DatabaseInside MongoDB: the Internals of an Open-Source Database
Inside MongoDB: the Internals of an Open-Source Database
 

Similar to Inside PyMongo - MongoNYC

Gae Meets Django
Gae Meets DjangoGae Meets Django
Gae Meets Django
fool2nd
 
A Basic Django Introduction
A Basic Django IntroductionA Basic Django Introduction
A Basic Django Introduction
Ganga Ram
 
Ruby Development and MongoMapper (John Nunemaker)
Ruby Development and MongoMapper (John Nunemaker)Ruby Development and MongoMapper (John Nunemaker)
Ruby Development and MongoMapper (John Nunemaker)
MongoSF
 

Similar to Inside PyMongo - MongoNYC (20)

Python Development (MongoSF)
Python Development (MongoSF)Python Development (MongoSF)
Python Development (MongoSF)
 
MongoDB hearts Django? (Django NYC)
MongoDB hearts Django? (Django NYC)MongoDB hearts Django? (Django NYC)
MongoDB hearts Django? (Django NYC)
 
Rapid and Scalable Development with MongoDB, PyMongo, and Ming
Rapid and Scalable Development with MongoDB, PyMongo, and MingRapid and Scalable Development with MongoDB, PyMongo, and Ming
Rapid and Scalable Development with MongoDB, PyMongo, and Ming
 
Introduction to Django
Introduction to DjangoIntroduction to Django
Introduction to Django
 
Optimization in django orm
Optimization in django ormOptimization in django orm
Optimization in django orm
 
Gae Meets Django
Gae Meets DjangoGae Meets Django
Gae Meets Django
 
MongoDB at ZPUGDC
MongoDB at ZPUGDCMongoDB at ZPUGDC
MongoDB at ZPUGDC
 
Тестирование и Django
Тестирование и DjangoТестирование и Django
Тестирование и Django
 
PyCon 2010 SQLAlchemy tutorial
PyCon 2010 SQLAlchemy tutorialPyCon 2010 SQLAlchemy tutorial
PyCon 2010 SQLAlchemy tutorial
 
A Basic Django Introduction
A Basic Django IntroductionA Basic Django Introduction
A Basic Django Introduction
 
Django - Know Your Namespace: Middleware
Django - Know Your Namespace: MiddlewareDjango - Know Your Namespace: Middleware
Django - Know Your Namespace: Middleware
 
MongoDB World 2018: Keynote
MongoDB World 2018: KeynoteMongoDB World 2018: Keynote
MongoDB World 2018: Keynote
 
What's new in Django 1.2?
What's new in Django 1.2?What's new in Django 1.2?
What's new in Django 1.2?
 
Django (Web Konferencia 2009)
Django (Web Konferencia 2009)Django (Web Konferencia 2009)
Django (Web Konferencia 2009)
 
Benchy, python framework for performance benchmarking of Python Scripts
Benchy, python framework for performance benchmarking  of Python ScriptsBenchy, python framework for performance benchmarking  of Python Scripts
Benchy, python framework for performance benchmarking of Python Scripts
 
MongoDB With Style
MongoDB With StyleMongoDB With Style
MongoDB With Style
 
Practical Google App Engine Applications In Py
Practical Google App Engine Applications In PyPractical Google App Engine Applications In Py
Practical Google App Engine Applications In Py
 
Ruby Development and MongoMapper (John Nunemaker)
Ruby Development and MongoMapper (John Nunemaker)Ruby Development and MongoMapper (John Nunemaker)
Ruby Development and MongoMapper (John Nunemaker)
 
Fun Teaching MongoDB New Tricks
Fun Teaching MongoDB New TricksFun Teaching MongoDB New Tricks
Fun Teaching MongoDB New Tricks
 
Strategies for refactoring and migrating a big old project to be multilingual...
Strategies for refactoring and migrating a big old project to be multilingual...Strategies for refactoring and migrating a big old project to be multilingual...
Strategies for refactoring and migrating a big old project to be multilingual...
 

More from Mike Dirolf

FrozenRails Training
FrozenRails TrainingFrozenRails Training
FrozenRails Training
Mike Dirolf
 

More from Mike Dirolf (14)

FrozenRails Training
FrozenRails TrainingFrozenRails Training
FrozenRails Training
 
MongoDB at FrozenRails
MongoDB at FrozenRailsMongoDB at FrozenRails
MongoDB at FrozenRails
 
Introduction to MongoDB
Introduction to MongoDBIntroduction to MongoDB
Introduction to MongoDB
 
MongoDB at CodeMash 2.0.1.0
MongoDB at CodeMash 2.0.1.0MongoDB at CodeMash 2.0.1.0
MongoDB at CodeMash 2.0.1.0
 
MongoDB at RubyConf
MongoDB at RubyConfMongoDB at RubyConf
MongoDB at RubyConf
 
MongoDB at RuPy
MongoDB at RuPyMongoDB at RuPy
MongoDB at RuPy
 
MongoDB at RubyEnRails 2009
MongoDB at RubyEnRails 2009MongoDB at RubyEnRails 2009
MongoDB at RubyEnRails 2009
 
MongoDB Strange Loop 2009
MongoDB Strange Loop 2009MongoDB Strange Loop 2009
MongoDB Strange Loop 2009
 
MongoDB Hadoop DC
MongoDB Hadoop DCMongoDB Hadoop DC
MongoDB Hadoop DC
 
MongoDB London PHP
MongoDB London PHPMongoDB London PHP
MongoDB London PHP
 
MongoDB EuroPython 2009
MongoDB EuroPython 2009MongoDB EuroPython 2009
MongoDB EuroPython 2009
 
MongoDB NYC Python
MongoDB NYC PythonMongoDB NYC Python
MongoDB NYC Python
 
MongoDB SF Python
MongoDB SF PythonMongoDB SF Python
MongoDB SF Python
 
MongoDB SF Ruby
MongoDB SF RubyMongoDB SF Ruby
MongoDB SF Ruby
 

Recently uploaded

Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Victor Rentea
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 

Recently uploaded (20)

Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 

Inside PyMongo - MongoNYC

  • 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') }
  • 5. GridFS (setup) >>> from pymongo import Connection >>> import gridfs >>> >>> db = Connection().gridfs_example >>> fs = gridfs.GridFS(db)
  • 6. 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()
  • 7. GridFS (after) >>> fs.put(“hello world”) >>> file_id = fs.put("hello world") >>> fs.get(file_id).read() 'hello world'
  • 8. 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]
  • 9. Commands (before) >>> db.command({“buildinfo”: 1}) >>> db.command({“collstats”: collection}) >>> db.command(SON([(“filemd5”, object_id), (“root”, file_root)]))
  • 10. Commands (after) >>> db.command(“buildinfo”) >>> db.command(“collstats”, collection) >>> db.command(“filemd5”, object_id, root=file_root)
  • 12. Stored JS (1.5) >>> 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
  • 14. $slice and Field Negation >>> db.test.find(fields=[“foo”]) >>> db.test.find(fields={“foo”: 0}) >>> db.test.find(fields={“foo”: {“$slice”: -2}})
  • 15. y2038
  • 18. as_class >>> c = Connection() >>> c.db.test.save({"x": 1}) ObjectId('4bf6a71be6fb1b4bce000000') >>> c.db.test.find_one() {u'x': 1, u'_id': ObjectId('4bf6a71be6fb1b4bce000000')} >>> c.db.test.find_one(as_class=SON) SON([(u'_id', ObjectId('4bf6a71be6fb1b4bce000000')), (u'x', 1)]) >>> c.document_class=SON >>> c.db.test.find_one() SON([(u'_id', ObjectId('4bf6a71be6fb1b4bce000000')), (u'x', 1)])
  • 20. ?
  • 21. Yes... ...but also sometimes no
  • 22. 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
  • 23. 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', )
  • 24. 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...'}]}
  • 25. 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
  • 26. 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
  • 27. 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/
  • 28. mango - sessions and auth • Full sessions support • mango provided User class • supports is_authenticated(), set_password(), etc. http://github.com/vpulim/mango
  • 29. 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
  • 30. What about admin? • No great solution... yet. • Could replace admin app like mango does for sessions / auth • Or...
  • 31. Supporting MongoDB in django.db

Editor's Notes