Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- @app.route('/double/<int:number>')
- def double(number):
- return '%d' % (number * 2)
- class UserConverter(BaseConverter):
- """Converts Users for flask URLs."""
- def to_python(self, value):
- """Called to convert a `value` to its python equivalent.
- Here, we convert `value` to a User.
- """
- # Anytime an invalid value is provided, raise ValidationError. Flask
- # will catch this, and continue searching the other routes. First,
- # check that value is an integer, if not there is no way it could be
- # a user.
- if not value.isdigit():
- raise ValidationError()
- user_id = int(value)
- # Look up the user in the database.
- if user_id not in _database:
- raise ValidationError()
- # Otherwise, return the user.
- return _database[user_id]
- def to_url(self, value):
- """Called to convert a `value` to its `url` equivalent.
- Here we convert `value`, the User object to an integer - the user id.
- """
- return str(value.id)
- app.url_map.converters['user'] = UserConverter
- url_for('find_user', user=user)
- from flask import Flask, url_for
- from werkzeug.routing import BaseConverter, ValidationError
- class User:
- def __init__(self, id, name):
- self.id = id
- self.name = name
- class UserConverter(BaseConverter):
- """Converts Users for flask URLs."""
- def to_python(self, value):
- """Called to convert a `value` to its python equivalent.
- Here, we convert `value` to a User.
- """
- # Anytime an invalid value is provided, raise ValidationError. Flask
- # will catch this, and continue searching the other routes. First,
- # check that value is an integer, if not there is no way it could be
- # a user.
- if not value.isdigit():
- raise ValidationError()
- user_id = int(value)
- # Look up the user in the database.
- if user_id not in _database:
- raise ValidationError()
- # Otherwise, return the user.
- return _database[user_id]
- def to_url(self, value):
- """Called to convert a `value` to its `url` equivalent.
- Here we convert `value`, the User object to an integer - the user id.
- """
- return str(value.id)
- # Create a `database` of users.
- _database = {
- 1: User(1, 'Bob'),
- 2: User(2, 'Jim'),
- 3: User(3, 'Ben')
- }
- app = Flask(__name__)
- app.url_map.converters['user'] = UserConverter
- @app.route('/find/<user:user>')
- def find_user(user):
- return "User: %s" % user.name
- @app.route('/find/<user:user>/extrapath')
- def find_userextra(user):
- return 'User extra: %s' % user.name
- @app.route('/users')
- def list_users():
- # Return some broken HTML showing url's to our users.
- s = ''
- for user in _database.values():
- s += url_for('find_user', user=user) + '<br/>'
- return s
- if __name__ == '__main__':
- app.run(debug=True)
- @app.route('/user/<user:user>/something')
- @app.route('/user/<user:user>/something-else')
- @app.route('/user/<user:user>/)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement