Python mongoengine.errors.NotUniqueError() Examples

The following are 7 code examples of mongoengine.errors.NotUniqueError(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module mongoengine.errors , or try the search function .
Example #1
Source File: database.py    From cascade-server with Apache License 2.0 6 votes vote down vote up
def update_existing(cls, **kwargs):
        # Create a new object to resolve the UUID to ObjectId
        new_obj = cls(**kwargs)
        existing_obj = new_obj.existing()

        if existing_obj is None:
            try:
                new_obj.save()
                return new_obj
            except NotUniqueError as e:
                new_obj.id = None
                # if a race condition occurs in python, and in object was created, then get that object and update it
                existing_obj = new_obj.existing()

        existing_obj.modify(**kwargs)
        return existing_obj 
Example #2
Source File: database.py    From cascade-server with Apache License 2.0 5 votes vote down vote up
def save(self, *args, **kwargs):
        # this is not recommended as it may overwrite changes and lead to race conditions
        try:
            return super(UniqueDocument, self).save(*args, **kwargs)
        except NotUniqueError:
            self.id = None
            existing = self.existing()
            if existing:
                self.id = existing.id
            return super(UniqueDocument, self).save(*args, **kwargs) 
Example #3
Source File: authorization.py    From auth with MIT License 5 votes vote down vote up
def add_role(self, role, description=None):
        """ Creates a new group """
        new_group = AuthGroup(role=role, creator=self.client)
        try:
            new_group.save()
            return True
        except NotUniqueError:
            return False 
Example #4
Source File: store.py    From patzilla with GNU Affero General Public License v3.0 5 votes vote down vote up
def provision_users(event):

    # Disabled as of 2017-08-09.
    # Enable temporarily again to create "admin" user on daemon start. YMMV.
    return

    users = [

        User(
            fullname = 'Administrator',
            username = 'admin',
            password = 'admin',
            tags     = ['staff'],
            modules  = ['keywords-user', 'family-citations', 'analytics', 'ificlaims', 'depatech', 'sip']),

        """
        User(
            username = 'test@example.com',
            password = 'test',
            fullname = 'Markus Tester',
            tags = ['']
        ),
        """
    ]
    for user in users:
        try:
            if type(user) is User:
                user.save()
        except NotUniqueError as ex:
            pass 
Example #5
Source File: views.py    From sarjitsu with GNU General Public License v3.0 5 votes vote down vote up
def register():
  """
  Registration Form
  """
  form = RegisterForm(request.form)
  if form.validate_on_submit():
    # create an user instance not yet stored in the database
    user = User(username=form.name.data,
                email=form.email.data,
                password=generate_password_hash(form.password.data)
    )
    #current_user=True)
    # Insert the record in our database and commit it
    try:
      user.save()
    except errors.NotUniqueError:
      return render_template("users/register.html",
                             form=form,
                             duplicate=True,
                             user=None)
    except:
      raise

    # Log the user in, as he now has an id
    session['user_id'] = str(user.id)
    session['user'] = user.username
    print "session user_id: %s" % (str(user.id))
    # flash will display a message to the user
    #flash('Thanks for registering')
    # redirect user to the 'home' method of the user module.
    return redirect(url_for('users.home'))
  return render_template("users/register.html", form=form, user=None) 
Example #6
Source File: store.py    From patzilla with GNU Affero General Public License v3.0 4 votes vote down vote up
def add_user(cls, **kwargs):
        """
        MongoDB blueprint:
        {
            _id: ObjectId("545b6c81a42dde3b4f2c8524"),
            userid: "9cff5461-1104-43e7-b23d-9261dabf5ced",
            username: "test@example.org",
            password: "$p5k2$1f4$8ViZsq5E$XF9C2/0Qoalds2PytzhCWC1wbw.V5x1c",
            fullname: "Max Mustermann",
            organization: "Example Inc.",
            homepage: "https://example.org/",
            created: ISODate("2014-11-06T13:41:37.934Z"),
            modified: ISODate("2014-11-06T13:41:37.933Z"),
            tags: [
                "trial"
            ],
            modules: [
                "keywords-user",
                "family-citations",
                "analytics"
            ]
        }
        """


        # Build dictionary of proper object attributes from kwargs
        data = {}
        for field in User._fields:
            if field == 'id': continue
            if field in kwargs and kwargs[field] is not None:
                data[field] = kwargs[field]

        # Sanity checks
        required_fields = ['username', 'password', 'fullname']
        for required_field in required_fields:
            if required_field not in data:
                log.error('Option "--{}" required.'.format(required_field))
                return

        # Create user object and store into database
        user = User(**data)
        try:
            user.save()
            return user
        except NotUniqueError:
            log.error('User with username "{}" already exists.'.format(data['username'])) 
Example #7
Source File: views.py    From patzilla with GNU Affero General Public License v3.0 4 votes vote down vote up
def admin_user_create(request):

    success = False
    success_message = ''
    error = False
    error_messages = []

    if request.method == 'POST':
        fullname = request.params.get('fullname').strip()
        username = request.params.get('username').strip().lower()
        password = request.params.get('password')

        if not fullname:
            error = True
            error_messages.append('Full name must not be empty.')

        if not username:
            error = True
            error_messages.append('Email address / Username must not be empty.')

        if not password:
            error = True
            error_messages.append('Password must not be empty.')

        if not error:
            user = User(username = username, password = password, fullname = fullname, tags = ['trial'])
            try:
                user.save()
                success = True
                success_message = 'User "%s" created.' % username

                fullname = ''
                username = ''

            except NotUniqueError as ex:
                error = True
                error_messages.append('User already exists: %s' % ex)

    tplvars = {
        'username': '',
        'fullname': '',
        'success': success,
        'success_message': success_message,
        'error': error,
        'error_message': '<ul><li>' + '</li><li>'.join(error_messages) + '</li></ul>',
    }

    tplvars.update(dict(request.params))
    tplvars.update(**locals())

    tplvars['success'] = asbool(tplvars['success'])
    tplvars['error'] = asbool(tplvars['error'])
    return tplvars