from werkzeug.routing import BaseConverter, ValidationError from bson.objectid import ObjectId from bson.errors import InvalidId from base64 import urlsafe_b64encode, urlsafe_b64decode class ObjectIDConverter(BaseConverter): def to_python(self, value): try: Value = urlsafe_b64decode(value.encode('utf-8')) if not type(Value) is str: Value = str(Value.decode('utf-8')) return ObjectId(Value) except (InvalidId, ValueError, TypeError): raise ValidationError() def to_url(self, value): Value = urlsafe_b64encode(value.encode('utf-8')) if not type(Value) is str: Value = str(Value.decode('utf-8')) return Value def objectid(value): try: return ObjectId(str(value)) except (InvalidId, ValueError, TypeError): return None