-
-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Support for Mongoengine in V2.0 #2611
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Draft
Bastian-Kuhn
wants to merge
10
commits into
pallets-eco:master
Choose a base branch
from
Bastian-Kuhn:mongoengine
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from all commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
a727463
Remove flask-mongoengine imports
karpitsky 101cd04
Fix non-ajax ReferenceField
karpitsky 40160ce
Merged karpitsky's changes
Bastian-Kuhn c512320
Merge branch 'karpitsky-mongoengine' into mongoengine
Bastian-Kuhn ae07a0b
Readded missing plugin files
Bastian-Kuhn 1b2f730
Fixed dependency
Bastian-Kuhn 8c05683
Fixed styling in ajax.py
Bastian-Kuhn 3740f8b
Fixed Styling of Files using ox -e style
Bastian-Kuhn 450cf8c
More Style Fixes
Bastian-Kuhn 4c64508
Final Style Fixes
Bastian-Kuhn File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,8 @@ | ||
# flake8: noqa | ||
try: | ||
import mongoengine | ||
except ImportError: | ||
raise Exception("Please install mongoengine in order to use mongoengine backend") | ||
|
||
from .view import ModelView | ||
from .form import EmbeddedForm |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,150 @@ | ||
import mongoengine | ||
|
||
from flask_admin._compat import as_unicode | ||
from flask_admin._compat import iteritems | ||
from flask_admin._compat import string_types | ||
from flask_admin.model.ajax import AjaxModelLoader | ||
from flask_admin.model.ajax import DEFAULT_PAGE_SIZE | ||
|
||
|
||
class QueryAjaxModelLoader(AjaxModelLoader): | ||
def __init__(self, name, model, **options): | ||
""" | ||
Constructor. | ||
|
||
:param fields: | ||
Fields to run query against | ||
""" | ||
super() | ||
|
||
self.model = model | ||
self.fields = options.get("fields") | ||
|
||
self._cached_fields = self._process_fields() | ||
|
||
if not self.fields: | ||
raise ValueError( | ||
"AJAX loading requires `fields` " | ||
f"to be specified for {model}.{self.name}" | ||
) | ||
|
||
def _process_fields(self): | ||
remote_fields = [] | ||
|
||
for field in self.fields: | ||
if isinstance(field, string_types): | ||
attr = getattr(self.model, field, None) | ||
|
||
if not attr: | ||
raise ValueError(f"{self.model}.{field} does not exist.") | ||
|
||
remote_fields.append(attr) | ||
else: | ||
remote_fields.append(field) | ||
|
||
return remote_fields | ||
|
||
def format(self, model): | ||
if not model: | ||
return None | ||
|
||
return (as_unicode(model.pk), as_unicode(model)) | ||
|
||
def get_one(self, pk): | ||
return self.model.objects.filter(pk=pk).first() | ||
|
||
def get_list(self, query, offset=0, limit=DEFAULT_PAGE_SIZE): | ||
query = self.model.objects | ||
|
||
if len(query) > 0: | ||
criteria = None | ||
|
||
for field in self._cached_fields: | ||
flt = {f"{field.name}__icontains": query} | ||
|
||
if not criteria: | ||
criteria = mongoengine.Q(**flt) | ||
else: | ||
criteria |= mongoengine.Q(**flt) | ||
|
||
query = query.filter(criteria) | ||
|
||
if offset: | ||
query = query.skip(offset) | ||
|
||
return query.limit(limit).all() | ||
|
||
|
||
def create_ajax_loader(model, name, field_name, opts): | ||
prop = getattr(model, field_name, None) | ||
|
||
if prop is None: | ||
raise ValueError(f"Model {model} does not have field {field_name}.") | ||
|
||
ftype = type(prop).__name__ | ||
|
||
if ftype in ["ListField", "SortedListField"]: | ||
prop = prop.field | ||
ftype = type(prop).__name__ | ||
|
||
if ftype != "ReferenceField": | ||
raise ValueError(f"Dont know how to convert {ftype} type for AJAX loader") | ||
|
||
remote_model = prop.document_type | ||
return QueryAjaxModelLoader(name, remote_model, **opts) | ||
|
||
|
||
def process_ajax_references(references, view): | ||
def make_name(base, name): | ||
if base: | ||
return (f"{base}-{name}").lower() | ||
return as_unicode(name).lower() | ||
|
||
def handle_field(field, subdoc, base): | ||
ftype = type(field).__name__ | ||
|
||
if ftype in ["ListField", "SortedListField"]: | ||
child_doc = getattr(subdoc, "_form_subdocuments", {}).get(None) | ||
|
||
if child_doc: | ||
handle_field(field.field, child_doc, base) | ||
elif ftype == "EmbeddedDocumentField": | ||
result = {} | ||
|
||
ajax_refs = getattr(subdoc, "form_ajax_refs", {}) | ||
|
||
for field_name, opts in iteritems(ajax_refs): | ||
child_name = make_name(base, field_name) | ||
|
||
if isinstance(opts, dict): | ||
loader = create_ajax_loader( | ||
field.document_type_obj, child_name, field_name, opts | ||
) | ||
else: | ||
loader = opts | ||
|
||
result[field_name] = loader | ||
references[child_name] = loader | ||
|
||
subdoc._form_ajax_refs = result | ||
|
||
child_doc = getattr(subdoc, "_form_subdocuments", None) | ||
if child_doc: | ||
handle_subdoc(field.document_type_obj, subdoc, base) | ||
else: | ||
raise ValueError(f"Failed to process subdocument field {field}") | ||
|
||
def handle_subdoc(model, subdoc, base): | ||
documents = getattr(subdoc, "_form_subdocuments", {}) | ||
|
||
for name, doc in iteritems(documents): | ||
field = getattr(model, name, None) | ||
|
||
if not field: | ||
raise ValueError(f"Invalid subdocument field {model}.{name}") | ||
|
||
handle_field(field, doc, make_name(base, name)) | ||
|
||
handle_subdoc(view.model, view, "") | ||
|
||
return references |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,95 @@ | ||
from mongoengine.base import get_document | ||
from werkzeug.datastructures import FileStorage | ||
from wtforms import fields | ||
|
||
try: | ||
from wtforms.fields.core import _unset_value as unset_value | ||
except ImportError: | ||
from wtforms.utils import unset_value | ||
|
||
from flask_admin.model.fields import InlineFormField | ||
|
||
from . import widgets | ||
|
||
|
||
def is_empty(file_object): | ||
file_object.seek(0) | ||
first_char = file_object.read(1) | ||
file_object.seek(0) | ||
return not bool(first_char) | ||
|
||
|
||
class ModelFormField(InlineFormField): | ||
""" | ||
Customized ModelFormField for MongoEngine EmbeddedDocuments. | ||
""" | ||
|
||
def __init__(self, model, view, form_class, form_opts=None, **kwargs): | ||
super().__init__(form_class, **kwargs) | ||
|
||
self.model = model | ||
if isinstance(self.model, str): | ||
self.model = get_document(self.model) | ||
|
||
self.view = view | ||
self.form_opts = form_opts | ||
|
||
def populate_obj(self, obj, name): | ||
candidate = getattr(obj, name, None) | ||
is_created = candidate is None | ||
if is_created: | ||
candidate = self.model() | ||
setattr(obj, name, candidate) | ||
|
||
self.form.populate_obj(candidate) | ||
|
||
self.view._on_model_change(self.form, candidate, is_created) | ||
|
||
|
||
class MongoFileField(fields.FileField): | ||
""" | ||
GridFS file field. | ||
""" | ||
|
||
widget = widgets.MongoFileInput() | ||
|
||
def __init__(self, label=None, validators=None, **kwargs): | ||
super().__init__(label, validators, **kwargs) | ||
|
||
self._should_delete = False | ||
|
||
def process(self, formdata, data=unset_value): | ||
if formdata: | ||
marker = f"_{self.name}-delete" | ||
if marker in formdata: | ||
self._should_delete = True | ||
|
||
return super().process(formdata, data) | ||
|
||
def populate_obj(self, obj, name): | ||
field = getattr(obj, name, None) | ||
if field is not None: | ||
# If field should be deleted, clean it up | ||
if self._should_delete: | ||
field.delete() | ||
return | ||
|
||
if isinstance(self.data, FileStorage) and not is_empty(self.data.stream): | ||
if not field.grid_id: | ||
func = field.put | ||
else: | ||
func = field.replace | ||
|
||
func( | ||
self.data.stream, | ||
filename=self.data.filename, | ||
content_type=self.data.content_type, | ||
) | ||
|
||
|
||
class MongoImageField(MongoFileField): | ||
""" | ||
GridFS image field. | ||
""" | ||
|
||
widget = widgets.MongoImageInput() |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Please can we copy the error format from other extensions, which will include adding a reference to
flask-admin[mongoengine]
- and setting that up as an extra inpyproject.toml
.