Skip to content

Commit 45cb991

Browse files
committed
Merge pull request MongoEngine#980 from MRigal/fix/various-fixes
Pep8, code clean-up and 0.10.0 changelog finalisation
2 parents 4c80154 + 839bc99 commit 45cb991

32 files changed

+196
-209
lines changed

AUTHORS

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ Laine Herron https://github.com/LaineHerron
1212

1313
CONTRIBUTORS
1414

15-
Dervived from the git logs, inevitably incomplete but all of whom and others
15+
Derived from the git logs, inevitably incomplete but all of whom and others
1616
have submitted patches, reported bugs and generally helped make MongoEngine
1717
that much better:
1818

CONTRIBUTING.rst

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,10 @@ Style Guide
2929
-----------
3030

3131
MongoEngine aims to follow `PEP8 <http://www.python.org/dev/peps/pep-0008/>`_
32-
including 4 space indents and 79 character line limits.
32+
including 4 space indents. When possible we try to stick to 79 character line limits.
33+
However, screens got bigger and an ORM has a strong focus on readability and
34+
if it can help, we accept 119 as maximum line length, in a similar way as
35+
`django does <https://docs.djangoproject.com/en/dev/internals/contributing/writing-code/coding-style/#python-style>`_
3336

3437
Testing
3538
-------
@@ -38,6 +41,10 @@ All tests are run on `Travis <http://travis-ci.org/MongoEngine/mongoengine>`_
3841
and any pull requests are automatically tested by Travis. Any pull requests
3942
without tests will take longer to be integrated and might be refused.
4043

44+
You may also submit a simple failing test as a PullRequest if you don't know
45+
how to fix it, it will be easier for other people to work on it and it may get
46+
fixed faster.
47+
4148
General Guidelines
4249
------------------
4350

@@ -48,6 +55,7 @@ General Guidelines
4855
from the cmd line to run the test suite).
4956
- Ensure tests pass on every Python and PyMongo versions.
5057
You can test on these versions locally by executing ``tox``
58+
- Add enhancements or problematic bug fixes to docs/changelog.rst
5159
- Add yourself to AUTHORS :)
5260

5361
Documentation

README.rst

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,9 @@ a `tutorial <http://readthedocs.org/docs/mongoengine-odm/en/latest/tutorial.html
2626

2727
Installation
2828
============
29-
If you have `setuptools <http://peak.telecommunity.com/DevCenter/setuptools>`_
29+
We recommend the use of `virtualenv <https://virtualenv.pypa.io/>`_ and of
30+
`pip <https://pip.pypa.io/>`_. You can then use ``pip install -U mongoengine``.
31+
You may also have `setuptools <http://peak.telecommunity.com/DevCenter/setuptools>`_ and thus
3032
you can use ``easy_install -U mongoengine``. Otherwise, you can download the
3133
source from `GitHub <http://github.com/MongoEngine/mongoengine>`_ and run ``python
3234
setup.py install``.
@@ -114,7 +116,7 @@ Also use the -s argument if you want to print out whatever or access pdb while t
114116

115117
.. code-block:: shell
116118
117-
$ python setup.py nosetests --tests tests/test_django.py:QuerySetTest.test_get_document_or_404 -s
119+
$ python setup.py nosetests --tests tests/fields/fields.py:FieldTest.test_cls_field -s
118120
119121
Community
120122
=========

docs/_themes/sphinx_rtd_theme/footer.html

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
{% if next or prev %}
33
<div class="rst-footer-buttons">
44
{% if next %}
5-
<a href="{{ next.link|e }}" class="btn btn-neutral float-right" title="{{ next.title|striptags|e }}"/>Next <span class="icon icon-circle-arrow-right"></span></a>
5+
<a href="{{ next.link|e }}" class="btn btn-neutral float-right" title="{{ next.title|striptags|e }}">Next <span class="icon icon-circle-arrow-right"></span></a>
66
{% endif %}
77
{% if prev %}
88
<a href="{{ prev.link|e }}" class="btn btn-neutral" title="{{ prev.title|striptags|e }}"><span class="icon icon-circle-arrow-left"></span> Previous</a>

docs/changelog.rst

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,15 @@
22
Changelog
33
=========
44

5+
Changes in 0.10.1 - DEV
6+
=======================
57

