Skip to content

Instantly share code, notes, and snippets.

@kwatch
Last active November 17, 2015 16:17
Show Gist options
  • Save kwatch/4204380 to your computer and use it in GitHub Desktop.
Save kwatch/4204380 to your computer and use it in GitHub Desktop.
Custom Decorator for View Method in Pyramid 1.3
import sys
from pyramid.view import view_config
from venusian import ATTACH_ATTR # view_config() uses 'venusian' module internally
##
## utility
##
def view_method(fn, **kwargs):
# get frame of class definition
classdef_frame = sys._getframe(2)
classdef_globals = classdef_frame.f_globals
classdef_locals = classdef_frame.f_locals
# set '__module__' var (necessary for 'venusian' module)
__module__ = classdef_globals.get('__name__')
# set hidden local var (necessary for 'venusian' module)
k = ATTACH_ATTR
if k in classdef_locals:
locals()[k] = classdef_locals[k]
#
kwargs['attr'] = fn.__name__
fn = view_config(**kwargs)(fn)
# set hidden local var (necessary for 'venusian' module)
if k not in classdef_locals:
classdef_locals[k] = locals()[k]
return fn
##
## custom decorator for view method
##
def GET(route_name, template):
request_method = 'GET'
def deco(func):
def fn(self):
# ... do something here ...
return func(self)
fn.__name__ = func.__name__ # IMPORTANT!
fn.__doc__ = func.__doc__
#
return view_method(fn,
route_name=route_name, request_method=request_method,
renderer='templates/'+template)
return deco
##
## example of view method
##
class HelloView(object):
def __init__(self, request):
self.request = request
#@view_config(route_name='hello', renderer='templates/hello.pt')
@GET('hello', 'hello.pt')
def hello(self):
return {'title': 'Hello!'}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment