How to use the mongoengine.StringField 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 MongoEngine / mongoengine / benchmarks / test_basic_doc_ops.py View on Github external
def test_big_doc():
    class Contact(EmbeddedDocument):
        name = StringField()
        title = StringField()
        address = StringField()

    class Company(Document):
        name = StringField()
        contacts = ListField(EmbeddedDocumentField(Contact))

    Company.drop_collection()

    def init_company():
        return Company(
            name="MongoDB, Inc.",
            contacts=[
                Contact(name="Contact %d" % x, title="CEO", address="Address %d" % x)
                for x in range(1000)
            ],
        )

    company = init_company()
    print("Big doc to mongo: %.3fms" % (timeit(company.to_mongo, 100) * 10 ** 3))
github IRC-SPHERE / HyperStream / hyperstream / models / factor.py View on Github external
# 
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
# OR OTHER DEALINGS IN THE SOFTWARE.
from mongoengine import EmbeddedDocument, EmbeddedDocumentField, ListField, StringField, BooleanField

from .tool import ToolModel


class OutputPlateDefinitionModel(EmbeddedDocument):
    plate_id = StringField(min_length=1, max_length=512, required=True)
    meta_data_id = StringField(min_length=1, max_length=512, required=True)
    description = StringField(min_length=1, max_length=512, required=True)
    use_provided_values = BooleanField(required=True)


class FactorDefinitionModel(EmbeddedDocument):
    tool = EmbeddedDocumentField(document_type=ToolModel, required=True)
    factor_type = StringField(required=True)
    sources = ListField(field=StringField(min_length=1, max_length=512), required=False)
    sinks = ListField(field=StringField(min_length=1, max_length=512), required=False)
    alignment_node = StringField(min_length=1, max_length=512, required=False)
    splitting_node = StringField(min_length=1, max_length=512, required=False)
    output_plate = EmbeddedDocumentField(document_type=OutputPlateDefinitionModel, required=False)
github StackStorm / st2 / st2common / st2common / models / db / trigger.py View on Github external
stormbase.UIDFieldMixin):
    """
    Attribute:
        name - Trigger name.
        pack - Name of the content pack this trigger belongs to.
        type - Reference to the TriggerType object.
        parameters - Trigger parameters.
    """

    RESOURCE_TYPE = ResourceType.TRIGGER
    UID_FIELDS = ['pack', 'name']

    ref = me.StringField(required=False)
    name = me.StringField(required=True)
    pack = me.StringField(required=True, unique_with='name')
    type = me.StringField()
    parameters = me.DictField()
    ref_count = me.IntField(default=0)

    meta = {
        'indexes': [
            {'fields': ['name']},
            {'fields': ['type']},
            {'fields': ['parameters']},
        ] + stormbase.UIDFieldMixin.get_indexes()
    }

    def __init__(self, *args, **values):
        super(TriggerDB, self).__init__(*args, **values)
        self.ref = self.get_reference().ref
        self.uid = self.get_uid()
github marrow / contentment / web / extras / contentment / components / asset / model.py View on Github external
children = db.ListField(db.GenericReferenceField(), default=list)
    contents = property(lambda self: Asset.objects(parent=self))
    path = db.StringField(default='')
    
    # Basic properties.
    name = db.StringField(max_length=250, required=True) # unique_with="parent"
    title = db.StringField(max_length=250, required=True)
    description = db.StringField()
    
    # Search
    index = db.ListField(db.StringField(), default=[])
    
    # Magic properties.
    immutable = db.BooleanField(default=False)
    default = db.StringField(default="view:contents", max_length=128)
    tags = db.ListField(db.StringField(max_length=32), default=list)
    properties = db.DictField(default=dict)
    acl = db.ListField(db.EmbeddedDocumentField(ACLRule), default=list)
    
    # Ownership and dates.
    owner = db.GenericReferenceField()
    created = db.DateTimeField(default=lambda: datetime.utcnow().replace(microsecond=0))
    modified = db.DateTimeField()
    
    @property
    def acl_(self):
        """Determine the canonical ACL for the current Asset instance.
        
        The method:
        
            1. Load the ACLs (just the ACLs) for all nodes from the current node to the root.
            2. Separate the root ACL (it's special).
github sdayu / pumbaa / pumbaa / models / forums.py View on Github external
author = me.ReferenceField("User", dbref=True)
    
    def get_topic(self):
        topic = Topic.objects(comments__id = self.id).first()
        if topic is None:
            topic = Topic.objects(comments__replies__id = self.id).first()
        if topic is None:
            topic = Topic.objects(comments__replies__replies__id = self.id).first()
        return topic
        
    
class TopicHistory(me.EmbeddedDocument):
    author = me.ReferenceField("User", dbref=True, required=True)
    changed_date = me.DateTimeField(required=True, default=datetime.datetime.now)
    title = me.StringField(required=True)
    description = me.StringField(required=True)
    tags = me.ListField(me.StringField(required=True), required=True)

class Topic(me.Document):
    meta = {'collection' : 'topics'}
    
    title = me.StringField(required=True)
    description = me.StringField(required=True)
    created_date = me.DateTimeField(required=True, default=datetime.datetime.now)
    updated_date = me.DateTimeField(required=True, default=datetime.datetime.now)
    published_date = me.DateTimeField()
    
    status = me.StringField(required=True, default='draft', choices=TOPIC_STATUS)
    """ status: draft, publish, delete """
    
    ip_address  = me.StringField(max_length=100, required=True, default='0.0.0.0')
github pulp / pulp / server / pulp / server / db / model / __init__.py View on Github external
task_id = StringField(required=True)
    worker_name = StringField()
    tags = ListField(StringField())
    state = StringField(choices=constants.CALL_STATES, default=constants.CALL_WAITING_STATE)
    error = DictField(default=None)
    spawned_tasks = ListField(StringField())
    progress_report = DictField()
    task_type = StringField()
    start_time = ISO8601StringField()
    finish_time = ISO8601StringField()
    result = DynamicField()
    group_id = UUIDField(default=None)

    # These are deprecated, and will always be None
    exception = StringField()
    traceback = StringField()

    # For backward compatibility
    _ns = StringField(default='task_status')

    meta = {'collection': 'task_status',
            'indexes': ['-tags', '-state', {'fields': ['-task_id'], 'unique': True}, '-group_id'],
            'allow_inheritance': False,
            'queryset_class': CriteriaQuerySet}

    def save_with_set_on_insert(self, fields_to_set_on_insert):
        """
        Save the current state of the TaskStatus to the database, using an upsert operation.
        The upsert operation will only set those fields if this becomes an insert operation,
        otherwise those fields will be ignored. This also validates the fields according to the
        schema above.