6-
Changes in 0.9.X - DEV
7-
======================
8+
Changes in 0.10.0
9+
=================
10+
- Django support was removed and will be available as a separate extension. #958
11+
- Allow to load undeclared field with meta attribute 'strict': False #957
12+
- Support for PyMongo 3+ #946
13+
- Removed get_or_create() deprecated since 0.8.0. #300
814
- Improve Document._created status when switch collection and db #1020
915
- Queryset update doesn't go through field validation #453
1016
- Added support for specifying authentication source as option `authSource` in URI. #967
@@ -14,17 +20,14 @@ Changes in 0.9.X - DEV
1420
- Use sets for populating dbrefs to dereference
1521
- Fixed unpickled documents replacing the global field's list. #888
1622
- Fixed storage of microseconds in ComplexDateTimeField and unused separator option. #910
17-
- Django support was removed and will be available as a separate extension. #958
1823
- Don't send a "cls" option to ensureIndex (related to https://jira.mongodb.org/browse/SERVER-769)
1924
- Fix for updating sorting in SortedListField. #978
2025
- Added __ support to escape field name in fields lookup keywords that match operators names #949
21-
- Support for PyMongo 3+ #946
2226
- Fix for issue where FileField deletion did not free space in GridFS.
2327
- No_dereference() not respected on embedded docs containing reference. #517
2428
- Document save raise an exception if save_condition fails #1005
2529
- Fixes some internal _id handling issue. #961
2630
- Updated URL and Email Field regex validators, added schemes argument to URLField validation. #652
27-
- Removed get_or_create() deprecated since 0.8.0. #300
2831
- Capped collection multiple of 256. #1011
2932
- Added `BaseQuerySet.aggregate_sum` and `BaseQuerySet.aggregate_average` methods.
3033
- Fix for delete with write_concern {'w': 0}. #1008

docs/django.rst

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,5 +15,5 @@ The MongoEngine team is looking for help contributing and maintaining a new
1515
Django extension for MongoEngine! If you have Django experience and would like
1616
to help contribute to the project, please get in touch on the
1717
`mailing list <http://groups.google.com/group/mongoengine-users>`_ or by
18-
simpily contributing on
18+
simply contributing on
1919
`GitHub <https://github.com/MongoEngine/django-mongoengine>`_.

docs/guide/querying.rst

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -598,7 +598,7 @@ Some variables are made available in the scope of the Javascript function:
598598

599599
The following example demonstrates the intended usage of
600600
:meth:`~mongoengine.queryset.QuerySet.exec_js` by defining a function that sums
601-
over a field on a document (this functionality is already available throught
601+
over a field on a document (this functionality is already available through
602602
:meth:`~mongoengine.queryset.QuerySet.sum` but is shown here for sake of
603603
example)::
604604

mongoengine/base/datastructures.py

Lines changed: 28 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import weakref
22
import itertools
3+
34
from mongoengine.common import _import_class
45
from mongoengine.errors import DoesNotExist, MultipleObjectsReturned
56

@@ -20,7 +21,7 @@ def __init__(self, dict_items, instance, name):
2021
if isinstance(instance, (Document, EmbeddedDocument)):
2122
self._instance = weakref.proxy(instance)
2223
self._name = name
23-
return super(BaseDict, self).__init__(dict_items)
24+
super(BaseDict, self).__init__(dict_items)
2425

2526
def __getitem__(self, key, *args, **kwargs):
2627
value = super(BaseDict, self).__getitem__(key)
@@ -65,15 +66,15 @@ def __setstate__(self, state):
6566

6667
def clear(self, *args, **kwargs):
6768
self._mark_as_changed()
68-
return super(BaseDict, self).clear(*args, **kwargs)
69+
return super(BaseDict, self).clear()
6970

7071
def pop(self, *args, **kwargs):
7172
self._mark_as_changed()
7273
return super(BaseDict, self).pop(*args, **kwargs)
7374

7475
def popitem(self, *args, **kwargs):
7576
self._mark_as_changed()
76-
return super(BaseDict, self).popitem(*args, **kwargs)
77+
return super(BaseDict, self).popitem()
7778

7879
def setdefault(self, *args, **kwargs):
7980
self._mark_as_changed()
@@ -189,7 +190,7 @@ def remove(self, *args, **kwargs):
189190

190191
def reverse(self, *args, **kwargs):
191192
self._mark_as_changed()
192-
return super(BaseList, self).reverse(*args, **kwargs)
193+
return super(BaseList, self).reverse()
193194

194195
def sort(self, *args, **kwargs):
195196
self._mark_as_changed()
@@ -368,45 +369,61 @@ class StrictDict(object):
368369
__slots__ = ()
369370
_special_fields = set(['get', 'pop', 'iteritems', 'items', 'keys', 'create'])
370371
_classes = {}
372+
371373
def __init__(self, **kwargs):
372-
for k,v in kwargs.iteritems():
374+
for k, v in kwargs.iteritems():
373375
setattr(self, k, v)
376+
374377
def __getitem__(self, key):
375378
key = '_reserved_' + key if key in self._special_fields else key
376379
try:
377380
return getattr(self, key)
378381
except AttributeError:
379382
raise KeyError(key)
383+
380384
def __setitem__(self, key, value):
381385
key = '_reserved_' + key if key in self._special_fields else key
382386
return setattr(self, key, value)
387+
383388
def __contains__(self, key):
384389
return hasattr(self, key)
390+
385391
def get(self, key, default=None):
386392
try:
387393
return self[key]
388394
except KeyError:
389395
return default
396+
390397
def pop(self, key, default=None):
391398
v = self.get(key, default)
392399
try:
393400
delattr(self, key)
394401
except AttributeError:
395402
pass
396403
return v
404+
397405
def iteritems(self):
398406
for key in self:
399407
yield key, self[key]
408+
400409
def items(self):
401410
return [(k, self[k]) for k in iter(self)]
411+
412+
def iterkeys(self):
413+
return iter(self)
414+
402415
def keys(self):
403416
return list(iter(self))
417+
404418
def __iter__(self):
405419
return (key for key in self.__slots__ if hasattr(self, key))
420+
406421
def __len__(self):
407422
return len(list(self.iteritems()))
423+
408424
def __eq__(self, other):
409425
return self.items() == other.items()
426+
410427
def __neq__(self, other):
411428
return self.items() != other.items()
412429

@@ -417,15 +434,18 @@ def create(cls, allowed_keys):
417434
if allowed_keys not in cls._classes:
418435
class SpecificStrictDict(cls):
419436
__slots__ = allowed_keys_tuple
437+
420438
def __repr__(self):
421-
return "{%s}" % ', '.join('"{0!s}": {0!r}'.format(k,v) for (k,v) in self.iteritems())
439+
return "{%s}" % ', '.join('"{0!s}": {0!r}'.format(k) for k in self.iterkeys())
440+
422441
cls._classes[allowed_keys] = SpecificStrictDict
423442
return cls._classes[allowed_keys]
424443

425444

426445
class SemiStrictDict(StrictDict):
427-
__slots__ = ('_extras')
446+
__slots__ = ('_extras', )
428447
_classes = {}
448+
429449
def __getattr__(self, attr):
430450
try:
431451
super(SemiStrictDict, self).__getattr__(attr)
@@ -434,6 +454,7 @@ def __getattr__(self, attr):
434454
return self.__getattribute__('_extras')[attr]
435455
except KeyError as e:
436456
raise AttributeError(e)
457+
437458
def __setattr__(self, attr, value):
438459
try:
439460
super(SemiStrictDict, self).__setattr__(attr, value)

mongoengine/base/document.py

Lines changed: 13 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,6 @@
1414
from mongoengine.errors import (ValidationError, InvalidDocumentError,
1515
LookUpError, FieldDoesNotExist)
1616
from mongoengine.python_support import PY3, txt_type
17-
1817
from mongoengine.base.common import get_document, ALLOW_INHERITANCE
1918
from mongoengine.base.datastructures import (
2019
BaseDict,
@@ -150,7 +149,6 @@ def __setattr__(self, name, value):
150149
# Handle dynamic data only if an initialised dynamic document
151150
if self._dynamic and not self._dynamic_lock:
152151

153-
field = None
154152
if not hasattr(self, name) and not name.startswith('_'):
155153
DynamicField = _import_class("DynamicField")
156154
field = DynamicField(db_field=name)
@@ -183,8 +181,8 @@ def __setattr__(self, name, value):
183181
except AttributeError:
184182
self__initialised = False
185183
# Check if the user has created a new instance of a class
186-
if (self._is_document and self__initialised
187-
and self__created and name == self._meta.get('id_field')):
184+
if (self._is_document and self__initialised and
185+
self__created and name == self._meta.get('id_field')):
188186
super(BaseDocument, self).__setattr__('_created', False)
189187

190188
super(BaseDocument, self).__setattr__(name, value)
@@ -328,7 +326,7 @@ def to_mongo(self, use_db_field=True, fields=None):
328326

329327
if value is not None:
330328

331-
if isinstance(field, (EmbeddedDocumentField)):
329+
if isinstance(field, EmbeddedDocumentField):
332330
if fields:
333331
key = '%s.' % field_name
334332
embedded_fields = [
@@ -417,10 +415,11 @@ def validate(self, clean=True):
417415

418416
def to_json(self, *args, **kwargs):
419417
"""Converts a document to JSON.
420-
:param use_db_field: Set to True by default but enables the output of the json structure with the field names and not the mongodb store db_names in case of set to False
418+
:param use_db_field: Set to True by default but enables the output of the json structure with the field names
419+
and not the mongodb store db_names in case of set to False
421420
"""
422421
use_db_field = kwargs.pop('use_db_field', True)
423-
return json_util.dumps(self.to_mongo(use_db_field), *args, **kwargs)
422+
return json_util.dumps(self.to_mongo(use_db_field), *args, **kwargs)
424423

425424
@classmethod
426425
def from_json(cls, json_data, created=False):
@@ -570,15 +569,15 @@ def _get_changed_fields(self, inspected=None):
570569
continue
571570
elif (isinstance(data, (EmbeddedDocument, DynamicEmbeddedDocument))
572571
and db_field_name not in changed_fields):
573-
# Find all embedded fields that have been changed
572+
# Find all embedded fields that have been changed
574573
changed = data._get_changed_fields(inspected)
575574
changed_fields += ["%s%s" % (key, k) for k in changed if k]
576575
elif (isinstance(data, (list, tuple, dict)) and
577576
db_field_name not in changed_fields):
578577
if (hasattr(field, 'field') and
579578
isinstance(field.field, ReferenceField)):
580579
continue
581-
elif (isinstance(field, SortedListField) and field._ordering):
580+
elif isinstance(field, SortedListField) and field._ordering:
582581
# if ordering is affected whole list is changed
583582
if any(map(lambda d: field._ordering in d._changed_fields, data)):
584583
changed_fields.append(db_field_name)
@@ -621,18 +620,18 @@ def _delta(self):
621620
else:
622621
set_data = doc
623622
if '_id' in set_data:
624-
del(set_data['_id'])
623+
del set_data['_id']
625624

626625
# Determine if any changed items were actually unset.
627626
for path, value in set_data.items():
628627
if value or isinstance(value, (numbers.Number, bool)):
629628
continue
630629

631-
# If we've set a value that ain't the default value dont unset it.
630+
# If we've set a value that ain't the default value don't unset it.
632631
default = None
633632
if (self._dynamic and len(parts) and parts[0] in
634633
self._dynamic_fields):
635-
del(set_data[path])
634+
del set_data[path]
636635
unset_data[path] = 1
637636
continue
638637
elif path in self._fields:
@@ -666,7 +665,7 @@ def _delta(self):
666665
if default != value:
667666
continue
668667

669-
del(set_data[path])
668+
del set_data[path]
670669
unset_data[path] = 1
671670
return set_data, unset_data
672671

@@ -821,7 +820,6 @@ def _build_index_spec(cls, spec):
821820
parts = key.split('.')
822821
if parts in (['pk'], ['id'], ['_id']):
823822
key = '_id'
824-
fields = []
825823
else:
826824
fields = cls._lookup_field(parts)
827825
parts = []
@@ -981,7 +979,7 @@ def _lookup_field(cls, parts):
981979
if hasattr(getattr(field, 'field', None), 'lookup_member'):
982980
new_field = field.field.lookup_member(field_name)
983981
elif cls._dynamic and (isinstance(field, DynamicField) or
984-
getattr(getattr(field, 'document_type'), '_dynamic')):
982+
getattr(getattr(field, 'document_type'), '_dynamic')):
985983
new_field = DynamicField(db_field=field_name)
986984
else:
987985
# Look up subfield on the previous field or raise

0 commit comments

Comments
 (0)