Skip to content

Instantly share code, notes, and snippets.

@chergert
Created July 26, 2012 21:30
Show Gist options
  • Save chergert/3184674 to your computer and use it in GitHub Desktop.
Save chergert/3184674 to your computer and use it in GitHub Desktop.
Just enough of a mongoserver to handle a mongo shell connecting.
#!/usr/bin/env python
"""
A sample Mongo server that handles enough of the commands to connect
with the mongo shell.
Requires: https://github.com/chergert/mongo-async-python-driver
"""
from collections import OrderedDict
from twisted.internet import defer, protocol, reactor
from txmongo.protocol import MongoProtocol, Reply
class MyMongoServer(MongoProtocol):
def handle_QUERY(self, request):
if request.collection.endswith('.$cmd'):
doc = request.query.decode(as_class=OrderedDict)
if doc.keys()[0] == 'ismaster':
ret = {'ismaster': True, 'maxBsonSize': 16 * 1024 * 1024, 'ok': 1}
reply = Reply(response_to=request.request_id, documents=[ret])
self.send(reply)
elif doc.keys()[0] == 'whatsmyuri':
peer = self.transport.getPeer()
ret = {"you": '%s:%d' % (peer.host, peer.port), "ok": 1}
reply = Reply(response_to=request.request_id, documents=[ret])
self.send(reply)
elif doc.keys()[0] == 'replSetGetStatus':
ret = {"errmsg": "not running with --replSet", "ok": 0}
reply = Reply(response_to=request.request_id, documents=[ret])
self.send(reply)
if __name__ == '__main__':
factory = protocol.Factory()
factory.protocol = MyMongoServer
reactor.listenTCP(8181, factory)
reactor.run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment