Flask Snippets

Support PyMongo ObjectIDs in URLs

If you are using MongoDB with Flask you might want to consider adding native support for ObjectIDs to the routing system. With that object IDs will be compressed in URLs and the routing system will reject invalid ObjectIDs automatically.

The object IDs are then automatically compressed by url_for and decompressed by the routing system. To test this you can navigate to http://localhost:5000/users/UQWFb53NMX6iFe0s in the above example which will then expand to ObjectId('5105856f9dcd317ea215ed2c')

This snippet by Armin Ronacher can be used freely for
anything you like. Consider it public domain.

Comments

base64 encoder/decoder
by taehyun kang
on 2013-05-17 @ 14:29

if you don't want to have itsdangerous installed and use this snippet, an alternative is using base64 module from python's standard library. it has urlsafe_b64encode, urlsafe_b64decode that do what their name describe.