python - Best practice for repeatedly initializing a class with identical parameters (Pyramid)? -


i want streamline/reduce code, try put initializations of classes repeated parameters in own, extended classes. rest api based on pyramid & cornice.

how initialize pyramid.httpexceptions.httpunauthorized when i'm adding same headers on initialization? applies other http responses initialize them repeatedly without changing parameters.

currently i've come extend class:

class _401(httpunauthorized):     def basic_jwt_header(self):         self.headers.add('www-authenticate','jwt')         self.headers.add('www-authenticate', 'basic realm="please log in"')         return self      def jwt_header(self):         self.headers.add('www-authenticate','jwt')         return self 

which use in view this:

@forbidden_view_config() def authenticate(request):     response = _401()     return _401.basic_jwt_header(response) 

but not feel , right. there better, cleaner way?

since using 2 different methods after instantiating _401 instance, might better off using class-level factory methods, both instance creation and setting desired headers:

class _401(httpunauthorized):      @classmethod     def basic_jwt_header(cls):         ret = cls()         ret.headers.add('www-authenticate','jwt')         ret.headers.add('www-authenticate', 'basic realm="please log in"')         return ret      @classmethod     def jwt_header(cls):         ret = cls()         ret.headers.add('www-authenticate','jwt')         return ret  resp = _401.basic_jwt_header() print resp.headers 

now there's no need creating __init__, or calling super() or whatever. use cls instead of explicit _401 class in support of future subclassing of _401.


Comments