How to use the mongoengine.DateTimeField 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 / tests / fields / fields.py View on Github external
def test_default_values_set_to_None(self):
        """Ensure that default field values are used even when
        we explcitly initialize the doc with None values.
        """

        class Person(Document):
            name = StringField()
            age = IntField(default=30, required=False)
            userid = StringField(default=lambda: "test", required=True)
            created = DateTimeField(default=datetime.datetime.utcnow)

        # Trying setting values to None
        person = Person(name=None, age=None, userid=None, created=None)

        # Confirm saving now would store values
        data_to_be_saved = sorted(person.to_mongo().keys())
        self.assertEqual(data_to_be_saved, ["age", "created", "userid"])

        self.assertTrue(person.validate() is None)

        self.assertEqual(person.name, person.name)
        self.assertEqual(person.age, person.age)
        self.assertEqual(person.userid, person.userid)
        self.assertEqual(person.created, person.created)

        self.assertEqual(person._data["name"], person.name)
github samuelclay / NewsBlur / apps / profile / models.py View on Github external
return
    
    if user.password == "!":
        return user
        
    algorithm, salt, hash = user.password.split('$', 2)
    encoded_blank = hashlib.sha1(salt + password).hexdigest()
    encoded_username = authenticate(username=username, password=username)
    if encoded_blank == hash or encoded_username == user:
        return user

# Unfinished
class MEmailUnsubscribe(mongo.Document):
    user_id = mongo.IntField()
    email_type = mongo.StringField()
    date = mongo.DateTimeField(default=datetime.datetime.now)
    
    EMAIL_TYPE_FOLLOWS = 'follows'
    EMAIL_TYPE_REPLIES = 'replies'
    EMAIL_TYOE_PRODUCT = 'product'
    
    meta = {
        'collection': 'email_unsubscribes',
        'allow_inheritance': False,
        'indexes': ['user_id', 
                    {'fields': ['user_id', 'email_type'], 
                     'unique': True,
                     'types': False}],
    }
    
    def __unicode__(self):
        return "%s unsubscribed from %s on %s" % (self.user_id, self.email_type, self.date)
github yeti-platform / yeti / core / scheduling.py View on Github external
from core.config.celeryctl import celery_app
from core.config.config import yeti_config
from core.config.mongoengine_extras import TimeDeltaField
from core.database import YetiDocument


class ScheduleEntry(YetiDocument):
    """Base class for Scheduling Entries. Everything that should be scheduled
       must inherit from this"""

    name = StringField(required=True, unique=True)
    enabled = BooleanField(default=True)
    description = StringField()
    frequency = TimeDeltaField()
    status = StringField()
    last_run = DateTimeField()
    lock = BooleanField(default=False)

    # This should be defined in subclasses, to define the name of the celery task
    SCHEDULED_TASK = None

    # This should be defined in subclasses, to set the field values
    default_values = None

    meta = {"allow_inheritance": True}

    def update_status(self, status):
        self.status = status
        self.save()

    @classmethod
    def unlock_all(klass):
github IRC-SPHERE / HyperStream / hyperstream / models / stream.py View on Github external
meta = {
        'collection': 'summaries',
        'indexes': [
            {'fields': ['stream_id']},
            {'fields': ['stream_id', 'datetime'], 'unique': True}
        ],
        'ordering': ['datetime']
    }


class StreamDefinitionModel(Document):
    stream_id = EmbeddedDocumentField(document_type=StreamIdField, required=True)  # , unique=True)
    stream_type = StringField(required=False, min_length=1, max_length=512)
    channel_id = StringField(required=True, min_length=1, max_length=512)
    last_updated = DateTimeField(required=False)
    last_accessed = DateTimeField(required=False)
    calculated_intervals = EmbeddedDocumentListField(document_type=TimeIntervalModel, required=False)
    sandbox = StringField()

    meta = {
        'collection': 'stream_definitions',
        'indexes': [{'fields': ['stream_id'], 'unique': True}],
    }

    def get_calculated_intervals(self):
        return TimeIntervals(map(lambda x: TimeInterval(x.start, x.end), self.calculated_intervals))

    def set_calculated_intervals(self, intervals):
        if intervals is None:
            intervals = []
        self.calculated_intervals = tuple(map(lambda x: TimeIntervalModel(start=x.start, end=x.end), intervals))
github samuelclay / NewsBlur / apps / social / models.py View on Github external
share_key = "S:%s:%s" % (story_feed_id, story_guid_hash)
        following_user_ids = r.sinter(friends_key, share_key)
        following_user_ids = [int(f) for f in following_user_ids]
        if not following_user_ids:
            return None

        social_subs = cls.objects.filter(user_id=user_id, subscription_user_id__in=following_user_ids)
        for social_sub in social_subs:
            social_sub.needs_unread_recalc = True
            social_sub.save()
        return social_subs

