Python peewee.DoesNotExist() Examples

The following are 30 code examples of peewee.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 peewee , or try the search function .
Example #1
Source File: webhandlers.py    From conducthotline.com with Apache License 2.0 6 votes vote down vote up
def details(number):
    number_entry = models.Number.select().where(models.Number.number == number).get()

    try:
        event = (
            models.Event.select()
            .where(models.Event.primary_number_id == number_entry)
            .get()
        )
    except peewee.DoesNotExist:
        event = None

    info = hotline.telephony.lowlevel.get_number_info(number)

    return flask.render_template(
        "numberadmin/details.html",
        number=number_entry,
        event=event,
        info=info,
        NumberPool=models.NumberPool,
    ) 
Example #2
Source File: user.py    From pypi-server with MIT License 6 votes vote down vote up
def get(self, uid):
        try:
            user = Users.get(id=uid)
        except DoesNotExist:
            raise HTTPError(404)

        self.response(dict(
            id=user.id,
            login=user.login,
            email=user.email,
            is_admin=user.is_admin,
            disabled=user.disabled,
            packages=list(
                map(
                    lambda x: x.name,
                    user.package_set
                )
            )
        )) 
Example #3
Source File: login.py    From pypi-server with MIT License 6 votes vote down vote up
def post(self):
        try:
            login, password = self.json['login'], self.json['password']
        except KeyError:
            raise HTTPError(400)

        try:
            user = Users.check(login, password)
        except DoesNotExist:
            raise HTTPError(403)

        self.set_secure_cookie(
            'session',
            (
                user.id,
                self.request.remote_ip,
                IOLoop.current().time()
            ),
            SESSION_DAYS
        )

        return self.response({
            'login': user.login,
            'is_admin': user.is_admin,
        }) 
Example #4
Source File: models.py    From sentinel with MIT License 6 votes vote down vote up
def check_db_schema_version():
    """ Ensure DB schema is correct version. Drop tables if not. """
    db_schema_version = None

    try:
        db_schema_version = Setting.get(Setting.name == 'DB_SCHEMA_VERSION').value
    except (peewee.OperationalError, peewee.DoesNotExist, peewee.ProgrammingError) as e:
        printdbg("[info]: Can't get DB_SCHEMA_VERSION...")

    printdbg("[info]: SCHEMA_VERSION (code) = [%s]" % SCHEMA_VERSION)
    printdbg("[info]: DB_SCHEMA_VERSION = [%s]" % db_schema_version)
    if (SCHEMA_VERSION != db_schema_version):
        printdbg("[info]: Schema version mis-match. Syncing tables.")
        try:
            existing_table_names = db.get_tables()
            existing_models = [m for m in db_models() if m._meta.db_table in existing_table_names]
            if (existing_models):
                printdbg("[info]: Dropping tables...")
                db.drop_tables(existing_models, safe=False, cascade=False)
        except (peewee.InternalError, peewee.OperationalError, peewee.ProgrammingError) as e:
            print("[error] Could not drop tables: %s" % e) 
Example #5
Source File: peewee_validates.py    From peewee-validates with MIT License 6 votes vote down vote up
def validate(self, name, data):
        """
        If there is a problem with the data, raise ValidationError.

        :param name: The name of this field.
        :param data: Dictionary of data for all fields.
        :raises: ValidationError
        """
        super().validate(name, data)
        if self.value is not None:
            try:
                # self.query could be a query like "User.select()" or a model like "User"
                # so ".select().where()" handles both cases.
                self.value = [self.query.select().where(self.lookup_field == v).get() for v in self.value if v]
            except (AttributeError, ValueError, peewee.DoesNotExist):
                raise ValidationError('related', field=self.lookup_field.name, values=self.value) 
Example #6
Source File: model.py    From torpeewee with MIT License 6 votes vote down vote up
def get_or_create(cls, **kwargs):
        defaults = kwargs.pop('defaults', {})
        query = cls.select()
        for field, value in kwargs.items():
            query = query.where(getattr(cls, field) == value)

        try:
            result = await query.get(), False
        except cls.DoesNotExist:
            try:
                if defaults:
                    kwargs.update(defaults)
                with cls._meta.database.atomic():
                    result = await cls.create(**kwargs), True
            except IntegrityError as exc:
                try:
                    result = await query.get(), False
                except cls.DoesNotExist:
                    raise exc
        return result 
Example #7
Source File: model.py    From torpeewee with MIT License 6 votes vote down vote up
def get_or_create(self, **kwargs):
        defaults = kwargs.pop('defaults', {})
        query = self.model_class.select().bind(self.database)
        for field, value in kwargs.items():
            query = query.where(getattr(self.model_class, field) == value)

        try:
            result = await query.get(), False
        except self.model_class.DoesNotExist:
            try:
                if defaults:
                    kwargs.update(defaults)
                result = await self.create(**kwargs), True
            except IntegrityError as exc:
                try:
                    result = await query.get(), False
                except self.model_class.DoesNotExist:
                    raise exc
        return result 
Example #8
Source File: peewee_async.py    From peewee-async with MIT License 6 votes vote down vote up
def get_object(source, *args):
    """Get object asynchronously.

    :param source: mode class or query to get object from
    :param args: lookup parameters
    :return: model instance or raises ``peewee.DoesNotExist`` if object not
        found
    """
    warnings.warn("get_object() is deprecated, Manager.get() "
                  "should be used instead",
                  DeprecationWarning)

    if isinstance(source, peewee.Query):
        query = source
        model = query.model
    else:
        query = source.select()
        model = source

    # Return first object from query
    for obj in (await select(query.where(*args))):
        return obj

    # No objects found
    raise model.DoesNotExist 
Example #9
Source File: highlevel.py    From conducthotline.com with Apache License 2.0 6 votes vote down vote up
def accept_organizer_invitation(
    invitation_id: str, user: dict
) -> Optional[models.Event]:
    try:
        organizer_entry = get_event_organizer(invitation_id)
    except peewee.DoesNotExist:
        return None

    if organizer_entry.user_email != user["email"]:
        return None

    organizer_entry.user_id = user["user_id"]
    organizer_entry.user_name = user["name"]
    organizer_entry.save()

    return organizer_entry.event 
Example #10
Source File: manager.py    From PyPlanet with GNU General Public License v3.0 6 votes vote down vote up
def get_player(self, login=None, pk=None, lock=True):
		"""
		Get player by login or primary key.

		:param login: Login.
		:param pk: Primary Key identifier.
		:param lock: Lock for a sec when receiving.
		:return: Player or exception if not found
		:rtype: pyplanet.apps.core.maniaplanet.models.Player
		"""
		try:
			if login:
				return await Player.get_by_login(login)
			elif pk:
				return await Player.get(pk=pk)
			else:
				raise PlayerNotFound('Player not found.')
		except DoesNotExist:
			if lock:
				await asyncio.sleep(4)
				return await self.get_player(login=login, pk=pk, lock=False)
			else:
				raise PlayerNotFound('Player not found.') 
Example #11
Source File: models.py    From social-relay with GNU Affero General Public License v3.0 6 votes vote down vote up
def get_profile(identifier):
        """Get or create remote profile.

        Fetch it from federation layer if necessary or if the public key is empty for some reason.
        """
        try:
            sender_profile = Profile.get(Profile.identifier == identifier)
            if not sender_profile.public_key:
                raise DoesNotExist
        except DoesNotExist:
            remote_profile = retrieve_remote_profile(identifier)
            if not remote_profile:
                logging.warning("Remote profile %s not found locally or remotely.", identifier)
                return
            sender_profile = Profile.from_remote_profile(remote_profile)
        return sender_profile 
