Python decorator example

    0

    0

    import functools
    
    user = {'username': 'jose123', 'access_level': 'admin'}
    
    
    # A function that returns a decorator which allows for dynamic access levels
    def make_secure(access_level: str):
      def decorator(func):
        @functools.wraps(func)
        def secure_function(*args, **kwargs):
          if user['access_level'] == access_level:
            return func(*args, **kwargs)
          else:
            return f"No admin permissions for {user['username']}."
    
        return secure_function
      return decorator
    
    
    @make_secure('admin')
    def get_admin_password():
      return '1234'
    
    
    @make_secure('user')
    def get_dashboard_password():
      return 'user: user_password'
    Codiga Logo
    Codiga Hub
    • Rulesets
    • Playground
    • Snippets
    • Cookbooks
    soc-2 icon

    We are SOC-2 Compliance Certified

    G2 high performer medal

    Codiga – All rights reserved 2022.