class MCommentReply(mongo.EmbeddedDocument):
    reply_id      = mongo.ObjectIdField()
    user_id       = mongo.IntField()
    publish_date  = mongo.DateTimeField()
    comments      = mongo.StringField()
    email_sent    = mongo.BooleanField(default=False)
    liking_users  = mongo.ListField(mongo.IntField())
    
    def to_json(self):
        reply = {
            'reply_id': self.reply_id,
            'user_id': self.user_id,
            'publish_date': relative_timesince(self.publish_date),
            'date': self.publish_date,
            'comments': self.comments,
        }
        return reply
        
    meta = {
        'ordering': ['publish_date'],
github UWFlow / rmc / models / course_alert.py View on Github external
# These set of fields form a partial key; together with an audience
    # identifier from the subclass, forms a complete key.
    BASE_UNIQUE_FIELDS = ['course_id', 'term_id', 'section_type',
            'section_num']

    meta = {
        'indexes': BASE_INDEXES,
        'abstract': True,
    }

    # eg. earth121l
    course_id = me.StringField(required=True)

    # eg. datetime.datetime(2013, 1, 7, 22, 30)
    created_date = me.DateTimeField(required=True)

    # eg. datetime.datetime(2013, 1, 7, 22, 30)
    expiry_date = me.DateTimeField(required=True)

    # Optional fields to specify section to alert on

    # eg. 2013_09. Note that this is our term ID, not Quest's 4-digit ID.
    term_id = me.StringField(default='')

    # eg. LEC, TUT, EXAM. Note uppercase.
    section_type = me.StringField(default='')

    # eg. 001
    section_num = me.StringField(default='')

    TO_DICT_FIELDS = ['id', 'course_id', 'created_date', 'expiry_date',
github xuwenbao / simplebbs / src / posts / models.py View on Github external
from utils.security import (
    Allow,
    Deny,
    EveryOne,
    Owner,
    Authenticated,
)
from utils.mixins import PermissionMixin
from users.models import User

class Comment(EmbeddedDocument):

    author = ReferenceField('users.User')
    content = StringField(max_length=500, required=True)
    create_time = DateTimeField(default=timezone.now)

    __object_name__ = 'Comment'
    __acl__ = [
        (Allow, EveryOne, 'view'),
        (Allow, Authenticated, 'add'),
        (Allow, Owner, 'change'),
        (Allow, Owner, 'delete'),
    ]
    meta = {
        'ordering': ['create_time'],
    }

    @classmethod
    def create_comment(cls, post_id, username, content):
        post = Post.get_by_id(post_id)
        user = User.get_by_uesrname(username)
github UWFlow / rmc / models / user.py View on Github external
'sparse': True,
            },
            'referrer_id',
        ],
    }

    # Randomly generated ID used to access some subset of user's information
    # without going through any ACL. Used for e.g. sharing schedules with non
    # flow users.
    #
    # e.g. A8RLLZTMX
    secret_id = me.StringField()

    # TODO(mack): join_date should be encapsulate in _id, but store it
    # for now, just in case; can remove it when sure that info is in _id
    join_date = me.DateTimeField(required=True)
    join_source = me.IntField(required=True,
            choices=[JoinSource.FACEBOOK, JoinSource.EMAIL])
    referrer_id = me.ObjectIdField(required=False)

    # eg. Mack
    first_name = me.StringField(required=True)

    middle_name = me.StringField()

    # eg. Duan
    last_name = me.StringField(required=True)

    # TODO(mack): check if facebook always returns gender field
    gender = me.StringField(choices=['male', 'female'])

    # eg. 1647810326
github samuelclay / NewsBlur / apps / rss_feeds / models.py View on Github external
if not self.original_page_z or force:
            feed = Feed.get_by_id(self.story_feed_id)
            importer = PageImporter(request=request, feed=feed, story=self)
            original_page = importer.fetch_story()
        else:
            logging.user(request, "~FYFetching ~FGoriginal~FY story page, ~SBfound.")
            original_page = zlib.decompress(self.original_page_z)
        
        return original_page


class MStarredStory(mongo.Document):
    """Like MStory, but not inherited due to large overhead of _cls and _type in
       mongoengine's inheritance model on every single row."""
    user_id                  = mongo.IntField(unique_with=('story_guid',))
    starred_date             = mongo.DateTimeField()
    story_feed_id            = mongo.IntField()
    story_date               = mongo.DateTimeField()
    story_title              = mongo.StringField(max_length=1024)
    story_content            = mongo.StringField()
    story_content_z          = mongo.BinaryField()
    story_original_content   = mongo.StringField()
    story_original_content_z = mongo.BinaryField()
    original_text_z          = mongo.BinaryField()
    story_content_type       = mongo.StringField(max_length=255)
    story_author_name        = mongo.StringField()
    story_permalink          = mongo.StringField()
    story_guid               = mongo.StringField()
    story_hash               = mongo.StringField()
    story_tags               = mongo.ListField(mongo.StringField(max_length=250))
    user_tags                = mongo.ListField(mongo.StringField(max_length=128))
    image_urls               = mongo.ListField(mongo.StringField(max_length=1024))
github dpgaspar / Flask-AppBuilder / flask_appbuilder / security / mongoengine / models.py View on Github external
class User(Document):
    meta = {
        "allow_inheritance": True
    }  # Added for user extension via Mongoengine Document inheritance

    first_name = StringField(max_length=64, required=True)
    last_name = StringField(max_length=64, required=True)
    username = StringField(max_length=64, required=True, unique=True)
    password = StringField(max_length=256)
    active = BooleanField()
    email = StringField(max_length=64, required=True, unique=True)
    last_login = DateTimeField()
    login_count = IntField()
    fail_login_count = IntField()
    roles = ListField(ReferenceField(Role))
    created_on = DateTimeField(default=datetime.datetime.now)
    changed_on = DateTimeField(default=datetime.datetime.now)

    created_by = ReferenceField("self", default=get_user_id())
    changed_by = ReferenceField("self", default=get_user_id())

    @property
    def is_authenticated(self):
        return True

    @property
    def is_active(self):
        return self.active

    @property
    def is_anonymous(self):
        return False