Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def test_inheritance_to_mongo_keys(self):
"""Ensure that document may inherit fields from a superclass document.
"""
class Person(Document):
name = StringField()
age = IntField()
meta = {'allow_inheritance': True}
class Employee(Person):
salary = IntField()
self.assertEqual(['_cls', 'age', 'id', 'name', 'salary'],
sorted(Employee._fields.keys()))
self.assertEqual(Person(name="Bob", age=35).to_mongo().keys(),
['_cls', 'name', 'age'])
self.assertEqual(Employee(name="Bob", age=35, salary=0).to_mongo().keys(),
['_cls', 'name', 'age', 'salary'])
self.assertEqual(Employee._get_collection_name(),
Person._get_collection_name())
import binascii
import os
from django.db import models
from django.utils import timezone
from django.utils.encoding import python_2_unicode_compatible
from django.utils.translation import ugettext_lazy as _
from django.contrib.auth.hashers import check_password, make_password
from django.contrib.auth.models import _user_has_perm, _user_get_all_permissions, _user_has_module_perms
import mongoengine
from mongoengine.django import auth
from mongoengine import fields, Document, ImproperlyConfigured
class User(Document):
"""
VERSION ISSUES:
In Mongoengine <= 0.9 there is a mongoengine.django subpackage, which
implements mongoengine User document and its integration with django
authentication system.
In Mongoengine >= 0.10 mongoengine.django was extracted from Mongoengine
codebase and moved into a separate repository - django-mongoengine. That
repository contains an AbstractBaseUser class, so that you can just
inherit your User model from it, instead of copy-pasting the following
200 lines of boilerplate code from mongoengine.django.auth.User.
"""
id = fields.IntField(primary_key=True)
username = fields.StringField(required=True)
email = fields.EmailField()
from mongoengine.fields import (
DateTimeField,
EmbeddedDocumentField,
ListField,
ReferenceField,
StringField,
)
class Department(Document):
meta = {"collection": "department"}
name = StringField()
class Role(Document):
meta = {"collection": "role"}
name = StringField()
class Task(EmbeddedDocument):
name = StringField()
deadline = DateTimeField(default=datetime.now)
class Employee(Document):
meta = {"collection": "employee"}
name = StringField()
hired_on = DateTimeField(default=datetime.now)
print "\nYTD Totals:"
year_totals = {}
years = datetime.datetime.now().year - 2009
for y in reversed(range(years)):
now = datetime.datetime.now()
start_date = datetime.datetime(now.year, 1, 1) - dateutil.relativedelta.relativedelta(years=y)
end_date = now - dateutil.relativedelta.relativedelta(years=y)
if end_date > now: end_date = now
year_totals[now.year - y] = _counter(start_date, end_date)
total = cls.objects.all().aggregate(sum=Sum('payment_amount'))
print "\nTotal: $%s" % total['sum']
class MGiftCode(mongo.Document):
gifting_user_id = mongo.IntField()
receiving_user_id = mongo.IntField()
gift_code = mongo.StringField(max_length=12)
duration_days = mongo.IntField()
payment_amount = mongo.IntField()
created_date = mongo.DateTimeField(default=datetime.datetime.now)
meta = {
'collection': 'gift_codes',
'allow_inheritance': False,
'indexes': ['gifting_user_id', 'receiving_user_id', 'created_date'],
}
def __unicode__(self):
return "%s gifted %s on %s: %s (redeemed %s times)" % (self.gifting_user_id, self.receiving_user_id, self.created_date, self.gift_code, self.redeemed)
min_value=0,
help_text='number of images in the payload')
timestamp = mongo.DateTimeField(
required=True,
help_text='page collection timestamp')
@property
def batch(self):
""" Returns the batch in which the page has been retrieved """
try:
return Batch.objects.get(id=self.batch_id)
except Batch.DoesNotExist:
return None
class Batch(mongo.Document):
""" Used to record and report information about batch collection jobs """
batch_id = mongo.StringField(
required=True,
primary_key=True,
max_length=MD5LEN,
min_length=MD5LEN)
urls = mongo.ListField(
mongo.URLField(),
required=True,
help_text='list of all URLs passed to this batch')
failed = mongo.ListField(
mongo.URLField(),
help_text='list of URLs that failed to process')
started = mongo.DateTimeField(
required=True,
help_text='start time of the batch')
import mongoengine as db
import datetime
db.connect(
db=config['mongo']['db'],
host=config['mongo']['host'],
port=config['mongo']['port']
)
source_options = ('transparency', 'phishtank')
matching_types = ('regex', 'fuzzy')
class Whitelist(db.Document):
domain = db.StringField(required=True, max_length=500, unique=True)
class Regex(db.Document):
value = db.StringField(required=True, max_length=500, unique=True)
score = db.IntField(required=False, default=80)
class Fuzzy(db.Document):
value = db.StringField(required=True, unique=True)
likelihood = db.IntField(required=True)
score = db.IntField(required=False, default=80)
class Matching(db.EmbeddedDocument):
name = db.StringField(required=True, choices=matching_types)
value = db.StringField(required=True, max_length=500)
data = db.DictField()
class Matches(db.Document):
timestamp = db.DateTimeField(required=False, default=datetime.datetime.now)
datasource = db.StringField(max_length=50, required=True, choices=source_options)
from csc.nl import get_nl
import mongoengine as mon
class Dataset(mon.Document):
name = mon.StringField(required=True, primary_key=True)
language = mon.StringField()
@property
def nl():
if self.language is None:
raise ValueError("This Dataset is not associated with a natural language")
return get_nl(self.language)
if not hasattr(entity, name):
continue
value = getattr(entity, name)
if value != self.attributes[name]:
result = None
break
return result
attributes = db.DictField(default=dict)
class Asset(db.Document):
def __repr__(self):
return '%s(%s, "%s")' % (self.__class__.__name__, self.path, self.title)
meta = dict(
collection="assets",
ordering=['parents', 'name'],
indexes=[('parents', 'name'), 'parent', 'name', 'path', 'index', 'owner', 'created', 'modified']
)
_indexable = ['title', 'description', 'tags']
_widgets = fields
_component = None
controller = None
id = db.ObjectIdField('_id')
import datetime
from mongoengine import Document
from mongoengine import (
DateTimeField,
StringField,
ReferenceField,
ListField,
FileField,
ImageField,
)
mindate = datetime.date(datetime.MINYEAR, 1, 1)
class ContactGroup(Document):
name = StringField(max_length=60, required=True, unique=True)
def __unicode__(self):
return self.name
def __repr__(self):
return self.name
class Gender(Document):
name = StringField(max_length=60, required=True, unique=True)
def __unicode__(self):
return self.name
def __repr__(self):