Skip to content

Instantly share code, notes, and snippets.

@theorm
Created January 8, 2013 11:19
Show Gist options
  • Save theorm/4483033 to your computer and use it in GitHub Desktop.
Save theorm/4483033 to your computer and use it in GitHub Desktop.
MongoDB ObjectId converter for Flask framework.
-*- coding: utf-8 -*-
from werkzeug.routing import BaseConverter
from werkzeug.exceptions import BadRequest
import bson
class ObjectIdConverter(BaseConverter):
'''Converts string to :class:`~bson.objectid.ObjectId` and
vise versa::
@app.route('/users/<ObjectId:user_id>', methods=['GET'])
def get_user(user_id):
...
To register it in `Flask`, add it to converters dict::
app.url_map.converters['ObjectId'] = ObjectIdConverter
Alternative registration way::
ObjectIdConverter.register_in_flask(app)
'''
def to_python(self, value):
try:
return bson.ObjectId(value)
except bson.errors.InvalidId as e:
raise BadRequest(e)
def to_url(self, value):
return str(value)
@classmethod
def register_in_flask(cls, flask_app):
flask_app.url_map.converters['ObjectId'] = cls
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment