wraps.py 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. from collections.abc import Callable
  2. from functools import wraps
  3. from typing import Optional
  4. from flask_restful import reqparse
  5. from extensions.ext_database import db
  6. from models.account import Tenant
  7. def get_tenant(view: Optional[Callable] = None):
  8. def decorator(view_func):
  9. @wraps(view_func)
  10. def decorated_view(*args, **kwargs):
  11. # fetch json body
  12. parser = reqparse.RequestParser()
  13. parser.add_argument('tenant_id', type=str, required=True, location='json')
  14. parser.add_argument('user_id', type=str, required=True, location='json')
  15. kwargs = parser.parse_args()
  16. user_id = kwargs.get('user_id')
  17. tenant_id = kwargs.get('tenant_id')
  18. del kwargs['tenant_id']
  19. del kwargs['user_id']
  20. try:
  21. tenant_model = db.session.query(Tenant).filter(
  22. Tenant.id == tenant_id,
  23. ).first()
  24. except Exception:
  25. raise ValueError('tenant not found')
  26. if not tenant_model:
  27. raise ValueError('tenant not found')
  28. kwargs['tenant_model'] = tenant_model
  29. kwargs['user_id'] = user_id
  30. return view_func(*args, **kwargs)
  31. return decorated_view
  32. if view is None:
  33. return decorator
  34. else:
  35. return decorator(view)