Skip to content

Instantly share code, notes, and snippets.

@haginara
Created May 1, 2020 17:41
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save haginara/965dd11eda8fd0b787efc2f9ecd79d71 to your computer and use it in GitHub Desktop.
Save haginara/965dd11eda8fd0b787efc2f9ecd79d71 to your computer and use it in GitHub Desktop.
Mongo Custom IP Field for PyMongo
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