How to use the mongoengine.fields function in mongoengine

To help you get started, we’ve selected a few mongoengine examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github umutbozkurt / django-rest-framework-mongoengine / tests / test_basic.py View on Github external
from django.core.exceptions import ImproperlyConfigured
from django.test import TestCase
from mongoengine import Document, fields
from rest_framework import serializers

from rest_framework_mongoengine.serializers import DocumentSerializer

from .utils import dedent


class CustomField(fields.BaseField):
    pass


class OneFieldModel(Document):
    str_field = fields.StringField()


class AutoFieldModel(Document):
    auto_field = fields.SequenceField(primary_key=True)


class RegularModel(Document):
    """
    A model class for testing regular flat fields.
    """
    str_field = fields.StringField()
    str_regex_field = fields.StringField(regex="^valid_regex")
    url_field = fields.URLField()
    email_field = fields.EmailField()
    int_field = fields.IntField()
    long_field = fields.LongField()
github umutbozkurt / django-rest-framework-mongoengine / rest_framework_mongoengine / utils.py View on Github external
)

REFERENCING_FIELD_TYPES = (
    me_fields.ReferenceField,
    me_fields.CachedReferenceField,
    me_fields.GenericReferenceField
)

EMBEDDING_FIELD_TYPES = (
    me_fields.EmbeddedDocumentField,
    me_fields.GenericEmbeddedDocumentField
)

COMPOUND_FIELD_TYPES = (
    me_fields.DictField,
    me_fields.ListField
)


def get_relation_info(model_field):
    return RelationInfo(
        model_field=model_field,
        related_model=getattr(model_field, 'document_type', None)
    )


def get_field_info(model):
    """
    Given a model class, returns a `FieldInfo` instance, which is a
    `namedtuple`, containing metadata about the various field types on the model
    including information about their relationships.
    """
github zenweasel / ChromeCaster / chromecaster / models.py View on Github external
from mongoengine import Document, register_connection, EmbeddedDocument, fields

register_connection('default', 'chromecaster')


class Settings(Document):
    setting = fields.StringField(primary_key=True)


class Media(Document):

    type = fields.StringField()
    file_id = fields.StringField(primary_key=True)
    artist = fields.StringField()
    title = fields.StringField()
    filename = fields.StringField()
    path = fields.StringField()
    album = fields.StringField()
    description = fields.StringField()
    genre = fields.StringField()
    bpm = fields.DecimalField()
    tags = fields.DictField()
    image = fields.StringField()

    def get_collection(self):
        return self._get_collection()


class PlayListItem(EmbeddedDocument):
    media_item = fields.ReferenceField('Media')
    sort_order = fields.IntField()
github MongoEngine / django-mongoengine / django_mongoengine / sessions.py View on Github external
settings, 'MONGOENGINE_SESSION_DB_ALIAS',
    DEFAULT_CONNECTION_NAME)

# a setting for the name of the collection used to store sessions
MONGOENGINE_SESSION_COLLECTION = getattr(
    settings, 'MONGOENGINE_SESSION_COLLECTION',
    'django_session')

# a setting for whether session data is stored encoded or not
MONGOENGINE_SESSION_DATA_ENCODE = getattr(
    settings, 'MONGOENGINE_SESSION_DATA_ENCODE',
    True)


class MongoSession(Document):
    session_key = fields.StringField(primary_key=True, max_length=40)
    session_data = fields.StringField() if MONGOENGINE_SESSION_DATA_ENCODE \
                                        else fields.DictField()
    expire_date = fields.DateTimeField()

    meta = {
        'collection': MONGOENGINE_SESSION_COLLECTION,
        'db_alias': MONGOENGINE_SESSION_DB_ALIAS,
        'allow_inheritance': False,
        'indexes': [
            {
                'fields': ['expire_date'],
                'expireAfterSeconds': 0
            }
        ]
    }
github jucacrispim / mongomotor / mongomotor / fields.py View on Github external
def __get__(self, instance, owner):

        if instance is None:
            return self

        super_meth = super().__get__
        if isinstance(self.field, ReferenceField) and self._auto_dereference:
            r = asynchronize(super_meth)(instance, owner)
        else:
            r = super_meth(instance, owner)

        return r


class ListField(ComplexBaseField, fields.ListField):
    pass


class DictField(ComplexBaseField, fields.DictField):
    pass


class GridFSProxy(fields.GridFSProxy, metaclass=AsyncGenericMetaclass):

    delete = Async()
    new_file = Async()
    put = Async()
    read = Async()
    replace = Async()
    close = Async()
github sunshaoyan / ISeeNN / ISeeNN / search_web / models.py View on Github external
def __str__(self):
        return "%s(%s)" % (self.server_name, self.server_ip)


"""
We only save the path on local disk, rather than the image data into the database,
in order to reduce database memory cost. As a result, the image may be moved from
the saved path.
"""


class DBImage(Document):
    server = fields.ObjectIdField(required=True)
    path = fields.StringField(required=True)
    mime_type = fields.StringField(required=True)
    width = fields.IntField(required=True)
    height = fields.IntField(required=True)
    source = fields.StringField()
    meta = {
        'indexes': [
            {
                'fields': ['path'],
                'unique': True
            },
            '#source'
        ]
    }


class UserUploadImage(Document):
    data = fields.ImageField(required=True, size=(1024, 1024), thumbnail_size=(640, 200))
    feature = fields.BinaryField()
github matchbox / flask-mongorest-swagger / flask_mongorest_swagger.py View on Github external
LIST_METHODS = [methods.List, methods.Create, methods.BulkUpdate]
DETAIL_METHODS = [methods.Update, methods.Fetch, methods.Delete]


DEFAULT_METHOD_SUMMARY = {
    methods.List: 'List all %ss',
    methods.Create: 'Create a new %s',
    methods.BulkUpdate: 'Bulk update of %ss',
    methods.Update: 'Update a single %s',
    methods.Fetch: 'Get a single %s',
    methods.Delete: 'Delete a %s'
}


FIELD_TO_TYPE = {
    fields.StringField: 'string',
    fields.IntField: 'int',
    fields.FloatField: 'float',
    fields.BooleanField: 'boolean',
    fields.DateTimeField: 'Date',
    fields.ObjectIdField: 'string'}


def jsonify(data):
    response = _jsonify(data)
    response.headers['Access-Control-Allow-Origin'] = '*'
    return response


def all_values(_name, obj, *args, **kwargs):
    value = getattr(obj, _name, None)
    if value:
github zamarrowski / nemesis / models / report.py View on Github external
import pytz
from datetime import datetime

from mongoengine import DynamicDocument, fields

from models.user import UserSlack
from common.config import options
from common import constants


class UserStatusReport(DynamicDocument):
    user = fields.ReferenceField(UserSlack, required=True)
    status = fields.IntField(choices=constants.USER_STATUS, max_length=1, required=True)
    reported_at = fields.DateTimeField(required=True)
    comments = fields.StringField(required=False)

    meta = {
        'ordering': ['-reported_at']
    }

    @classmethod
    def clean(self):
        self.reported_at = datetime.utcnow()

    @property
    def reported(self, timezone=options.nemesis_timezone):
        current_tz = pytz.timezone(timezone)
        reported_at = self.reported_at.replace(tzinfo=pytz.utc).astimezone(current_tz)
        return '{datetime:%d-%m-%Y %H:%M:%S}'.format(datetime=reported_at)

    @property
github qwiglydee / drf-mongo-filters / drf_mongo_filters / filtersets.py View on Github external
if fields is None:
            fields = model._fields_ordered

        docfilters = {} # unordered
        for name in set(declared_filters.keys()) | set(fields) | set(['id']):
            if name in exclude:
                continue
            if name in declared_filters:
                docfilters[name] = declared_filters[name]
            else:
                docfilters[name] = self.filter_for_field(name, model._fields[name], fltargs.get(name,None))

        return docfilters

    default_filters_mapping = {
        mongo_fields.StringField: filters.CharFilter,
        mongo_fields.URLField: filters.CharFilter,
        mongo_fields.EmailField: filters.CharFilter,
        mongo_fields.IntField: filters.IntegerFilter,
        mongo_fields.LongField: filters.IntegerFilter,
        mongo_fields.FloatField: filters.FloatFilter,
        mongo_fields.DecimalField: filters.FloatFilter,
        mongo_fields.BooleanField: filters.BooleanFilter,
        mongo_fields.DateTimeField: filters.DateTimeFilter,
        # mongo_fields.ComplexDateTimeField: filters.DateTimeFilter, #### its' a string!
        # mongo_fields.EmbeddedDocumentField: filters.Filter,
        mongo_fields.ObjectIdField: filters.ObjectIdFilter,
        mongo_fields.ReferenceField: filters.ReferenceFilter,
        # mongo_fields.GenericEmbeddedDocumentField: filters.Filter,
        # mongo_fields.DynamicField: filters.Filter,
        # mongo_fields.ListField: filters.Filter,
        # mongo_fields.SortedListField: filters.Filter,
github jucacrispim / mongomotor / mongomotor / fields.py View on Github external
# instance we don't need a Future
        if instance is None:
            return self

        meth = super().__get__
        if self._auto_dereference:
            if isinstance(instance, EmbeddedDocument):
                # It's used when there's a reference in a EmbeddedDocument.
                # We use it to get the async framework to be used.
                instance._get_db = self.document_type._get_db
            meth = asynchronize(meth)

        return meth(instance, owner)


class ReferenceField(BaseAsyncReferenceField, fields.ReferenceField):
    """A reference to a document that will be automatically dereferenced on
    access (lazily).

    Use the `reverse_delete_rule` to handle what should happen if the document
    the field is referencing is deleted.  EmbeddedDocuments, DictFields and
    MapFields does not support reverse_delete_rule and an
    `InvalidDocumentError` will be raised if trying to set on one of these
    Document / Field types.

    The options are:

      * DO_NOTHING (0)  - don't do anything (default).
      * NULLIFY    (1)  - Updates the reference to null.
      * CASCADE    (2)  - Deletes the documents associated with the reference.
      * DENY       (3)  - Prevent the deletion of the reference object.
      * PULL       (4)  - Pull the reference from a