From 7bdc7646c6306c93bb660c3bbf3364ddad507fc6 Mon Sep 17 00:00:00 2001 From: Mike Dirolf Date: Mon, 12 Jan 2009 15:45:29 -0500 Subject: [PATCH] basic support for find and find_one. Cursor. database connections must specify database name. --- mongo.py | 213 +++++++++++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 190 insertions(+), 23 deletions(-) diff --git a/mongo.py b/mongo.py index 82820ef3f..e9296b6fd 100644 --- a/mongo.py +++ b/mongo.py @@ -25,29 +25,36 @@ class InvalidCollection(ValueError): class Mongo(object): """A connection to a Mongo database. """ - def __init__(self, host="localhost", port=27017): + def __init__(self, name, host="localhost", port=27017): """Open a new connection to the database at host:port. - Raises TypeError if host is not an instance of string or port is + Raises TypeError if name or host is not an instance of string or port is not an instance of int. Raises ConnectionException if the connection cannot be made. Arguments: + - `name`: the name of the database to connect to - `host` (optional): the hostname or IPv4 address of the database to - connect to + connect to - `port` (optional): the port number on which to connect """ + if not isinstance(name, types.StringTypes): + raise TypeError("name must be an instance of (str, unicode)") if not isinstance(host, types.StringType): raise TypeError("host must be an instance of str") if not isinstance(port, types.IntType): raise TypeError("port must be an instance of int") + self.__name = name self.__host = host self.__port = port self.__id = 1 self.__connect() + def name(self): + return self.__name + def __connect(self): """(Re-)connect to the database.""" try: @@ -58,7 +65,7 @@ class Mongo(object): (self.__host, self.__port, traceback.format_exc())) def _send_message(self, operation, data): - """Say something to the database. Return the response. + """Say something to the database. Arguments: - `operation`: the opcode of the message @@ -82,13 +89,41 @@ class Mongo(object): raise ConnectionException("connection closed") total_sent += sent + return self.__id - 1 + + def _receive_message(self, operation, request_id): + """Receive a message from the database. + + Returns the message body. Asserts that the message uses the given opcode + and request id. + + Arguments: + - `operation`: the opcode of the message + - `request_id`: the request id that the message should be in response to + """ + def receive(length): + message = "" + while len(message) < length: + chunk = self.__connection.recv(length - len(message)) + if chunk == "": + raise ConnectionException("connection closed") + message += chunk + return message + + header = receive(16) + length = struct.unpack("