PEP8 fixes (only .py for now)
Signed-off-by: Mike Dirolf <mike@10gen.com>
This commit is contained in:
parent
359fbd8535
commit
69a87923bb
@ -45,6 +45,7 @@ version = "1.6+"
|
||||
Connection = PyMongo_Connection
|
||||
"""Alias for :class:`pymongo.connection.Connection`."""
|
||||
|
||||
|
||||
def has_c():
|
||||
"""Is the C extension installed?
|
||||
|
||||
|
||||
@ -50,6 +50,7 @@ USER_DEFINED_SUBTYPE = 128
|
||||
.. versionadded:: 1.5
|
||||
"""
|
||||
|
||||
|
||||
class Binary(str):
|
||||
"""Representation of binary data to be stored in or retrieved from MongoDB.
|
||||
|
||||
|
||||
@ -195,17 +195,17 @@ _element_getter = {
|
||||
"\x03": _get_object,
|
||||
"\x04": _get_array,
|
||||
"\x05": _get_binary,
|
||||
"\x06": _get_null, # undefined
|
||||
"\x06": _get_null, # undefined
|
||||
"\x07": _get_oid,
|
||||
"\x08": _get_boolean,
|
||||
"\x09": _get_date,
|
||||
"\x0A": _get_null,
|
||||
"\x0B": _get_regex,
|
||||
"\x0C": _get_ref,
|
||||
"\x0D": _get_string, # code
|
||||
"\x0E": _get_string, # symbol
|
||||
"\x0D": _get_string, # code
|
||||
"\x0E": _get_string, # symbol
|
||||
"\x0F": _get_code_w_scope,
|
||||
"\x10": _get_int, # number_int
|
||||
"\x10": _get_int, # number_int
|
||||
"\x11": _get_timestamp,
|
||||
"\x12": _get_long,
|
||||
"\xFF": lambda x, y: (MinKey(), x),
|
||||
@ -297,9 +297,9 @@ def _element_to_bson(key, value, check_keys):
|
||||
return "\x08" + name + "\x00"
|
||||
if isinstance(value, (int, long)):
|
||||
# TODO this is a really ugly way to check for this...
|
||||
if value > 2**64 / 2 - 1 or value < -2**64 / 2:
|
||||
if value > 2 ** 64 / 2 - 1 or value < -2 ** 64 / 2:
|
||||
raise OverflowError("MongoDB can only handle up to 8-byte ints")
|
||||
if value > 2**32 / 2 - 1 or value < -2**32 / 2:
|
||||
if value > 2 ** 32 / 2 - 1 or value < -2 ** 32 / 2:
|
||||
return "\x12" + name + struct.pack("<q", value)
|
||||
return "\x10" + name + struct.pack("<i", value)
|
||||
if isinstance(value, datetime.datetime):
|
||||
@ -355,8 +355,8 @@ def _dict_to_bson(dict, check_keys, top_level=True):
|
||||
|
||||
length = len(elements) + 5
|
||||
if length > 4 * 1024 * 1024:
|
||||
raise InvalidDocument("document too large - BSON documents are limited "
|
||||
"to 4 MB")
|
||||
raise InvalidDocument("document too large - BSON documents are"
|
||||
"limited to 4 MB")
|
||||
return struct.pack("<i", length) + elements + "\x00"
|
||||
if _use_c:
|
||||
_dict_to_bson = _cbson._dict_to_bson
|
||||
|
||||
@ -15,6 +15,7 @@
|
||||
"""Tools for representing JavaScript code to be evaluated by MongoDB.
|
||||
"""
|
||||
|
||||
|
||||
class Code(str):
|
||||
"""JavaScript code to be evaluated by MongoDB.
|
||||
|
||||
|
||||
@ -481,7 +481,8 @@ class Collection(object):
|
||||
"""
|
||||
return self.find().count()
|
||||
|
||||
def create_index(self, key_or_list, deprecated_unique=None, ttl=300, **kwargs):
|
||||
def create_index(self, key_or_list, deprecated_unique=None,
|
||||
ttl=300, **kwargs):
|
||||
"""Creates an index on this collection.
|
||||
|
||||
Takes either a single key or a list of (key, direction) pairs.
|
||||
@ -564,7 +565,8 @@ class Collection(object):
|
||||
check_keys=False)
|
||||
return name
|
||||
|
||||
def ensure_index(self, key_or_list, deprecated_unique=None, ttl=300, **kwargs):
|
||||
def ensure_index(self, key_or_list, deprecated_unique=None,
|
||||
ttl=300, **kwargs):
|
||||
"""Ensures that an index exists on this collection.
|
||||
|
||||
Takes either a single key or a list of (key, direction) pairs.
|
||||
@ -631,7 +633,8 @@ class Collection(object):
|
||||
|
||||
if self.__database.connection._cache_index(self.__database.name,
|
||||
self.__name, name, ttl):
|
||||
return self.create_index(key_or_list, deprecated_unique, ttl, **kwargs)
|
||||
return self.create_index(key_or_list, deprecated_unique,
|
||||
ttl, **kwargs)
|
||||
return None
|
||||
|
||||
def drop_indexes(self):
|
||||
|
||||
@ -94,7 +94,7 @@ class Pool(threading.local):
|
||||
self.sock = None
|
||||
|
||||
|
||||
class Connection(object): # TODO support auth for pooling
|
||||
class Connection(object): # TODO support auth for pooling
|
||||
"""Connection to MongoDB.
|
||||
"""
|
||||
|
||||
@ -189,7 +189,8 @@ class Connection(object): # TODO support auth for pooling
|
||||
i = source.find(sub)
|
||||
if i == -1:
|
||||
return (source, None)
|
||||
return (source[:i], source[i+len(sub):])
|
||||
|
||||
return (source[:i], source[i + len(sub):])
|
||||
|
||||
@staticmethod
|
||||
def _parse_uri(uri):
|
||||
@ -198,7 +199,8 @@ class Connection(object): # TODO support auth for pooling
|
||||
if uri.startswith("mongodb://"):
|
||||
uri = uri[len("mongodb://"):]
|
||||
elif "://" in uri:
|
||||
raise InvalidURI("Invalid uri scheme: %s" % Connection.__partition(uri, "://")[0])
|
||||
raise InvalidURI("Invalid uri scheme: %s"
|
||||
% Connection.__partition(uri, "://")[0])
|
||||
|
||||
(hosts, database) = Connection.__partition(uri, "/")
|
||||
|
||||
@ -211,7 +213,8 @@ class Connection(object): # TODO support auth for pooling
|
||||
(auth, hosts) = Connection.__partition(hosts, "@")
|
||||
|
||||
if ":" not in auth:
|
||||
raise InvalidURI("auth must be specified as 'username:password@'")
|
||||
raise InvalidURI("auth must be specified as "
|
||||
"'username:password@'")
|
||||
(username, password) = Connection.__partition(auth, ":")
|
||||
|
||||
host_list = []
|
||||
@ -441,7 +444,7 @@ class Connection(object): # TODO support auth for pooling
|
||||
self.__port = port
|
||||
return
|
||||
except socket.error, e:
|
||||
sock_error=True
|
||||
sock_error = True
|
||||
finally:
|
||||
if sock is not None:
|
||||
sock.close()
|
||||
@ -499,9 +502,10 @@ class Connection(object): # TODO support auth for pooling
|
||||
"""Set this connection's cursor manager.
|
||||
|
||||
Raises :class:`TypeError` if `manager_class` is not a subclass of
|
||||
:class:`~pymongo.cursor_manager.CursorManager`. A cursor manager handles
|
||||
closing cursors. Different managers can implement different policies in
|
||||
terms of when to actually kill a cursor that has been closed.
|
||||
:class:`~pymongo.cursor_manager.CursorManager`. A cursor manager
|
||||
handles closing cursors. Different managers can implement different
|
||||
policies in terms of when to actually kill a cursor that has
|
||||
been closed.
|
||||
|
||||
:Parameters:
|
||||
- `manager_class`: cursor manager to use
|
||||
@ -562,7 +566,8 @@ class Connection(object): # TODO support auth for pooling
|
||||
# lastError) and raise OperationFailure if it is an error
|
||||
# response.
|
||||
if with_last_error:
|
||||
response = self.__receive_message_on_socket(1, request_id, sock)
|
||||
response = self.__receive_message_on_socket(1, request_id,
|
||||
sock)
|
||||
return self.__check_response_to_last_error(response)
|
||||
return None
|
||||
except (ConnectionFailure, socket.error), e:
|
||||
|
||||
@ -25,8 +25,7 @@ _QUERY_OPTIONS = {
|
||||
"tailable_cursor": 2,
|
||||
"slave_okay": 4,
|
||||
"oplog_replay": 8,
|
||||
"no_timeout": 16
|
||||
}
|
||||
"no_timeout": 16}
|
||||
|
||||
|
||||
# TODO might be cool to be able to do find().include("foo") or
|
||||
@ -263,13 +262,15 @@ class Cursor(object):
|
||||
skip = 0
|
||||
if index.start is not None:
|
||||
if index.start < 0:
|
||||
raise IndexError("Cursor instances do not support negative indices")
|
||||
raise IndexError("Cursor instances do not support"
|
||||
"negative indices")
|
||||
skip = index.start
|
||||
|
||||
if index.stop is not None:
|
||||
limit = index.stop - skip
|
||||
if limit <= 0:
|
||||
raise IndexError("stop index must be greater than start index for slice %r" % index)
|
||||
raise IndexError("stop index must be greater than start"
|
||||
"index for slice %r" % index)
|
||||
else:
|
||||
limit = 0
|
||||
|
||||
@ -279,14 +280,16 @@ class Cursor(object):
|
||||
|
||||
if isinstance(index, (int, long)):
|
||||
if index < 0:
|
||||
raise IndexError("Cursor instances do not support negative indices")
|
||||
raise IndexError("Cursor instances do not support negative"
|
||||
"indices")
|
||||
clone = self.clone()
|
||||
clone.skip(index + self.__skip)
|
||||
clone.limit(-1) # use a hard limit
|
||||
clone.limit(-1) # use a hard limit
|
||||
for doc in clone:
|
||||
return doc
|
||||
raise IndexError("no such item for Cursor instance")
|
||||
raise TypeError("index %r cannot be applied to Cursor instances" % index)
|
||||
raise TypeError("index %r cannot be applied to Cursor "
|
||||
"instances" % index)
|
||||
|
||||
def max_scan(self, max_scan):
|
||||
"""Limit the number of documents to scan when performing the query.
|
||||
|
||||
@ -82,8 +82,8 @@ class Database(object):
|
||||
- `manipulator`: the manipulator to add
|
||||
"""
|
||||
def method_overwritten(instance, method):
|
||||
return getattr(instance, method) != getattr(super(instance.__class__, instance), method)
|
||||
|
||||
return getattr(instance, method) != \
|
||||
getattr(super(instance.__class__, instance), method)
|
||||
|
||||
if manipulator.will_copy():
|
||||
if method_overwritten(manipulator, "transform_incoming"):
|
||||
@ -440,9 +440,10 @@ class Database(object):
|
||||
|
||||
.. versionadded:: 1.4
|
||||
"""
|
||||
pwd = helpers._password_digest(name, password)
|
||||
self.system.users.update({"user": name},
|
||||
{"user": name,
|
||||
"pwd": helpers._password_digest(name, password)},
|
||||
"pwd": pwd},
|
||||
upsert=True, safe=True)
|
||||
|
||||
def remove_user(self, name):
|
||||
@ -509,7 +510,8 @@ class Database(object):
|
||||
nonce = self.command("getnonce")["nonce"]
|
||||
key = helpers._auth_key(nonce, name, password)
|
||||
try:
|
||||
self.command("authenticate", user=unicode(name), nonce=nonce, key=key)
|
||||
self.command("authenticate", user=unicode(name),
|
||||
nonce=nonce, key=key)
|
||||
return True
|
||||
except OperationFailure:
|
||||
return False
|
||||
@ -525,9 +527,9 @@ class Database(object):
|
||||
"""Dereference a DBRef, getting the SON object it points to.
|
||||
|
||||
Raises TypeError if `dbref` is not an instance of DBRef. Returns a SON
|
||||
object or None if the reference does not point to a valid object. Raises
|
||||
ValueError if `dbref` has a database specified that is different from
|
||||
the current database.
|
||||
object or None if the reference does not point to a valid object.
|
||||
Raises ValueError if `dbref` has a database specified that is different
|
||||
from the current database.
|
||||
|
||||
:Parameters:
|
||||
- `dbref`: the reference
|
||||
|
||||
@ -14,6 +14,7 @@
|
||||
|
||||
"""Exceptions raised by PyMongo."""
|
||||
|
||||
|
||||
class PyMongoError(Exception):
|
||||
"""Base class for all PyMongo exceptions.
|
||||
|
||||
|
||||
@ -12,12 +12,12 @@
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
"""Little bits and pieces used by the driver that don't really fit elsewhere."""
|
||||
"""Bits and pieces used by the driver that don't really fit elsewhere."""
|
||||
|
||||
try:
|
||||
import hashlib
|
||||
_md5func = hashlib.md5
|
||||
except: # for Python < 2.5
|
||||
except: # for Python < 2.5
|
||||
import md5
|
||||
_md5func = md5.new
|
||||
import struct
|
||||
@ -28,6 +28,7 @@ from pymongo.errors import (OperationFailure,
|
||||
AutoReconnect)
|
||||
from pymongo.son import SON
|
||||
|
||||
|
||||
def _index_list(key_or_list, direction=None):
|
||||
"""Helper to generate a list of (key, direction) pairs.
|
||||
|
||||
|
||||
@ -55,6 +55,7 @@ from pymongo.objectid import ObjectId
|
||||
# TODO share this with bson.py?
|
||||
_RE_TYPE = type(re.compile("foo"))
|
||||
|
||||
|
||||
def object_hook(dct):
|
||||
if "$oid" in dct:
|
||||
return ObjectId(str(dct["$oid"]))
|
||||
@ -71,6 +72,7 @@ def object_hook(dct):
|
||||
return re.compile(dct["$regex"], flags)
|
||||
return dct
|
||||
|
||||
|
||||
def default(obj):
|
||||
if isinstance(obj, ObjectId):
|
||||
return {"$oid": str(obj)}
|
||||
|
||||
@ -138,9 +138,9 @@ class MasterSlaveConnection(object):
|
||||
return (-1, self.__master._send_message_with_response(message,
|
||||
_sock))
|
||||
|
||||
return (connection_id,
|
||||
self.__slaves[connection_id]._send_message_with_response(message,
|
||||
_sock))
|
||||
slaves = self.__slaves[connection_id]
|
||||
return (connection_id, slaves._send_message_with_response(message,
|
||||
_sock))
|
||||
|
||||
def start_request(self):
|
||||
"""Start a "request".
|
||||
|
||||
@ -48,10 +48,10 @@ def __pack_message(operation, data):
|
||||
|
||||
Returns the resultant message string.
|
||||
"""
|
||||
request_id = random.randint(-2**31 - 1, 2**31)
|
||||
request_id = random.randint(-2 ** 31 - 1, 2 ** 31)
|
||||
message = struct.pack("<i", 16 + len(data))
|
||||
message += struct.pack("<i", request_id)
|
||||
message += __ZERO # responseTo
|
||||
message += __ZERO # responseTo
|
||||
message += struct.pack("<i", operation)
|
||||
return (request_id, message + data)
|
||||
|
||||
|
||||
@ -21,7 +21,7 @@ import datetime
|
||||
try:
|
||||
import hashlib
|
||||
_md5func = hashlib.md5
|
||||
except ImportError: # for Python < 2.5
|
||||
except ImportError: # for Python < 2.5
|
||||
import md5
|
||||
_md5func = md5.new
|
||||
import os
|
||||
@ -64,8 +64,8 @@ class ObjectId(object):
|
||||
hex string)
|
||||
|
||||
.. versionadded:: 1.2.1
|
||||
The `oid` parameter can be a ``unicode`` instance (that contains only
|
||||
hexadecimal digits).
|
||||
The `oid` parameter can be a ``unicode`` instance (that contains
|
||||
only hexadecimal digits).
|
||||
|
||||
.. mongodoc:: objectids
|
||||
"""
|
||||
@ -193,5 +193,3 @@ class ObjectId(object):
|
||||
.. versionadded:: 1.1
|
||||
"""
|
||||
return hash(self.__id)
|
||||
|
||||
|
||||
|
||||
@ -20,6 +20,7 @@
|
||||
import calendar
|
||||
import datetime
|
||||
|
||||
|
||||
class Timestamp(object):
|
||||
"""MongoDB internal timestamps used in the opLog.
|
||||
"""
|
||||
@ -53,10 +54,10 @@ class Timestamp(object):
|
||||
raise TypeError("time must be an instance of int")
|
||||
if not isinstance(inc, int):
|
||||
raise TypeError("inc must be an instance of int")
|
||||
if not 0 <= time < 2**32:
|
||||
if not 0 <= time < 2 ** 32:
|
||||
raise ValueError("time must be contained in [0, 2**32)")
|
||||
if not 0 <= inc < 2**32:
|
||||
raise ValueError("inc must be contained in [0, 2**32), not %r" % inc)
|
||||
if not 0 <= inc < 2 ** 32:
|
||||
raise ValueError("inc must be contained in [0, 2**32)")
|
||||
|
||||
self.__time = time
|
||||
self.__inc = inc
|
||||
|
||||
Loading…
Reference in New Issue
Block a user