adierebel / Flask ObjectID (Base64) URL Converter
Cloned from adierebel / Flask ObjectID URL Converter
08 Feb 2018 at 18:51
| 1 | from werkzeug.routing import BaseConverter, ValidationError |
| 2 | from bson.objectid import ObjectId |
| 3 | from bson.errors import InvalidId |
| 4 | from base64 import urlsafe_b64encode, urlsafe_b64decode |
| 5 | |
| 6 | class ObjectIDConverter(BaseConverter): |
| 7 | def to_python(self, value): |
| 8 | try: |
| 9 | Value = urlsafe_b64decode(value.encode('utf-8')) |
| 10 | if not type(Value) is str: |
| 11 | Value = str(Value.decode('utf-8')) |
| 12 | return ObjectId(Value) |
| 13 | |
| 14 | except (InvalidId, ValueError, TypeError): |
| 15 | raise ValidationError() |
| 16 | |
| 17 | def to_url(self, value): |
| 18 | Value = urlsafe_b64encode(value.encode('utf-8')) |
| 19 | if not type(Value) is str: |
| 20 | Value = str(Value.decode('utf-8')) |
| 21 | return Value |
| 22 | |
| 23 | def objectid(value): |
| 24 | try: |
| 25 | return ObjectId(str(value)) |
| 26 | except (InvalidId, ValueError, TypeError): |
| 27 | return None |
| 1 | from flask import Flask, render_template_string |
| 2 | from helper2 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 | Template = ''' |
| 12 | <html> |
| 13 | <head></head> |
| 14 | <body> |
| 15 | <a href='{{ url_for('profile', id='5a56530badfa67061e014c23') }}'>Profile</a> |
| 16 | <br /> |
| 17 | <a href='{{ url_for('user', id='5a56530badfa67061e014c23') }}'>User</a> |
| 18 | </body> |
| 19 | </html |
| 20 | ''' |
| 21 | return render_template_string(Template) |
| 22 | |
| 23 | @app.route('/profile/<ObjectID:id>') |
| 24 | def profile(id): |
| 25 | Output = 'Profile ID: %s' % (id) |
| 26 | return Output |
| 27 | |
| 28 | @app.route('/user/<id>') |
| 29 | def user(id): |
| 30 | # Validate ObjectID |
| 31 | UserID = objectid(id) |
| 32 | if UserID: |
| 33 | Output = 'Profile ID: %s' % (UserID) |
| 34 | else: |
| 35 | Output = 'Invalid UserID' |
| 36 | |
| 37 | return Output |
| 38 | |
| 39 | # Run |
| 40 | if __name__ == "__main__": |
| 41 | app.run() |
To add a comment, please login or register first.
Register or Login