當前位置: 首頁>>代碼示例>>Python>>正文


Python errors.InvalidId方法代碼示例

本文整理匯總了Python中bson.errors.InvalidId方法的典型用法代碼示例。如果您正苦於以下問題:Python errors.InvalidId方法的具體用法?Python errors.InvalidId怎麽用?Python errors.InvalidId使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在bson.errors的用法示例。


在下文中一共展示了errors.InvalidId方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: is_valid

# 需要導入模塊: from bson import errors [as 別名]
# 或者: from bson.errors import InvalidId [as 別名]
def is_valid(cls, oid):
        """Checks if a `oid` string is valid or not.

        :Parameters:
          - `oid`: the object id to validate

        .. versionadded:: 2.3
        """
        if not oid:
            return False

        try:
            ObjectId(oid)
            return True
        except (InvalidId, TypeError):
            return False 
開發者ID:Frank-qlu,項目名稱:recruit,代碼行數:18,代碼來源:objectid.py

示例2: __validate

# 需要導入模塊: from bson import errors [as 別名]
# 或者: from bson.errors import InvalidId [as 別名]
def __validate(self, oid):
        """Validate and use the given id for this ObjectId.

        Raises TypeError if id is not an instance of
        (:class:`basestring` (:class:`str` or :class:`bytes`
        in python 3), ObjectId) and InvalidId if it is not a
        valid ObjectId.

        :Parameters:
          - `oid`: a valid ObjectId
        """
        if isinstance(oid, ObjectId):
            self.__id = oid.binary
        # bytes or unicode in python 2, str in python 3
        elif isinstance(oid, string_type):
            if len(oid) == 24:
                try:
                    self.__id = bytes_from_hex(oid)
                except (TypeError, ValueError):
                    _raise_invalid_id(oid)
            else:
                _raise_invalid_id(oid)
        else:
            raise TypeError("id must be an instance of (bytes, %s, ObjectId), "
                            "not %s" % (text_type.__name__, type(oid))) 
開發者ID:birforce,項目名稱:vnpy_crypto,代碼行數:27,代碼來源:objectid.py

示例3: valid_server

# 需要導入模塊: from bson import errors [as 別名]
# 或者: from bson.errors import InvalidId [as 別名]
def valid_server(self, node=None):
        """Validates node is in the MongoDB instance connected to

        Args:
            node (str): MongoDB Object ID to validate; defaults to local node

        Returns:
            tuple: first element is boolean if valid second is objectId as string

        """
        if node:
            try:
                server = self.ioc.getCollection('JobServer').find_one({'_id': ObjectId(str(node))})
            except InvalidId:
                self.ioc.getLogger().error("Invalid ObjectID passed to bridge info [{0}]".format(node))
                return False, ""
            if server:
                return True, dict(server).get('_id')
            self.ioc.getLogger().error("Failed to find server [{0}] in the database".format(node))
            return False, ""
        return True, self.ioc.getConfig().NodeIdentity 
開發者ID:target,項目名稱:grease,代碼行數:23,代碼來源:bridge.py

示例4: unblock_user

# 需要導入模塊: from bson import errors [as 別名]
# 或者: from bson.errors import InvalidId [as 別名]
def unblock_user(self, user_id=None, perm=None, **kw):
        try:
            user_id = list(map(ObjectId, user_id))
        except InvalidId:
            user_id = []
        users = model.User.query.find({'_id': {'$in': user_id}}).all()
        if not users:
            return dict(error='Select user to unblock')
        unblocked = []
        for user in users:
            ace = model.ACE.deny(model.ProjectRole.by_user(user)._id, perm)
            ace = model.ACL.contains(ace, self.app.acl)
            if ace:
                self.app.acl.remove(ace)
                unblocked.append(str(user._id))
        return dict(unblocked=unblocked) 
開發者ID:apache,項目名稱:allura,代碼行數:18,代碼來源:app.py

示例5: url

# 需要導入模塊: from bson import errors [as 別名]
# 或者: from bson.errors import InvalidId [as 別名]
def url(self, name):
        if self.base_url is None:
            raise ValueError("This file is not accessible via a URL.")
        gridfs, filename = self._get_gridfs(name)
        try:
            file_oid = gridfs.get_last_version(filename=name).__getattr__('_id')
        except NoFile:
            # In case not found by filename
            try:
                # Check is a valid ObjectId
                file_oid = ObjectId(name)
            except (InvalidId, TypeError, ValueError):
                return None
            # Check if exist a file with that ObjectId
            if not gridfs.exists(file_oid):
                return None
        return urljoin(self.base_url, filepath_to_uri(str(file_oid))) 
開發者ID:nesdis,項目名稱:djongo,代碼行數:19,代碼來源:storage.py

示例6: _raise_invalid_id

# 需要導入模塊: from bson import errors [as 別名]
# 或者: from bson.errors import InvalidId [as 別名]
def _raise_invalid_id(oid):
    raise InvalidId(
        "%r is not a valid ObjectId, it must be a 12-byte input"
        " of type %r or a 24-character hex string" % (
            oid, binary_type.__name__)) 
開發者ID:Frank-qlu,項目名稱:recruit,代碼行數:7,代碼來源:objectid.py

示例7: __validate

# 需要導入模塊: from bson import errors [as 別名]
# 或者: from bson.errors import InvalidId [as 別名]
def __validate(self, oid):
        """Validate and use the given id for this ObjectId.

        Raises TypeError if id is not an instance of
        (:class:`basestring` (:class:`str` or :class:`bytes`
        in python 3), ObjectId) and InvalidId if it is not a
        valid ObjectId.

        :Parameters:
          - `oid`: a valid ObjectId
        """
        if isinstance(oid, ObjectId):
            self.__id = oid.__id
        elif isinstance(oid, string_types):
            if len(oid) == 12:
                if isinstance(oid, binary_type):
                    self.__id = oid
                else:
                    _raise_invalid_id(oid)
            elif len(oid) == 24:
                try:
                    self.__id = bytes_from_hex(oid)
                except (TypeError, ValueError):
                    _raise_invalid_id(oid)
            else:
                _raise_invalid_id(oid)
        else:
            raise TypeError("id must be an instance of (%s, %s, ObjectId), "
                            "not %s" % (binary_type.__name__,
                                        text_type.__name__, type(oid))) 
開發者ID:Frank-qlu,項目名稱:recruit,代碼行數:32,代碼來源:objectid.py

示例8: to_internal_value

# 需要導入模塊: from bson import errors [as 別名]
# 或者: from bson.errors import InvalidId [as 別名]
def to_internal_value(self, data):
        try:
            return ObjectId(data)
        except InvalidId as e:
            raise ValidationError(e) 
開發者ID:qwiglydee,項目名稱:drf-mongo-filters,代碼行數:7,代碼來源:fields.py

示例9: mongodb_error_log

# 需要導入模塊: from bson import errors [as 別名]
# 或者: from bson.errors import InvalidId [as 別名]
def mongodb_error_log(func):
    def wrapper(*args, **kwargs):
        try:
            return func(*args, **kwargs)
        except PyMongoError as err:
            tb_content = ' '.join(traceback.format_exception(*sys.exc_info()))
            msg = (
                '\nOperate Mongodb error! \n Func: {}, args: {}, kwargs: {} '
                '\n Error: {} \n {}'
            ).format(func.__name__, args, kwargs, err, tb_content)
            logger.error(msg)
            raise DBError(msg)
        except InvalidId as err:
            logger.error('Invalid BSON ObjectId: {}'.format(err))
    return wrapper 
開發者ID:momosecurity,項目名稱:aswan,代碼行數:17,代碼來源:permission.py

示例10: _raise_invalid_id

# 需要導入模塊: from bson import errors [as 別名]
# 或者: from bson.errors import InvalidId [as 別名]
def _raise_invalid_id(oid):
    raise InvalidId(
        "%r is not a valid ObjectId, it must be a 12-byte input"
        " or a 24-character hex string" % oid) 
開發者ID:birforce,項目名稱:vnpy_crypto,代碼行數:6,代碼來源:objectid.py

示例11: fetch_submission

# 需要導入模塊: from bson import errors [as 別名]
# 或者: from bson.errors import InvalidId [as 別名]
def fetch_submission(self, submissionid):
        try:
            submission = self.submission_manager.get_submission(submissionid, False)
            if not submission:
                raise web.notfound()
        except InvalidId as ex:
            self._logger.info("Invalid ObjectId : %s", submissionid)
            raise web.notfound()

        courseid = submission["courseid"]
        taskid = submission["taskid"]
        course, task = self.get_course_and_check_rights(courseid, taskid)
        return course, task, submission 
開發者ID:UCL-INGI,項目名稱:INGInious,代碼行數:15,代碼來源:submission.py

示例12: _get_one_resource

# 需要導入模塊: from bson import errors [as 別名]
# 或者: from bson.errors import InvalidId [as 別名]
def _get_one_resource(resource, res_id):
    try:
        res = resource.get(_id=res_id)
    except InvalidId:
        res = None
    if not res:
        return error_response(errors.API_RESOURCE_NOT_FOUND, 404)
    else:
        return jsonify(res.to_dict()) 
開發者ID:CommunityHoneyNetwork,項目名稱:CHN-Server,代碼行數:11,代碼來源:views.py

示例13: check_and_return

# 需要導入模塊: from bson import errors [as 別名]
# 或者: from bson.errors import InvalidId [as 別名]
def check_and_return(self, value):
        if not self.allow_blank and value is None:
            self._failure("blank value is not allowed", code='empty_value')
        if isinstance(value, self.convertable) or value is None:
            try:
                return ObjectId(value)
            except InvalidId as e:
                self._failure(str(e), code='invalid_objectid')

        self._failure('value is not %s' % self.value_type.__name__, code='not_objectid') 
開發者ID:Deepwalker,項目名稱:trafaret,代碼行數:12,代碼來源:object_id.py

示例14: serve_media

# 需要導入模塊: from bson import errors [as 別名]
# 或者: from bson.errors import InvalidId [as 別名]
def serve_media(media_id):
    try:
        f = MEDIA_CACHE.fs.get(ObjectId(media_id))
    except (InvalidId, NoFile):
        abort(404)

    resp = app.response_class(f, direct_passthrough=True, mimetype=f.content_type)
    resp.headers.set("Content-Length", f.length)
    resp.headers.set("ETag", f.md5)
    resp.headers.set(
        "Last-Modified", f.uploadDate.strftime("%a, %d %b %Y %H:%M:%S GMT")
    )
    resp.headers.set("Cache-Control", "public,max-age=31536000,immutable")
    resp.headers.set("Content-Encoding", "gzip")
    return resp 
開發者ID:tsileo,項目名稱:microblog.pub,代碼行數:17,代碼來源:app.py

示例15: serve_uploads

# 需要導入模塊: from bson import errors [as 別名]
# 或者: from bson.errors import InvalidId [as 別名]
def serve_uploads(oid, fname):
    try:
        f = MEDIA_CACHE.fs.get(ObjectId(oid))
    except (InvalidId, NoFile):
        abort(404)

    resp = app.response_class(f, direct_passthrough=True, mimetype=f.content_type)
    resp.headers.set("Content-Length", f.length)
    resp.headers.set("ETag", f.md5)
    resp.headers.set(
        "Last-Modified", f.uploadDate.strftime("%a, %d %b %Y %H:%M:%S GMT")
    )
    resp.headers.set("Cache-Control", "public,max-age=31536000,immutable")
    resp.headers.set("Content-Encoding", "gzip")
    return resp 
開發者ID:tsileo,項目名稱:microblog.pub,代碼行數:17,代碼來源:app.py


注:本文中的bson.errors.InvalidId方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。