@@ -98,25 +98,53 @@ def __validate(self, oid):
9898 raise TypeError ("id must be an instance of (str, ObjectId), "
9999 "not %s" % type (oid ))
100100
101- def url_encode (self ):
101+ def url_encode (self , legacy = False ):
102102 """Get a string representation of this ObjectId safe for use in a url.
103103
104+ The `legacy` parameter is for backwards compatibility only and should
105+ almost always be kept False. It might eventually be removed.
106+
104107 The reverse can be achieved using `url_decode()`.
108+
109+ :Parameters:
110+ - `legacy` (optional): use the legacy byte ordering to represent the
111+ ObjectId. if you aren't positive you need this it is probably best
112+ left as False.
105113 """
106- return self .__id .encode ("hex" )
114+ if legacy :
115+ return self .legacy_str ().encode ("hex" )
116+ else :
117+ return self .__id .encode ("hex" )
107118
108- def url_decode (cls , encoded_oid ):
119+ def url_decode (cls , encoded_oid , legacy = False ):
109120 """Create an ObjectId from an encoded hex string.
110121
122+ The `legacy` parameter is for backwards compatibility only and should
123+ almost always be kept False. It might eventually be removed.
124+
111125 The reverse can be achieved using `url_encode()`.
112126
113127 :Parameters:
114128 - `encoded_oid`: string encoding of an ObjectId (as created
115129 by `url_encode()`)
130+ - `legacy` (optional): use the legacy byte ordering to represent the
131+ ObjectId. if you aren't positive you need this it is probably best
132+ left as False.
116133 """
117- return cls (encoded_oid .decode ("hex" ))
134+ if legacy :
135+ oid = encoded_oid .decode ("hex" )
136+ return cls .from_legacy_str (oid )
137+ else :
138+ return cls (encoded_oid .decode ("hex" ))
118139 url_decode = classmethod (url_decode )
119140
141+ def legacy_str (self ):
142+ return self .__id [7 ::- 1 ] + self .__id [:7 :- 1 ]
143+
144+ def from_legacy_str (cls , legacy_str ):
145+ return cls (legacy_str [7 ::- 1 ] + legacy_str [:7 :- 1 ])
146+ from_legacy_str = classmethod (from_legacy_str )
147+
120148 def __str__ (self ):
121149 return self .__id
122150
0 commit comments