Example #12
Source File: job_manager.py    From dgenies with GNU General Public License v3.0 6 votes vote down vote up
def delete(self):
        """
        Remove a job

        :return:
            * [0] Success of the deletion
            * [1] Error message, if any (else empty string)
        :rtype: (bool, str)
        """
        if not os.path.exists(self.output_dir) or not os.path.isdir(self.output_dir):
            return False, "Job does not exists"
        if MODE == "webserver":
            try:
                job = Job.get(id_job=self.id_job)
            except DoesNotExist:
                pass
            else:
                is_gallery = Gallery.select().where(Gallery.job == job)
                if is_gallery:
                    return False, "Delete a job that is in gallery is forbidden"
                job.delete_instance()
        shutil.rmtree(self.output_dir)
        return True, "" 
Example #13
Source File: job_manager.py    From dgenies with GNU General Public License v3.0 6 votes vote down vote up
def status(self):
        """
        Get job status and error. In webserver mode, get also mem peak and time elapsed

        :return: status and other informations
        :rtype: dict
        """
        if MODE == "webserver":
            try:
                with Job.connect():
                    job = Job.get(Job.id_job == self.id_job)
                    return {"status": job.status, "mem_peak": job.mem_peak, "time_elapsed": job.time_elapsed,
                            "error": job.error}
            except DoesNotExist:
                return {"status": "unknown", "error": ""}
        else:
            try:
                status, error = self.get_status_standalone(True)
                return {"status": status, "mem_peak": None, "time_elapsed": None, "error": error}
            except FileNotFoundError:
                return {"status": "unknown", "error": ""} 
Example #14
Source File: functions.py    From dgenies with GNU General Public License v3.0 6 votes vote down vote up
def is_in_gallery(id_job, mode="webserver"):
        """
        Check whether a job is in the gallery

        :param id_job: job id
        :type id_job: str
        :param mode: webserver or standalone
        :type mode: str
        :return: True if job is in the gallery, else False
        :rtype: bool
        """
        if mode == "webserver":
            from dgenies.database import Gallery, Job
            from peewee import DoesNotExist
            try:
                return len(Gallery.select().where(Gallery.job == Job.get(id_job=id_job))) > 0
            except DoesNotExist:
                return False
        return False 
Example #15
Source File: views.py    From dgenies with GNU General Public License v3.0 6 votes vote down vote up
def ask_upload():
    """
    Ask for upload: to keep a max number of concurrent uploads
    """
    if MODE == "standalone":
        return jsonify({
            "success": True,
            "allowed": True
        })
    try:
        s_id = request.form['s_id']
        with Session.connect():
            session = Session.get(s_id=s_id)
            allowed = session.ask_for_upload(True)
        return jsonify({
            "success": True,
            "allowed": allowed
        })
    except DoesNotExist:
        return jsonify({"success": False, "message": "Session not initialized. Please refresh the page."}) 
Example #16
Source File: Tokens.py    From neo-python with MIT License 5 votes vote down vote up
def execute(self, arguments):
        wallet = PromptData.Wallet

        if len(arguments) != 1:
            print("Please specify the required parameter")
            return False

        hash_string = arguments[0]
        try:
            script_hash = UInt160.ParseString(hash_string)
        except Exception:
            # because UInt160 throws a generic exception. Should be fixed in the future
            print("Invalid script hash")
            return False

        # try to find token and collect some data
        try:
            token = ModelNEP5Token.get(ContractHash=script_hash)
        except peewee.DoesNotExist:
            print(f"Could not find a token with script_hash {arguments[0]}")
            return False

        success = wallet.DeleteNEP5Token(script_hash)
        if success:
            print(f"Token {token.Symbol} with script_hash {arguments[0]} deleted")
        else:
            # probably unreachable to due token check earlier. Better safe than sorrow
            print(f"Could not find a token with script_hash {arguments[0]}")

        return success 
Example #17
Source File: peewee_async.py    From peewee-async with MIT License 5 votes vote down vote up
def get_or_create(self, model_, defaults=None, **kwargs):
        """Try to get an object or create it with the specified defaults.

        Return 2-tuple containing the model instance and a boolean
        indicating whether the instance was created.
        """
        try:
            return (await self.get(model_, **kwargs)), False
        except model_.DoesNotExist:
            data = defaults or {}
            data.update({k: v for k, v in kwargs.items() if '__' not in k})
            return (await self.create(model_, **data)), True 
Example #18
Source File: battle.py    From yobot with GNU General Public License v3.0 5 votes vote down vote up
def _get_group_previous_challenge(self, group: Clan_group):
        Clan_challenge_alias = Clan_challenge.alias()
        query = Clan_challenge.select().where(
            Clan_challenge.cid == Clan_challenge_alias.select(
                peewee.fn.MAX(Clan_challenge_alias.cid)
            ).where(
                Clan_challenge_alias.gid == group.group_id,
                Clan_challenge_alias.bid == group.battle_id,
            )
        )
        try:
            return query.get()
        except peewee.DoesNotExist:
            return None 
Example #19
Source File: cache.py    From spotify-dl with MIT License 5 votes vote down vote up
def check_if_in_cache(search_term):
    """
    Checks if the specified search term is in the local database cache
    and returns the video id if it exists.
    :param search_term: String to be searched for in the cache
    :return A tuple with Boolean and video id if it exists
    """
    try:
        song = Song.get(search_term=search_term)
        return True, song.video_id
    except DoesNotExist:
        return False, None 
Example #20
Source File: model.py    From torpeewee with MIT License 5 votes vote down vote up
def get_or_none(cls, *query, **filters):
        try:
            result = await cls.get(*query, **filters)
        except DoesNotExist:
            result = None
        return result 
Example #21
Source File: peewee_validates.py    From peewee-validates with MIT License 5 votes vote down vote up
def validate(self, data=None, only=None, exclude=None):
        """
        Validate the data for all fields and return whether the validation was successful.
        This method also retains the validated data in ``self.data`` so that it can be accessed later.

        If data for a field is not provided in ``data`` then this validator will check against the
        provided model instance.

        This is usually the method you want to call after creating the validator instance.

        :param data: Dictionary of data to validate.
        :param only: List or tuple of fields to validate.
        :param exclude: List or tuple of fields to exclude from validation.
        :return: True if validation is successful, otherwise False.
        """
        data = data or {}
        only = only or self._meta.only
        exclude = exclude or self._meta.exclude

        for name, field in self.instance._meta.fields.items():
            if name in exclude or (only and name not in only):
                continue
            try:
                data.setdefault(name, getattr(self.instance, name, None))
            except (peewee.DoesNotExist):
                if PEEWEE3:
                    instance_data = self.instance.__data__
                else:
                    instance_data = self.instance._data
                data.setdefault(name, instance_data.get(name, None))

        # This will set self.data which we should use from now on.
        super().validate(data=data, only=only, exclude=exclude)

        if not self.errors:
            self.perform_index_validation(self.data)

        return (not self.errors) 
Example #22
Source File: manager.py    From PyPlanet with GNU General Public License v3.0 5 votes vote down vote up
def register(self, name, description='', app=None, min_level=1, namespace=None):
		"""
		Register a new permission.
		
		:param name: Name of permission
		:param description: Description in english.
		:param app: App instance to retrieve the label.
		:param min_level: Minimum level required.
		:param namespace: Namespace, only for core usage!
		:return: Permission instance.
		"""
		if not namespace and app:
			namespace = app.label
		if not namespace:
			raise Exception('Namespace is required. You should give your app instance with app=app instead!')

		try:
			perm = await self.get_perm(namespace=namespace, name=name)

			# TODO: Implement overrides on min_level here.
			if perm.min_level != min_level:
				perm.min_level = min_level
				await perm.save()

		except DoesNotExist:
			perm = Permission(namespace=namespace, name=name, description=description, min_level=min_level)
			await perm.save()
		return perm 
Example #23
Source File: peewee_validates.py    From peewee-validates with MIT License 5 votes vote down vote up
def validate(self, name, data):
        """
        If there is a problem with the data, raise ValidationError.

        :param name: The name of this field.
        :param data: Dictionary of data for all fields.
        :raises: ValidationError
        """
        super().validate(name, data)
        if self.value is not None:
            try:
                self.value = self.query.get(self.lookup_field == self.value)
            except (AttributeError, ValueError, peewee.DoesNotExist):
                raise ValidationError('related', field=self.lookup_field.name, values=self.value) 
Example #24
Source File: manager.py    From PyPlanet with GNU General Public License v3.0 5 votes vote down vote up
def get_map(self, uid=None):
		"""
		Get map instance by uid.

		:param uid: By uid (pk).
		:return: Player or exception if not found
		"""
		try:
			return await Map.get_by_uid(uid)
		except DoesNotExist:
			raise MapNotFound('Map not found.') 
Example #25
Source File: db.py    From vorta with GNU General Public License v3.0 5 votes vote down vote up
def get_password(self, service, repo_url):
        from vorta.models import RepoPassword
        try:
            keyring_entry = RepoPassword.get(url=repo_url)
            return keyring_entry.password
        except peewee.DoesNotExist:
            return None 
Example #26
Source File: server.py    From ns with MIT License 5 votes vote down vote up
def summarize():
    """
    Get a summary of given links subjected to limit of words.

    Argument in JSON:
    {
      topic: "topic inputted by user",
      words: 150 // words limit
    }

    Return 201 if request is queued, otherwise return 4xx.

    """
    if environ.get("REDIRECT") == "1":
        print("Move to new domain")
        return redirect("http://ns.apps.xiamx.me" + "/summarize", code=301)
    params = request.get_json()

    print("Summarize %s" % params["topic"])

    try:
        cached_summary = Summary.select().where(
            Summary.topic == params["topic"],
            Summary.last_updated.between(
                datetime.today() - timedelta(days=3),
                datetime.today()
            )
        ).order_by(Summary.last_updated.desc()).get()
        print("Summary found in database")
        return jsonify({
            "summary": cached_summary.summary,
            "images": cached_summary.images,
            "links": cached_summary.links,
            "names": cached_summary.names,
            "status": "done"
        }), 200
    except DoesNotExist:
        summary = generate_summary.delay(params["topic"], params["words"])
        tid = summary.task_id
        return jsonify({"status": "created", "task": tid}), 201 
Example #27
Source File: flask_utils.py    From Quiver-alfred with MIT License 5 votes vote down vote up
def get_object_or_404(query_or_model, *query):
    if not isinstance(query_or_model, SelectQuery):
        query_or_model = query_or_model.select()
    try:
        return query_or_model.where(*query).get()
    except DoesNotExist:
        abort(404) 
Example #28
Source File: login.py    From pypi-server with MIT License 5 votes vote down vote up
def find_user(uid, is_admin=False):
    cond = (
        Users.disabled == False,
        Users.id == uid,
    )
    if is_admin:
        cond += (Users.is_admin == is_admin,)

    q = Users.select().where(*cond)

    if not q.count():
        raise DoesNotExist("User doesn't exists")

    return q.limit(1)[0] 
Example #29
Source File: manager.py    From PyPlanet with GNU General Public License v3.0 5 votes vote down vote up
def get_map_by_index(self, index):
		"""
		Get map instance by index id (primary key).

		:param index: Primary key index.
		:return: Map instance or raise exception.
		"""
		try:
			return await Map.get(id=index)
		except DoesNotExist:
			raise MapNotFound('Map not found.') 
Example #30
Source File: highlevel.py    From conducthotline.com with Apache License 2.0 5 votes vote down vote up
def check_if_blocked(event: models.Event, number: str):
    try:
        models.BlockList.get(
            models.BlockList.event == event, models.BlockList.number == number
        )
        return True
    except peewee.DoesNotExist:
        return False