github mikeckennedy / build-pypi-mongodb-webcast-series / part2 / pypi_data_layer / data / package.py View on Github external
class Package(mongoengine.Document):
    id = mongoengine.StringField(primary_key=True)

    created_date = mongoengine.DateTimeField(
        default=datetime.datetime.now)
    summary = mongoengine.StringField(required=True)
    description = mongoengine.StringField()

    home_page = mongoengine.StringField()
    docs_url = mongoengine.StringField()
    package_url = mongoengine.StringField()

    author = mongoengine.StringField()
    author_email = mongoengine.StringField()

    license = mongoengine.StringField()

    languages = mongoengine.ListField(mongoengine.StringField())

    maintainers = mongoengine.ListField(mongoengine.ObjectIdField())
    # health = mongoengine.EmbeddedDocumentField(HealthDoc)

    meta = {
        'db_alias': 'core',
        'collection': 'packages',
        'indexes': [
            'author_email',
            'created_date',
            'license',
            # 'languages.name'
github samuelclay / NewsBlur / apps / social / models.py View on Github external
from utils import json_functions as json

RECOMMENDATIONS_LIMIT = 5
    
class MSocialProfile(mongo.Document):
    user_id              = mongo.IntField(unique=True)
    username             = mongo.StringField(max_length=30, unique=True)
    email                = mongo.StringField()
    bio                  = mongo.StringField(max_length=160)
    blurblog_title       = mongo.StringField(max_length=256)
    custom_bgcolor       = mongo.StringField(max_length=50)
    custom_css           = mongo.StringField()
    photo_url            = mongo.StringField()
    photo_service        = mongo.StringField()
    location             = mongo.StringField(max_length=40)
    website              = mongo.StringField(max_length=200)
    subscription_count   = mongo.IntField(default=0)
    shared_stories_count = mongo.IntField(default=0)
    following_count      = mongo.IntField(default=0)
    follower_count       = mongo.IntField(default=0)
    following_user_ids   = mongo.ListField(mongo.IntField())
    follower_user_ids    = mongo.ListField(mongo.IntField())
    unfollowed_user_ids  = mongo.ListField(mongo.IntField())
    popular_publishers   = mongo.StringField()
    stories_last_month   = mongo.IntField(default=0)
    average_stories_per_month = mongo.IntField(default=0)
    story_count_history  = mongo.ListField()
    feed_classifier_counts = mongo.DictField()
    favicon_color        = mongo.StringField(max_length=6)
    
    meta = {
        'collection': 'social_profile',
github StackStorm / st2 / st2common / st2common / models / db / policy.py View on Github external
policy_type: The type of policy.
        parameters: The specification of input parameters for the policy.
    """

    RESOURCE_TYPE = ResourceType.POLICY
    UID_FIELDS = ['pack', 'name']

    name = me.StringField(required=True)
    ref = me.StringField(required=True)
    pack = me.StringField(
        required=False,
        default=pack_constants.DEFAULT_PACK_NAME,
        unique_with='name',
        help_text='Name of the content pack.',
    )
    description = me.StringField()
    enabled = me.BooleanField(
        required=True,
        default=True,
        help_text='A flag indicating whether this policy is enabled in the system.',
    )
    resource_ref = me.StringField(
        required=True, help_text='The resource that this policy is applied to.'
    )
    policy_type = me.StringField(
        required=True, unique_with='resource_ref', help_text='The type of policy.'
    )
    parameters = me.DictField(help_text='The specification of input parameters for the policy.')

    meta = {'indexes': [{'fields': ['name']}, {'fields': ['resource_ref']}]}

    def __init__(self, *args, **kwargs):
github sdayu / pumbaa / pumbaa / models / photos.py View on Github external
orientation = me.StringField(required=True, default='horizontal', choices=['vertical', 'horizontal'])
    
    def get_album(self):
        album = PhotoAlbum.objects(photos__id = self.id).first()
        return album

class PhotoAlbum(me.Document):
    meta = {'collection' : 'photo_albums'}
    
    name = me.StringField(required=True)
    description = me.StringField(default='')
    event_date = me.DateTimeField()
    shared = me.BooleanField(required=True, default=False)
    
    photos = me.ListField(me.EmbeddedDocumentField(Photo))
    status = me.StringField(required=True, default='draft')
    """ status: draft, publish, delete """
    
    created_date = me.DateTimeField(required=True, default=datetime.datetime.now)
    published_date = me.DateTimeField(required=True, default=datetime.datetime.now)
    updated_date = me.DateTimeField(required=True, default=datetime.datetime.now)
    
    comments = me.ListField(me.EmbeddedDocumentField(forums.Comment))

    user = me.ReferenceField("User", dbref=True, required=True)
        
    def get_photo(self, photo_id):
        for photo in self.photos:
            image = photo.image if photo.image.get() is not None else photo.vimage
            
            if image.filename == photo_id:
                return photo