Пример #1
0
 def _reload(self):
     mtimes = {}
     
     while 1: 
         try:
             has_reload = False
             sub_modules = set()
             for filename, module, k in _iter_module_files():
                 
                 filename = os.path.abspath(filename)
                 
                 try:
                     mtime = os.stat(filename).st_mtime
                 except OSError:
                     continue
                 
                 if filename.find(self.base_path)== -1:
                     continue
                 
                 sub_modules.add(k)
                 old_time = mtimes.get(filename)
                 if old_time is None:
                     mtimes[filename] = mtime
                     continue
                 elif mtime > old_time:
                     mtimes[filename] = mtime
                     if module.__name__ in ['__main__']:
                         continue
                     
                     reload(module)
                     has_reload = True
                     logging.info(' * Detected change in %r, reloading', filename)
             
             if has_reload:
                 for k in sub_modules:
                     
                     if k in ['__main__'] or k not in sys.modules:
                         continue
                     del sys.modules[k]
                 
                 #self.importModule('controller')
                 for cls in XApplication.CONTROLLERS.values():
                     __import__(cls.__module__)
                     
         except:
             logging.exception("reload error")
         finally:
             time.sleep(1)
Пример #2
0
    def process(self, request):
        
        logging.update()
        controller  = request.get('c')
        action      = request.get('a')

        if controller and action:
            controller = controller.lower()
            action     = action.lower().replace('_', '')

            try:
                
                controller_class_name = controller.title().replace('_', '') + 'Controller'
                if not XApplication.CONTROLLERS.has_key(controller_class_name):
                    return BadRequest('CONTROLLER NOT FOUND %s' % controller_class_name)
                    
                controller_class = XApplication.CONTROLLERS[controller_class_name]
                if not issubclass(controller_class, XController):
                    return BadRequest('BAD CONTROLLER CLASS')
                    
                controller_instance = controller_class(request, self)
                if not isinstance(controller_instance, XController):
                    return BadRequest('BAD CONTROLLER INSTANCE')
                
                action_method_name = 'do%s'%action.replace('_', '')
                if not hasattr(controller_instance, action_method_name):
                    return BadRequest('METHOD NOT FOUND %s' % action_method_name)
                
                action_method = getattr(controller_instance, action_method_name)
                if not callable(action_method):
                    return BadRequest('%s.%s is not callable' %(controller_class_name, action_method_name) )
                
                kwargs = {}
                spec = inspect.getargspec(action_method)
                func_args = spec.args[1:]
                
                for k in func_args:
                    if request.args.has_key(k):
                        kwargs[k] = request.args.get(k)
                
                # 由函数的默认值获取配置信息
                if spec.defaults:
                    defaults = dict(zip(func_args[-(len(spec.defaults)):], spec.defaults))
                    
                    mimetype = defaults.get('mimetype')
                    if mimetype:
                        controller_instance.mimetype = mimetype
                        
                    charset = defaults.get('charset')
                    if charset in ['gbk', 'utf-8', 'iso-9001']:
                        controller_instance.response.charset = charset
                    
                    read_only = defaults.get('read_only')
                    if read_only is not None:
                        controller_instance.read_only = read_only
                        
                    use_cache = defaults.get('use_cache')
                    if use_cache is not None:
                        controller_instance.use_cache = use_cache
                    
                    status_code = defaults.get('status_code')
                    if status_code:
                        controller_instance.response.status_code = status_code
                        
            except (ImportError, AttributeError) as ex:
                logging.exception("Can't find the method to process")
                return BadRequest('SEARCH METHOD ERROR %s' % ex)
                
            except Exception as ex:
                logging.exception(ex)
                return self.handleException(controller=controller, action=action, ex=ex)             
           
            try:
                controller_instance.action = action
                
                with BlockProfiler("[XWEB] ACTION EXECTION"):
                    if controller_instance.beforeAction():
                        action_method(**kwargs)
                        controller_instance.afterAction()
                        if not controller_instance.commit():
                            if not (hasattr(controller_instance, 'onCommitFail') 
                                and callable(controller_instance.onCommitFail)
                                and controller_instance.onCommitFail()):
                                return abort(500, 'COMMENT FAILED')
                
                context = controller_instance.context
                content_type = controller_instance.content_type
                status_code = controller_instance.response.status_code
                
                if status_code == 200:
                    if content_type == 'json':
                        controller_instance.response.data = json.dumps(getattr(controller_instance, 'json', ''))
                    elif content_type == 'text':
                        pass
                    else:
                        
                        if hasattr(controller_instance, 'template') and controller_instance.template:
                            template_name = controller_instance.template
                        else:
                            template_name = "%s/%s.html" % (controller, action)
                        
                        if hasattr(controller_instance, 'render') and callable(controller_instance.render):
                            controller_instance.response.data = controller_instance.render(action=action)
                        else:
                            controller_instance.response.data = self.render(template_name, context)
                elif status_code in [301, 302]:
                    pass
                else:
                    return abort(status_code, context.get('description'))
            except Exception, ex:
                if self.use_debuger:
                    raise
                if hasattr(controller_instance, 'handleException') and callable(controller_instance.handleException):
                    kwargs['action'] = action
                    kwargs['ex'] = ex
                    controller_instance.handleException(**kwargs)
                else:
                    logging.exception("error in process action")
                    return self.handleException(controller, action, ex)
                    
            finally:
Пример #3
0
 def update(self):
     try:
         self.cache_client.set(self.cache_key, self.data)
     except:
         logging.exception("vector cache update failed")
Пример #4
0
    def commit(self):
        '''
        '''

        deletes = []
        updates = []
        news = []
        db_names = set()

        for entity_class_name in self.entity_list.keys():
            entity_dict = self.entity_list.get(entity_class_name)
            for entity_id in entity_dict.keys():
                entity = entity_dict.get(entity_id)
                if entity.isDelete():
                    entity.onDelete()
                elif entity.isNew():
                    entity.onNew()
                elif entity.isDirty():
                    entity.onUpdate()
                else:
                    continue

        self.bad_entitys = []
        for entity_class_name in self.entity_list.keys():
            entity_dict = self.entity_list.get(entity_class_name)
            for entity_id in entity_dict.keys():
                entity = entity_dict.get(entity_id)
                if entity.isDelete():
                    deletes.append(entity)
                elif entity.isNew():
                    news.append(entity)
                elif entity.isDirty():
                    updates.append(entity)
                else:
                    continue

                if entity.isLoadedFromCache():
                    raise ModifyBasedCacheError(
                        "%s(%s) is loaded from cache, so can't be modified!!" %
                        (entity.__class__.__name__, entity.id))

                if self.use_validator and not entity.doValidate():
                    self.bad_entitys.append(entity)

                db_names.add(entity._db)

        if self.use_validator and self.bad_entitys:
            return False

        for name in db_names:
            connection = self.connection_manager.get(name)
            if connection and name == connection.name:
                connection.begin()

        try:
            for entitys in [deletes, updates, news]:
                for entity in entitys:
                    self.sync(entity)

            for name in db_names:
                connection = self.connection_manager.get(name)
                if name == connection.name:
                    connection.commit()

            for entity in deletes:
                try:
                    cache = self.cache_manager.get(entity._cache)
                    if not cache:
                        continue

                    cache_key = self.makeKey(entity.__class__, entity.id)
                    cache.delete(cache_key)
                except:
                    logging.exception("delete cache fail")

            for entitys in [updates, news]:
                for entity in entitys:
                    try:
                        cache = self.cache_manager.get(entity._cache)
                        if not cache:
                            continue
                        cache_key = self.makeKey(entity.__class__, entity.id)
                        cache.set(cache_key, entity.getCacheDict())
                    except:
                        logging.exception("set cache fail")

            return True
        except:
            logging.exception("[XWEB] COMMIT FAILED, ROLLBACK")
            for name in db_names:
                connection = self.connection_manager.get(name)
                if name == connection.name:
                    connection.rollback()
            return False
        finally:
            self.entity_list.clear()
Пример #5
0
 def update(self):
     try:
         self.cache_client.set(self.cache_key, self.data)
     except:
         logging.exception("vector cache update failed")
Пример #6
0
 def commit(self):
     '''
     '''
     
     deletes = []
     updates = []
     news = []
     db_names = set()
     
     for entity_class_name in self.entity_list.keys():
         entity_dict = self.entity_list.get(entity_class_name)
         for entity_id in entity_dict.keys():
             entity = entity_dict.get(entity_id)
             if entity.isDelete():
                 entity.onDelete()
             elif entity.isNew():
                 entity.onNew()
             elif entity.isDirty():
                 entity.onUpdate()
             else:
                 continue
             
     self.bad_entitys = []
     for entity_class_name in self.entity_list.keys():
         entity_dict = self.entity_list.get(entity_class_name)
         for entity_id in entity_dict.keys():
             entity = entity_dict.get(entity_id)
             if entity.isDelete():
                 deletes.append(entity)
             elif entity.isNew():
                 news.append(entity)
             elif entity.isDirty():
                 updates.append(entity)
             else:
                 continue
             
             if entity.isLoadedFromCache():
                 raise ModifyBasedCacheError("%s(%s) is loaded from cache, so can't be modified!!"%(
                     entity.__class__.__name__, entity.id))
             
             if self.use_validator and not entity.doValidate():
                 self.bad_entitys.append(entity)
                 
             db_names.add(entity._db)
             
     if self.use_validator and self.bad_entitys:
         return False
             
     for name in db_names:
         connection = self.connection_manager.get(name)
         if connection and name == connection.name:
             connection.begin()
             
     try:
         for entitys in [deletes, updates, news]:
             for entity in entitys:
                 self.sync(entity)
                 
         for name in db_names:
             connection = self.connection_manager.get(name)
             if name == connection.name:
                 connection.commit()
         
         for entity in deletes:
             try:
                 cache = self.cache_manager.get(entity._cache)
                 if not cache:
                     continue
                 
                 cache_key = self.makeKey(entity.__class__, entity.id)
                 cache.delete(cache_key)
             except:
                 logging.exception("delete cache fail")
             
         for entitys in [updates, news]:
             for entity in entitys:
                 try:
                     cache = self.cache_manager.get(entity._cache)
                     if not cache:
                         continue
                     cache_key = self.makeKey(entity.__class__, entity.id)
                     cache.set(cache_key, entity.getCacheDict())
                 except:
                     logging.exception("set cache fail")
                 
         return True
     except:
         logging.exception("[XWEB] COMMIT FAILED, ROLLBACK")
         for name in db_names:
             connection = self.connection_manager.get(name)
             if name == connection.name:
                 connection.rollback()
         return False
     finally:
         self.entity_list.clear()