Python mongoengine.errors.DoesNotExist() Examples

The following are 13 code examples of mongoengine.errors.DoesNotExist(). 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: fields.py    From django-rest-framework-mongoengine with MIT License 6 votes vote down vote up
def to_internal_value(self, value):
        if not isinstance(value, dict):
            self.fail('not_a_dict', input_type=type(value).__name__)
        try:
            doc_name = value['_cls']
            doc_id = value['_id']
        except KeyError:
            self.fail('missing_items')
        try:
            doc_cls = get_document(doc_name)
        except NotRegistered:
            self.fail('undefined_model', doc_cls=doc_name)

        try:
            doc_id = self.pk_field.to_internal_value(doc_id)
        except:
            self.fail('invalid_id', pk_value=repr(doc_id), pk_type=self.pk_field_class.__name__)

        try:
            return doc_cls.objects.only('id').get(id=doc_id)
        except DoesNotExist:
            self.fail('not_found', pk_value=doc_id) 
Example #2
Source File: views.py    From udata with GNU Affero General Public License v3.0 5 votes vote down vote up
def activity_feed():
    activity_keys = request.args.getlist('key')

    feed = AtomFeed(
        current_app.config.get('SITE_TITLE'), feed_url=request.url,
        url=request.url_root)
    activities = (Activity.objects.order_by('-created_at')
                                  .limit(current_site.feed_size))

    for activity in activities.select_related():
        # filter by activity.key
        # /!\ this won't completely honour `feed_size` (only as a max value)
        if activity_keys and activity.key not in activity_keys:
            continue
        try:
            owner = activity.actor or activity.organization
        except DoesNotExist:
            owner = 'deleted'
            owner_url = None
        else:
            owner_url = owner.url_for(_external=True)
        try:
            related = activity.related_to
        except DoesNotExist:
            related = 'deleted'
            related_url = None
        else:
            related_url = related.url_for(_external=True)
        feed.add(
            id='%s#activity=%s' % (
                url_for('site.dashboard', _external=True), activity.id),
            title='%s by %s on %s' % (
                activity.key, owner, related),
            url=related_url,
            author={
                'name': owner,
                'uri': owner_url,
            },
            updated=activity.created_at
        )
    return feed.get_response() 
Example #3
Source File: api.py    From udata with GNU Affero General Public License v3.0 5 votes vote down vote up
def get(self):
        '''Fetch site activity, optionally filtered by user of org.'''
        args = activity_parser.parse_args()
        qs = Activity.objects

        if args['organization']:
            qs = qs(db.Q(organization=args['organization']) |
                    db.Q(related_to=args['organization']))

        if args['user']:
            qs = qs(actor=args['user'])

        qs = qs.order_by('-created_at')
        qs = qs.paginate(args['page'], args['page_size'])

        # Filter out DBRefs
        # Always return a result even not complete
        # But log the error (ie. visible in sentry, silent for user)
        # Can happen when someone manually delete an object in DB (ie. without proper purge)
        safe_items = []
        for item in qs.queryset.items:
            try:
                item.related_to
            except DoesNotExist as e:
                log.error(e, exc_info=True)
            else:
                safe_items.append(item)
        qs.queryset.items = safe_items

        return qs 
Example #4
Source File: threattracking.py    From yeti with Apache License 2.0 5 votes vote down vote up
def create_entities(self, sheet_name, actors_list_info):
        for actor_names, campaigns, tools in actors_list_info:
            primary = actor_names[0]
            # create Actors with aliases
            _actor = Actor.get_or_create(name=primary)
            _actor.aliases = actor_names[1:]
            _actor.save()
            # create the campaign
            for c in campaigns:
                # logging.info(repr(c))
                # BUG Issue #120 - is there a bug where two entities cannot have the same name
                # Naikon the actor conflicts with Naikon the campaign
                _campaign = ''
                try:
                    _campaign = Campaign.get_or_create(name=c)
                except DoesNotExist:
                    _campaign = Campaign.get_or_create(name="CAMPAIGN-" + c)
                _actor.action(_campaign, self.name)
            # create the tools
            for mal in tools:
                _mal = ''
                try:
                    _mal = Malware.get_or_create(name=mal)
                except DoesNotExist:
                    _mal = Malware.get_or_create(name="MALWARE-" + mal)
                _actor.action(_mal, self.name)
        return 
Example #5
Source File: export.py    From yeti with Apache License 2.0 5 votes vote down vote up
def content(self, id):
        """Return export content

        Returns a given export's content.

        :query ObjectID id: Export ID
        :resheader X-Yeti-Export-MD5: The MD5 hash of the exported content. Use it to check the export's integrity
        """
        try:
            e = self.objectmanager.objects.get(id=id)
        except DoesNotExist:
            return render({
                "error": "No Export found for id {}".format(id)
            }), 404
        if e.output_dir.startswith("/"):
            d = e.output_dir
        else:
            d = os.path.join(
                os.path.dirname(
                    os.path.dirname(
                        os.path.dirname(
                            os.path.dirname(os.path.abspath(__file__))))),
                e.output_dir)

        response = make_response(
            send_from_directory(
                d, e.name, as_attachment=True, attachment_filename=e.name))
        response.headers['X-Yeti-Export-MD5'] = e.hash_md5
        return response 
Example #6
Source File: webapp.py    From yeti with Apache License 2.0 5 votes vote down vote up
def load_user(session_token):
    try:
        return User.objects.get(session_token=session_token)
    except DoesNotExist:
        return None 
Example #7
Source File: webapp.py    From yeti with Apache License 2.0 5 votes vote down vote up
def api_auth(request):
    try:
        return User.objects.get(api_key=request.headers.get('X-Api-Key'))
    except DoesNotExist:
        return None 
Example #8
Source File: user_management.py    From yeti with Apache License 2.0 5 votes vote down vote up
def authenticate():
    username = request.environ.get(yeti_config.auth.apache_variable)
    if username is None:
        return False
    try:
        return User.objects.get(username=username)
    except DoesNotExist:
        return create_user(username) 
Example #9
Source File: views.py    From sarjitsu with GNU General Public License v3.0 5 votes vote down vote up
def login():
  """
  Login form
  """
  form = LoginForm(request.form)
  # make sure data are valid, but doesn't validate password is right
  if form.validate_on_submit():
    #user = User.query.filter_by(email=form.email.data).first()
    try:
      user = User.objects.get(username=form.username.data)
      # we use werzeug to validate user's password
      if check_password_hash(user.password, form.password.data): #optional: bool(user)
        # the session can't be modified as it's signed,
        # it's a safe place to store the user id
        session['user_id'] = str(user.id)
        session['user'] = user.username
        # user.current_user = True
        # user.save()
        #flash('Success! Welcome %s!' % user.name)
        return redirect(url_for('home'))
    except errors.DoesNotExist:
      #raise#flash('Wrong email or password', 'error-message')
      return render_template("users/login.html",
                             doesnt_exist=True,
                             form=form,
                             user=None)
  return render_template("users/login.html", form=form, user=None) 
Example #10
Source File: group_test.py    From Arsenal with GNU General Public License v3.0 5 votes vote down vote up
def test_delete(self):
        """
        Test the DeleteGroup function.
        """
        group = Database.create_group()
        data = APIClient.delete_group(self.client, group.name)
        self.assertEqual(data['error'], False)
        with self.assertRaises(DoesNotExist):
            Database.get_group(group.name) 
Example #11
Source File: api_v2.py    From quads with GNU General Public License v3.0 5 votes vote down vote up
def GET(self, **data):
        date = datetime.datetime.now()
        if "date" in data:
            date = datetime.datetime.strptime(data["date"], "%Y-%m-%dt%H:%M:%S")

        if self.name == "moves":
            try:
                _hosts = model.Host.objects()

                result = []
                for _host in _hosts:

                    _scheduled_cloud = _host.default_cloud.name
                    _host_defined_cloud = _host.cloud.name
                    _current_schedule = self.model.current_schedule(host=_host, date=date).first()
                    try:
                        if _current_schedule:
                            _scheduled_cloud = _current_schedule.cloud.name
                        if _scheduled_cloud != _host_defined_cloud:
                            result.append(
                                {
                                    "host": _host.name,
                                    "new": _scheduled_cloud,
                                    "current": _host_defined_cloud,
                                }
                            )
                    except DoesNotExist:
                        continue

                return json.dumps({"result": result})
            except Exception as ex:
                logger.debug(ex)
                logger.info("400 Bad Request")
                cherrypy.response.status = "400 Bad Request"
                return json.dumps({"result": ["400 Bad Request"]}) 
Example #12
Source File: utils.py    From yet-another-image-bed with GNU General Public License v3.0 5 votes vote down vote up
def remove_image(img_id, resp):
    try:
        img = PicBed.objects.get(img_id=img_id)
        base_dir = current_app.config["UPLOAD_BASE_FOLDER"]
        file_path = Path(base_dir) / img.img_name
        if file_path.is_file():
            img.delete()
            file_path.unlink()
            return resp
    except DoesNotExist:
        pass
    abort(404) 
Example #13
Source File: fields.py    From django-rest-framework-mongoengine with MIT License 5 votes vote down vote up
def to_internal_value(self, value):
        if isinstance(value, dict):
            try:
                doc_id = self.parse_id(value['_id'])
            except KeyError:
                self.fail('invalid_input')
        else:
            doc_id = self.parse_id(value)

        try:
            # Use the 'pk' attribute instead of 'id' as the second does not
            # exist when the model has a custom primary key
            return self.get_queryset().only('pk').get(pk=doc_id).to_dbref()
        except DoesNotExist:
            self.fail('not_found', pk_value=doc_id)