Esempio n. 1
0
 def __init__(self, application, request):
     RequestHandler.__init__(self, application, request)
     self._current_user = None
     self.middleware_manager = MiddlewareManager(self)
     self._is_threaded = False
     self._is_toolstar_finished = False
     self.view = dotdict()
     self.db = Mongo.db.ui  #@UndefinedVariable
Esempio n. 2
0
 def __init__(self, application, request):
     RequestHandler.__init__(self, application, request)
     self._current_user = None
     #        self._username = None
     #        self._keep_logged_in=False
     self.middleware_manager = MiddlewareManager(self)
     self._is_threaded = False
     self._is_toolstar_finished = False
     self._is_threaded = False
     self.view = dotdict()
     self.db = Mongo.ui
Esempio n. 3
0
 def __init__(self, application, request):
     RequestHandler.__init__(self, application, request)
     self._current_user = None
     self.middleware_manager = MiddlewareManager(self)
     self._is_threaded = False
     self._is_toolstar_finished = False  
     self.view = dotdict()
     self.db = Mongo.db.ui #@UndefinedVariable
Esempio n. 4
0
    def __init__(self, application, request):
        RequestHandler.__init__(self, application, request)
        self._current_user = None
#        self._username = None
#        self._keep_logged_in=False
        self.middleware_manager = MiddlewareManager(self)
        self._is_threaded = False
        self._is_toolstar_finished = False
        self._is_threaded = False
        self.view = dotdict()  
        self.db = Mongo.ui
Esempio n. 5
0
class BaseHandler(RequestHandler):  
    
    __template_exists_cache = {}
    
    def __init__(self, application, request):
        RequestHandler.__init__(self, application, request)
        self._current_user = None
#        self._username = None
#        self._keep_logged_in=False
        self.middleware_manager = MiddlewareManager(self)
        self._is_threaded = False
        self._is_toolstar_finished = False
        self._is_threaded = False
        self.view = dotdict()  
        self.db = Mongo.ui
        
    def template_exists(self, template_name):
        tmp = self.__template_exists_cache.get(template_name, None)
        if tmp != None:
            print "found in cache: " + template_name
            return tmp
        
        lookup = self._get_template_lookup()
        try:
            new_template = lookup.get_template(template_name)
            if new_template :
                self.__template_exists_cache[template_name] = True
                return True
        except Exception as detail:
            print 'run-time error in BaseRequest::template_exists - ', detail
        self.__template_exists_cache[template_name] = False   
        return False
#        
#        
    def _get_template_lookup(self, extra_imports=None) :
        from views.filters import *        
        Cycler.cycle_registry = {}
        
        filter_imports = [
            'from views.filters import Filters, Cycler',
        ]
        
        if extra_imports:
            filter_imports.extend(extra_imports)
        
        
        if isinstance(options.template_dir, (list, tuple)):
            directory_paths = options.template_dir
        else:
            directory_paths = [options.template_dir]
            
        return TemplateLookup(
            directories=directory_paths,
            module_directory=options.mako_modules_dir,
            output_encoding='utf-8',
            encoding_errors='replace',
            imports=filter_imports
        )
#        


    def render_template(self, template_name, **kwargs):
        lookup = self._get_template_lookup()
        new_template = lookup.get_template(template_name)

        tornado_args = {
            "_": self.locale.translate,
            "current_user": self.get_current_user(),
            "datetime": datetime,
            "escape": escape.xhtml_escape,
            "handler": self,
            "json_encode": escape.json_encode,
            "linkify": escape.linkify,
            "locale": self.locale,
            "request": self.request,
            "reverse_url": self.application.reverse_url,
            "squeeze": escape.squeeze,
            "static_url": self.static_url,
            "url_escape": escape.url_escape,
            "xhtml_escape": escape.xhtml_escape,
            "xsrf_form_html": self.xsrf_form_html
        }
        tornado_args.update(self.ui)

        toolstar_args = {
            "is_logged_in": self.get_current_user() != None,
            "render_as": self.get_argument("render_as", "html"),
            "dict_get" : Filters.dict_get
        }

        kwargs.update(toolstar_args)
        kwargs.update(tornado_args)
        kwargs.update(self.view)
        
        self.middleware_manager.run_view_hooks(view=kwargs)
        
        self.finish(new_template.render(**kwargs))
        
        
        
    def asy_render_template(self, callback, **kwargs):
        http = httpclient.AsyncHTTPClient()
        http.fetch(self.request, callback)
        

    '''
    hook into the end of the request
    '''
    def finish(self, chunk=None):      
        self._is_toolstar_finished = True  
        #run all middleware response hooks
        self.middleware_manager.run_response_hooks()
        if self._is_threaded :
            
            print "Thread finished.  setting ioloop callback..", str(threading.currentThread())
            self._chunk = chunk
            ioloop.IOLoop.instance().add_callback(self.threaded_finish_callback)
            return
            
        super(BaseHandler, self).finish(chunk)
        
    
    '''
     this is called by the ioloop when the thread finally returns.
    '''
    def threaded_finish_callback(self):
        print "In the finish callback thread is ", str(threading.currentThread()) 
        super(BaseHandler, self).finish(self._chunk)
        self._chunk = None;
        
    
    
    '''
    hook into the begining of the request here
    '''
    def prepare(self):
        #run all middleware request hooks
        self.middleware_manager.run_request_hooks()
       
            
    def get_current_user(self):
        return self._current_user
    
        
    def set_current_user(self, user):
        self._current_user = user        
    
    def is_logged_in(self):
        return self.get_current_user() != None
    
    '''
    gets all the request params as a map. cleans them all up ala get_argument(s)
    '''
    def get_arguments_as_dict(self):
        params = {}
        retVals = []
        for key in self.request.arguments:
            values = self.get_arguments(key)
            k = unquote(key)
            if len(values) == 1 :
                params[k] = values[0]
            else :
                params[k] = values
            
        return params
    
    '''
    Same as get_argument but will return a list 
    if no arguments are supplied then a dict of all
    the arguments is returned.
    '''
    def get_arguments(self, name=None, default=None, strip=True):
        if name is None :
            return self.get_arguments_as_dict()
        
        values = self.request.arguments.get(name, None)
        if values is None:
            return default
        
        retVals = []
        for val in values :
            value = self._cleanup_param(val, strip)
            retVals.append(value)
        return retVals
    
    def get_argument(self, name, default=RequestHandler._ARG_DEFAULT, strip=True):
        value = super(BaseHandler, self).get_argument(name, default, strip)
        if value == default :
            return value  
        return unquote(value)
    
    '''
        cleans up any argument
        removes control chars, unescapes, ect
    '''
    def _cleanup_param(self, val, strip=True):
        # Get rid of any weird control chars
        value = re.sub(r"[\x00-\x08\x0e-\x1f]", " ", val)
        value = _unicode(value)
        if strip: value = value.strip()
        return unquote(value)   
    
    def get_username(self):
        if self.get_current_user() :
            return self.get_current_user()['_id']  
        return None
        
    
    def write(self, chunk, status=None):
        if status:
            self.set_status(status)
        
        RequestHandler.write(self, chunk)
    
    def get_error_html(self, status_code, **kwargs):  
        error_handler = JzErrorHandler(self.application, self.request, status_code=status_code)
        return error_handler.get_error_html(status_code, **kwargs) 
Esempio n. 6
0
class BaseHandler(RequestHandler):

    __template_exists_cache = {}

    def __init__(self, application, request):
        RequestHandler.__init__(self, application, request)
        self._current_user = None
        #        self._username = None
        #        self._keep_logged_in=False
        self.middleware_manager = MiddlewareManager(self)
        self._is_threaded = False
        self._is_toolstar_finished = False
        self._is_threaded = False
        self.view = dotdict()
        self.db = Mongo.ui

    def template_exists(self, template_name):
        tmp = self.__template_exists_cache.get(template_name, None)
        if tmp != None:
            print "found in cache: " + template_name
            return tmp

        lookup = self._get_template_lookup()
        try:
            new_template = lookup.get_template(template_name)
            if new_template:
                self.__template_exists_cache[template_name] = True
                return True
        except Exception as detail:
            print 'run-time error in BaseRequest::template_exists - ', detail
        self.__template_exists_cache[template_name] = False
        return False
#
#

    def _get_template_lookup(self, extra_imports=None):
        from views.filters import *
        Cycler.cycle_registry = {}

        filter_imports = [
            'from views.filters import Filters, Cycler',
        ]

        if extra_imports:
            filter_imports.extend(extra_imports)

        if isinstance(options.template_dir, (list, tuple)):
            directory_paths = options.template_dir
        else:
            directory_paths = [options.template_dir]

        return TemplateLookup(directories=directory_paths,
                              module_directory=options.mako_modules_dir,
                              output_encoding='utf-8',
                              encoding_errors='replace',
                              imports=filter_imports)


#

    def render_template(self, template_name, **kwargs):
        lookup = self._get_template_lookup()
        new_template = lookup.get_template(template_name)

        tornado_args = {
            "_": self.locale.translate,
            "current_user": self.get_current_user(),
            "datetime": datetime,
            "escape": escape.xhtml_escape,
            "handler": self,
            "json_encode": escape.json_encode,
            "linkify": escape.linkify,
            "locale": self.locale,
            "request": self.request,
            "reverse_url": self.application.reverse_url,
            "squeeze": escape.squeeze,
            "static_url": self.static_url,
            "url_escape": escape.url_escape,
            "xhtml_escape": escape.xhtml_escape,
            "xsrf_form_html": self.xsrf_form_html
        }
        tornado_args.update(self.ui)

        toolstar_args = {
            "is_logged_in": self.get_current_user() != None,
            "render_as": self.get_argument("render_as", "html"),
            "dict_get": Filters.dict_get
        }

        kwargs.update(toolstar_args)
        kwargs.update(tornado_args)
        kwargs.update(self.view)

        self.middleware_manager.run_view_hooks(view=kwargs)

        self.finish(new_template.render(**kwargs))

    def asy_render_template(self, callback, **kwargs):
        http = httpclient.AsyncHTTPClient()
        http.fetch(self.request, callback)

    '''
    hook into the end of the request
    '''

    def finish(self, chunk=None):
        self._is_toolstar_finished = True
        #run all middleware response hooks
        self.middleware_manager.run_response_hooks()
        if self._is_threaded:

            print "Thread finished.  setting ioloop callback..", str(
                threading.currentThread())
            self._chunk = chunk
            ioloop.IOLoop.instance().add_callback(
                self.threaded_finish_callback)
            return

        super(BaseHandler, self).finish(chunk)

    '''
     this is called by the ioloop when the thread finally returns.
    '''

    def threaded_finish_callback(self):
        print "In the finish callback thread is ", str(
            threading.currentThread())
        super(BaseHandler, self).finish(self._chunk)
        self._chunk = None

    '''
    hook into the begining of the request here
    '''

    def prepare(self):
        #run all middleware request hooks
        self.middleware_manager.run_request_hooks()

    def get_current_user(self):
        return self._current_user

    def set_current_user(self, user):
        self._current_user = user

    def is_logged_in(self):
        return self.get_current_user() != None

    '''
    gets all the request params as a map. cleans them all up ala get_argument(s)
    '''

    def get_arguments_as_dict(self):
        params = {}
        retVals = []
        for key in self.request.arguments:
            values = self.get_arguments(key)
            k = unquote(key)
            if len(values) == 1:
                params[k] = values[0]
            else:
                params[k] = values

        return params

    '''
    Same as get_argument but will return a list 
    if no arguments are supplied then a dict of all
    the arguments is returned.
    '''

    def get_arguments(self, name=None, default=None, strip=True):
        if name is None:
            return self.get_arguments_as_dict()

        values = self.request.arguments.get(name, None)
        if values is None:
            return default

        retVals = []
        for val in values:
            value = self._cleanup_param(val, strip)
            retVals.append(value)
        return retVals

    def get_argument(self,
                     name,
                     default=RequestHandler._ARG_DEFAULT,
                     strip=True):
        value = super(BaseHandler, self).get_argument(name, default, strip)
        if value == default:
            return value
        return unquote(value)

    '''
        cleans up any argument
        removes control chars, unescapes, ect
    '''

    def _cleanup_param(self, val, strip=True):
        # Get rid of any weird control chars
        value = re.sub(r"[\x00-\x08\x0e-\x1f]", " ", val)
        value = _unicode(value)
        if strip: value = value.strip()
        return unquote(value)

    def get_username(self):
        if self.get_current_user():
            return self.get_current_user()['_id']
        return None

    def write(self, chunk, status=None):
        if status:
            self.set_status(status)

        RequestHandler.write(self, chunk)

    def get_error_html(self, status_code, **kwargs):
        error_handler = JzErrorHandler(self.application,
                                       self.request,
                                       status_code=status_code)
        return error_handler.get_error_html(status_code, **kwargs)