qlixes / Flask ObjectID URL Converter
Cloned from adierebel / Flask ObjectID URL Converter
09 May 2018 at 10:16
| 1 | from werkzeug.routing import BaseConverter, ValidationError |
| 2 | from bson.objectid import ObjectId |
| 3 | from bson.errors import InvalidId |
| 4 | |
| 5 | class ObjectIDConverter(BaseConverter): |
| 6 | def to_python(self, value): |
| 7 | try: |
| 8 | return ObjectId(str(value)) |
| 9 | except (InvalidId, ValueError, TypeError): |
| 10 | raise ValidationError() |
| 11 | def to_url(self, value): |
| 12 | return str(value) |
| 13 | |
| 14 | def objectid(value): |
| 15 | try: |
| 16 | return ObjectId(str(value)) |
| 17 | except (InvalidId, ValueError, TypeError): |
| 18 | return None |
| 1 | from flask import Flask |
| 2 | from helper import ObjectIDConverter, objectid |
| 3 | |
| 4 | app = Flask(__name__) |
| 5 | |
| 6 | # Register ObjectIDConverter |
| 7 | app.url_map.converters['ObjectID'] = ObjectIDConverter |
| 8 | |
| 9 | @app.route('/') |
| 10 | def index(): |
| 11 | return 'Index Page' |
| 12 | |
| 13 | @app.route('/profile/<ObjectID:id>') |
| 14 | def profile(id): |
| 15 | Output = 'Profile ID: %s' % (id) |
| 16 | return Output |
| 17 | |
| 18 | @app.route('/user/<id>') |
| 19 | def user(id): |
| 20 | # Validate ObjectID |
| 21 | UserID = objectid(id) |
| 22 | if UserID: |
| 23 | Output = 'Profile ID: %s' % (UserID) |
| 24 | else: |
| 25 | Output = 'Invalid UserID' |
| 26 | |
| 27 | return Output |
| 28 | |
| 29 | # Run |
| 30 | if __name__ == "__main__": |
| 31 | app.run() |
To add a comment, please login or register first.
Register or Login