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()

Library

pip install flask pymongo

Run

python run.py

Test

Open http://localhost:5000/profile/5a56530badfa67061e014c23 or http://localhost:5000/user/5a56530badfa67061e014c23

Comments (0)