-
Notifications
You must be signed in to change notification settings - Fork 72
HTTP Method Decorators
Thomas Pollet edited this page Aug 6, 2020
·
2 revisions
It may be useful to apply decorators to your API endpoints, for example to implement granular authentication and access control.
The API will apply decorators in the decorators
list to all of the exposed HTTP methods.
Example:
def test_decorator(func):
def api_wrapper(*args, **kwargs):
print(f"decorated method: {func.__name__}")
return func(*args, **kwargs)
return api_wrapper
class User(SAFRSBase, db.Model):
"""
description: User description
"""
__tablename__ = "Users"
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String)
email = db.Column(db.String)
decorators = [test_decorator]
This decorator will also be called on requests to relationship endpoints. If you want to implement a decorator that will only be called on a specific relationship, you can set the decorators
attribute on the relationship, for example:
def test_decorator(func):
def api_wrapper(*args, **kwargs):
print(f"decorated method: {func.__name__}")
return func(*args, **kwargs)
return api_wrapper
class User(SAFRSBase, db.Model):
"""
description: User description
"""
__tablename__ = "Users"
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String)
email = db.Column(db.String)
others= db.relationship('UserOthers')
others.http_methods = ["GET"]
others.decorators = [test_decorator]
class UserOthers(SAFRSBase, db.Model):
"""
description: description of UserOthers, e.g. list of some other instances accessible by the user.
"""
__tablename__ = "UsersOthers"
allow_client_generated_ids = True
http_methods = ['GET', 'POST', 'DELETE']
user_id = db.Column(db.Integer, db.ForeignKey('Users.id'), primary_key=True)
other_id = db.Column(db.Integer, primary_key=True, autoincrement=False)