Skip to content

Instantly share code, notes, and snippets.

@jvanasco
Created January 30, 2012 22:33
Show Gist options
  • Save jvanasco/1707226 to your computer and use it in GitHub Desktop.
Save jvanasco/1707226 to your computer and use it in GitHub Desktop.
mongodb support in pyramid
import .subscribers
def main(global_config, **settings):
## ...
# Initialize mongodb , which is a subscriber
.subscribers.mongodb.initialize_mongo_db( config , settings )
## ...
return config.make_wsgi_app()
Python MonogoDB integration, based on http://docs.pylonsproject.org/projects/pyramid_cookbook/en/latest/mongo.html
I'm migrating a few projects to use mongodb, and I found this to be the easiest way to maintain across all projects ( as in, i don't have to change any code outside of .ini files )
1. the main() routin in __init__.py just needs to call subscribers.mongodb.initialize_mongo_db()
2. subscribers has a single file called mongodb, which initializes
3. environment.ini has its own mongodb space. setting mongodb_use to 'true' will initialize it, setting it to anything else will ignore it.
[app:myapp]
#...
mongodb_use = true
mongodb_uri = mongodb://localhost
mongodb_name = myapp
#...
import pymongo
from gridfs import GridFS
def initialize_mongo_db( config, settings ):
if ( 'mongodb_use' in settings ) and ( settings['mongodb_use'] == 'true' ):
conn = pymongo.Connection( settings['mongodb_uri'] )
config.registry.settings['mongodb_conn'] = conn
config.add_subscriber(add_mongo_db, 'pyramid.events.NewRequest')
def add_mongo_db(event):
settings = event.request.registry.settings
db = settings['mongodb_conn'][settings['mongodb_name']]
event.request.mongodb = db
event.request.gridfs = GridFS(db)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment