Created
May 1, 2020 17:41
-
-
Save haginara/965dd11eda8fd0b787efc2f9ecd79d71 to your computer and use it in GitHub Desktop.
Mongo Custom IP Field for PyMongo
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import ipaddress | |
from bson.codec_options import TypeCodec | |
from bson.codec_options import TypeRegistry | |
from bson.codec_options import CodecOptions | |
from bson.int64 import Int64 | |
class IPv4Codec(TypeCodec): | |
python_type = ipaddress.IPv4Address | |
bson_type = Int64 | |
def transform_python(self, value): | |
return Int64(value) | |
def transform_bson(self, value): | |
return ipaddress.ip_address(value) | |
ipv4_codec = IPv4Codec() | |
type_registry = TypeRegistry([ipv4_codec]) | |
codec_options = CodecOptions(type_registry=type_registry) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment