Created
January 8, 2013 11:19
-
-
Save theorm/4483033 to your computer and use it in GitHub Desktop.
MongoDB ObjectId converter for Flask framework.
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
-*- 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