本文整理汇总了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
示例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)))
示例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
示例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)
示例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)))
示例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__))
示例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)))
示例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)
示例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
示例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)
示例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
示例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())
示例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')
示例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
示例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