def _install_application(self, application): if application: app_class = application else: app_class = Application tornado_conf = settings.TORNADO_CONF if 'default_handler_class' in tornado_conf and \ isinstance(tornado_conf['default_handler_class'], str): tornado_conf['default_handler_class'] = import_object( tornado_conf['default_handler_class']) else: tornado_conf['default_handler_class'] = import_object( 'applications.core.handler.ErrorHandler') if hasattr(options, 'template_path') and os.path.exists( options.template_path): tornado_conf['template_path'] = options.template_path if hasattr(options, 'static_path') and os.path.exists( options.static_path): tornado_conf['static_path'] = options.static_path if hasattr(options, 'login_url') and os.path.exists(options.login_url): tornado_conf['login_url'] = options.login_url tornado_conf['debug'] = settings.debug self.application = app_class(handlers=self.urls, default_host='', transforms=None, wsgi=False, middlewares=settings.MIDDLEWARE_CLASSES, **tornado_conf)
def required_permissions(*dargs, **dkargs): """权限控制装饰器 """ User = import_object('applications.admin.models.User') SUPER_ADMIN = import_object('applications.configs.settings.SUPER_ADMIN') def wrapper(method): # @functools.wraps(method) def _wrapper(*args, **kargs): code = dargs[0] self = args[0] user_id = self.current_user.get('id') # print(self.current_user, user_id) if int(user_id) in SUPER_ADMIN: return method(*args, **kargs) obj = User.Q.filter(User.id == user_id).first() if obj and obj.permission and code not in obj.permission: if obj.role_permission and code not in obj.role_permission: return self.error('未授权', 401) return method(*args, **kargs) return _wrapper return wrapper
def render(self, **prop): self.dom_id = prop.get("id") self.cols = prop.get("cols") self.sort_sql = prop.get("sort_sql") self.entity_full_name = prop.get("entity") self.query_class = prop.get("query_class") # obj prop `data` func return [(k,v),(k,v)...] self.allow_blank = prop.get("allow_blank") html = list() html.append("<select id='%s' name='%s' class='form-control'>" % (self.dom_id, self.dom_id)) if self.allow_blank: html.append("<option value=''> </option>") if not self.query_class: if not self.entity_full_name: return "<small>Require entity full name.</small>" if self.entity_full_name: cls = import_object(self.entity_full_name) cnn = SessionFactory.new() q = cnn.query(cls) if self.sort_sql: q = q.order_by(self.sort_sql) items = q.all() all = list() for item in items: all.append([(getattr(item, col)) for col in self.cols.split(",")]) for opt in all: html.append("<option value='%s'>%s</option>" % (opt[0], opt[1])) else: obj = import_object(self.query_class)() if hasattr(obj, "data"): items = getattr(obj, "data")() for item in items: html.append("<option value='%s'>%s</option>" % (item[0], item[1])) html.append("</select>") return "".join(html)
def install(plugin_name): register = import_object(plugin_name.strip() + '.register') name = register._handler.__module__ + \ '.' + register._handler.__name__ if models.Plugins.filter(models.Plugins.name == name).count() == 0 : plugin = import_object(name)() plugin.install() # 尝试自加加载 ui_modules.py try: ui_modules = import_object(plugin_name + '.uimodules') for v in dir(ui_modules): if issubclass(getattr(ui_modules,v), UIModule) \ and v != 'UIModule': plugin.add_ui_module(v) except Exception, e: pass # 尝试自加加载 handlers.py try: handlers = import_object(plugin_name + '.handlers') reload(handlers) for v in dir(handlers): if issubclass(getattr(handlers,v), RequestHandler) \ and v != 'RequestHandler': plugin.add_handler(v) except Exception, e: pass
def __call__(self, request): if self._sync_id != cache.client.get(self._sync_key,0): # 重新加载 app handlers app_handlers = self.settings['app_path'].split(os.path.sep).pop() + '.handlers' handlers = import_object(app_handlers) Route._routes = {} for name in handlers.__all__: handler_module = import_object(app_handlers + '.' + name) reload(handler_module) for v in dir(handler_module): o = getattr(handler_module,v) if type(o) is types.ModuleType: reload(o) # 重新加载 plugins from xcat.models import Plugins for plugin in Plugins.select(Plugins.handlers).where(Plugins.handlers != '[]'): for v in Json.decode(plugin.handlers): plugin_module = v.split('.handlers.')[0] + '.handlers' reload(import_object(str(plugin_module))) self.handlers = [] self.named_handlers = {} Route.routes(self) # 标记已同步 self._sync_id = cache.client.get(self._sync_key) return super(Application,self).__call__(request)
def __call__(self, request): if self._sync_id != cache.client.get(self._sync_key, 0): # 重新加载 app handlers app_handlers = self.settings['app_path'].split( os.path.sep).pop() + '.handlers' handlers = import_object(app_handlers) Route._routes = {} for name in handlers.__all__: handler_module = import_object(app_handlers + '.' + name) reload(handler_module) for v in dir(handler_module): o = getattr(handler_module, v) if type(o) is types.ModuleType: reload(o) # 重新加载 plugins from xcat.models import Plugins for plugin in Plugins.select( Plugins.handlers).where(Plugins.handlers != '[]'): for v in Json.decode(plugin.handlers): plugin_module = v.split('.handlers.')[0] + '.handlers' reload(import_object(str(plugin_module))) self.handlers = [] self.named_handlers = {} Route.routes(self) # 标记已同步 self._sync_id = cache.client.get(self._sync_key) return super(Application, self).__call__(request)
def reset(): global _list , _plugins_key , _cache_key _work_plugins = [] _config = {} _list = {} for plugin in models.Plugins.select().order_by(models.Plugins.id.desc()): _work_plugins.append(plugin.name) _config[plugin.name] = Json.decode(plugin.config) # 注册插件路由 for handler in Json.decode(plugin.handlers,[]): import_object(handler) binds = Json.decode(plugin.bind,{}) for event in binds: _list.setdefault(event,[]) for v in binds[event]: v['handler'] = import_object(str(plugin.name)) v['name'] = plugin.name _list[event].append(v) _plugins_key = '|'.join(_work_plugins) cache.client.set(_cache_key,_plugins_key) cache.client.set('xcat.plugins.work_plugins',_work_plugins) cache.client.set('xcat.plugins.config',_config)
def start(): from tornado.log import enable_pretty_logging enable_pretty_logging() tornado.options.parse_command_line() import_object('devsniff.proxy') import_object('devsniff.admin') server_root = dirname(__file__) proxy_settings = dict( debug=tornado_options.debug, template_path=path_join(server_root, "templates"), static_path=path_join(server_root, "static"), ) proxy_app = TornadoWebApplication(route.get_routes(), **proxy_settings) proxy_bind = parse_bind_address(tornado_options.bind) if tornado_options.debug: proxy_app.listen(proxy_bind[1], proxy_bind[0]) else: server = tornado.httpserver.HTTPServer(proxy_app) server.bind(proxy_bind[1], proxy_bind[0]) server.start(0) io_loop = tornado.ioloop.IOLoop.instance() io_loop.add_callback(init_app) io_loop.start()
def install(plugin_name, config=None, callback=None): register = import_object(str(plugin_name).strip() + '.register') name = register._handler.__module__ + \ '.' + register._handler.__name__ plugin_configs = yield gen.Task(_application.cache.get, _cache_key, []) for plugin_data in plugin_configs: if plugin_data.get('name') == name: if callback: callback(False) return plugin = import_object(name)() plugin.install() # 尝试自加加载 ui_modules.py try: ui_modules = import_object(plugin_name + '.uimodules') for v in dir(ui_modules): if issubclass(getattr(ui_modules,v), UIModule) \ and v != 'UIModule': plugin.add_ui_module(v) except Exception, e: pass
def _install_application(self, application): if not self.urls: raise UrlError("urls not found.") if application: app_class = application else: app_class = Application tornado_conf = settings.TORNADO_CONF if 'default_handler_class' in tornado_conf and \ isinstance(tornado_conf['default_handler_class'], basestring): tornado_conf['default_handler_class'] = import_object( tornado_conf['default_handler_class']) else: tornado_conf['default_handler_class'] = import_object( 'torngas.handler.ErrorHandler') tornado_conf['debug'] = settings.DEBUG self.application = app_class(handlers=self.urls, default_host='', transforms=None, wsgi=False, middlewares=settings.MIDDLEWARE_CLASSES, **tornado_conf)
def import_platforms_bak(): for p in __actives__: pm = import_object(p) c = import_object('%s.config' % p) __platform_configs__.append(getattr(c, 'get_plaform_info')()) __platform_id_to_handler__[name_to_id(p)] = getattr( pm, 'get_handlers')() check_uniqueness(__platform_configs__)
def choice_module_(m): if m.startswith(EXCLUDE_PREFIX): import_m = import_object(m.lstrip(EXCLUDE_PREFIX)) check_baseclass_(import_m) if import_m not in non_modules: non_modules.append(import_m) else: import_m = import_object(m) check_baseclass_(import_m) inst_import_m = import_m() if inst_import_m not in modules_lst: modules_lst.append(inst_import_m)
def __init__(self): webapp_settings = dict( debug=tornado_options.debug, autoreload=tornado_options.debug, ) for app in self.enabled_apps: try: import_object('%s.controllers' % app) except Exception as e: warn('Failed to load app %s: %s' % (app, e)) route = import_object('{{cookiecutter.project_slug}}.common.route') controllers = route.route.get_routes() super(ApiApplication, self).__init__(controllers, **webapp_settings)
def urlhelper(self, prefix='', *urllist): """ 路由列表list """ urls = [] for u in urllist: handler = u.get('handler_module', '') if isinstance(handler, basestring): handler_module = '.'.join([prefix, u.get('handler_module', '')]) handler_module = import_object(handler_module) else: handler_module = handler pattern = u.get('pattern') pattern += '?' if pattern.endswith('/') else '/?' path = u.get('path', None) if path: if path != '/': pattern = path + pattern else: pattern = self.path + pattern kw = dict(u.get('kwargs', {})) kw['subapp_name'] = self.subapp_name url_name = ''.join([self.subapp_name, '-', u.get('name')]) url = urlspec(pattern, handler_module, kwargs=kw, name=url_name) urls.append(url) return urls
def get(self): '''停用/启用 分类''' if False == self.validator.success: self.jsonify( success=False, msg=self.validator.error.msg, ) return form_name = self.validator.data.form if form_name.find('app.') != 0 or form_name.find('..') != -1: self.jsonify(success=False, msg='Not Form Name') return locale_code = 'en_US' if hasattr(self, 'locale') and hasattr(self.locale, 'code'): locale_code = self.locale.code form_obj = import_object(form_name)(locale_code=locale_code) #try: #form_obj = import_object(form_name)(locale_code=locale_code) #except Exception, e: #self.jsonify(success=False, msg=str(e)) #return form_obj.xsrf_form_html = self.xsrf_form_html yield gen.Task(form_obj.load_field_data) form_obj.load_data(self.request.arguments) self.jsonify(form=form_obj.to_dict())
def __init__( self, matcher: "Matcher", target: Any, target_kwargs: Dict[str, Any] = None, name: str = None, ) -> None: """Constructs a Rule instance. :arg Matcher matcher: a `Matcher` instance used for determining whether the rule should be considered a match for a specific request. :arg target: a Rule's target (typically a ``RequestHandler`` or `~.httputil.HTTPServerConnectionDelegate` subclass or even a nested `Router`, depending on routing implementation). :arg dict target_kwargs: a dict of parameters that can be useful at the moment of target instantiation (for example, ``status_code`` for a ``RequestHandler`` subclass). They end up in ``target_params['target_kwargs']`` of `RuleRouter.get_target_delegate` method. :arg str name: the name of the rule that can be used to find it in `ReversibleRouter.reverse_url` implementation. """ if isinstance(target, str): # import the Module and instantiate the class # Must be a fully qualified name (module.ClassName) target = import_object(target) self.matcher = matcher # type: Matcher self.target = target self.target_kwargs = target_kwargs if target_kwargs else {} self.name = name
def valid(self, http_req): obj = None if type(self.action) == str: obj = import_object(self.action)() if hasattr(obj, "valid"): return obj.valid() return ""
def urlhelper(self, prefix='', *urllist): """ 路由列表list """ urls = [] for u in urllist: handler = u.get('handler', '') if isinstance(handler, basestring): handler_module = '.'.join([prefix, u.get('handler', '')]) handler_module = import_object(handler_module) else: handler_module = handler pattern = u.get('pattern') # pattern += '?' if pattern.endswith('/') else '/?' path = u.get('path', None) if path: if path != '/': pattern = path + pattern else: pattern = self.path + pattern kw = dict(u.get('kwargs', {})) # url_name = ''.join([self.subapp_name, '-', u.get('name')]) url = urlspec(pattern, handler_module, kwargs=kw, name=u.get('name')) urls.append(url) return urls
def enable_pretty_logging(options=None, logger=None): """Turns on formatted logging output as configured. This is called automaticaly by `tornado.options.parse_command_line` and `tornado.options.parse_config_file`. """ if options is None: from tornado.options import options if options.log_formatter: formatter_cls = import_object(options.log_formatter) if options.logging == 'none': return if logger is None: logger = logging.getLogger() logger.setLevel(getattr(logging, options.logging.upper())) if options.log_file_prefix: channel = logging.handlers.RotatingFileHandler( filename=options.log_file_prefix, maxBytes=options.log_file_max_size, backupCount=options.log_file_num_backups) channel.setFormatter(formatter_cls(color=False)) logger.addHandler(channel) if (options.log_to_stderr or (options.log_to_stderr is None and not logger.handlers)): # Set up color if we are in a tty and curses is installed channel = logging.StreamHandler() channel.setFormatter(formatter_cls()) logger.addHandler(channel)
def manage(): arguments, __ = Command().get_argument_parser().parse_known_args() if arguments.settings: os.environ[SETTINGS_ENVIRONMENT_VARIABLE] = arguments.settings if arguments.python_path: sys.path.insert(0, arguments.python_path) from monstro.conf import settings commands = { 'db': 'monstro.management.commands.db.DatabaseShell', 'migrate': 'monstro.management.commands.migrate.ApplyMigrations', 'new': 'monstro.management.commands.new.NewTemplate', 'run': 'monstro.management.commands.run.RunServer', 'shell': 'monstro.management.commands.shell.Shell', 'test': 'monstro.management.commands.test.Test', } commands.update(getattr(settings, 'commands', {})) try: command = import_object(commands[arguments.command]) except KeyError: print('Unknown command: {}'.format(arguments.command)) command().execute(command().get_argument_parser().parse_args())
def load_application(self, default_host='', transforms=None, wsgi=False): #加载app,进行初始化配置,如无ap参数,则使用内置app初始化 logger_module.logger.load_config() tornado.options.parse_command_line() #tornado把默认的根logger加了handler #把根logger的handler去除,然后重新绑定在tornado的logger下 logging.getLogger().handlers = [] enable_pretty_logging(None, logging.getLogger('tornado')) #加载本地化配置 if self.settings.TRANSLATIONS: try: tornado.locale.load_translations( self.settings.TRANSLATIONS_CONF.translations_dir) except: warnings.warn( 'locale dir load failure,maybe your config file is not set correctly.' ) #初始化app if not self.application: self.application = application_module.AppApplication( handlers=self.urls, default_host=default_host, transforms=transforms, wsgi=wsgi, **self.settings.get_settings('TORNADO_CONF')) self.application.project_path = self.proj_path if self.proj_path.endswith( '/') else self.proj_path + '/' self.application.tmpl = import_object( self.settings.TEMPLATE_ENGINE ) if self.settings.TEMPLATE_ENGINE else None return self.application
def load_middleware(self): if hasattr(settings, 'MIDDLEWARE_CLASSES') \ and len(settings.MIDDLEWARE_CLASSES): for midd_class in settings.MIDDLEWARE_CLASSES: try: cls = import_object(midd_class) except ImportError: raise try: inst = cls() if not isinstance(inst, BaseMiddleware): raise TorngasError( "middleware '%s' must inherit from the BaseMiddleware" % str(midd_class)) except Exception: raise if hasattr(inst, 'process_init'): self.init_middleware.append(inst) if hasattr(inst, 'process_request'): self.request_middleware.append(inst) if hasattr(inst, 'process_response'): self.response_middleware.append(inst) if hasattr(inst, 'process_call'): self.call_middleware.append(inst) if hasattr(inst, 'process_endcall'): self.endcall_middleware.append(inst) self.response_middleware.reverse() self.endcall_middleware.reverse()
def load(self): if hasattr(settings_module.settings, 'MIDDLEWARE_CLASSES') and len( settings_module.settings.MIDDLEWARE_CLASSES) > 0: for mclass in settings_module.settings.MIDDLEWARE_CLASSES: try: cls = import_object(mclass) except ImportError, ex: logger.getlogger.error( 'middleware error. module __import__ failed,msg:', ex) try: inst = cls() except Exception, ex: logger.getlogger.error( 'middleware error. cant instantiate cls(),msg:', ex) if hasattr(inst, 'process_init'): self.init_middleware.append(inst) if hasattr(inst, 'process_request'): self.request_middleware.append(inst) if hasattr(inst, 'process_response'): self.response_middleware.append(inst) if hasattr(inst, 'process_call'): self.call_middleware.append(inst) if hasattr(inst, 'process_endcall'): self.endcall_middleware.append(inst)
async def deserialize(self, value): value = await super().deserialize(value) try: return import_object(value) except ImportError: self.fail('import')
def __init__(self): handlers = [ (r'/', import_object('handler.HelloHandler')), ] settings = dict(template_path=os.path.join(os.path.dirname(__file__), "templates"), ) tornado.web.Application.__init__(self, handlers, **settings)
def msgHandle(self, pushMsg, configSection): """处理文本信息 @param pushMsg: 回复消息对象 @param configSection: 消息配置项 """ sm_logger.debug("pushMsg:%s" % pushMsg.__dict__) sm_logger.debug("configSection:%s" % configSection) replyMsg = None if pushMsg and configSection: replyMsg = ReplyMsg() replyMsg.toUsername = pushMsg.fromUsername replyMsg.fromUsername = pushMsg.toUsername replyMsg.createTime = str(int(time.time())) replyMsg.msgType = REPLY_MSG_TYPE['news'] try: articlesHandler = configSection['articles'] articlesHandler = import_object(articlesHandler) articlesHandler = articlesHandler() replyMsg.articles = articlesHandler.queryArticles( pushMsg, configSection) except Exception, e: sm_logger.debug("Exception:%s" % e) replyMsg = None
def load(self): if hasattr(settings_module.settings, 'MIDDLEWARE_CLASSES') and len( settings_module.settings.MIDDLEWARE_CLASSES) > 0: for mclass in settings_module.settings.MIDDLEWARE_CLASSES: try: cls = import_object(mclass) except ImportError, ex: logger.getlogger.error('middleware error. module __import__ failed,msg:', ex) try: inst = cls() except Exception, ex: logger.getlogger.error('middleware error. cant instantiate cls(),msg:', ex) if hasattr(inst, 'process_init'): self.init_middleware.append(inst) if hasattr(inst, 'process_request'): self.request_middleware.append(inst) if hasattr(inst, 'process_response'): self.response_middleware.append(inst) if hasattr(inst, 'process_call'): self.call_middleware.append(inst) if hasattr(inst, 'process_endcall'): self.endcall_middleware.append(inst)
def include(pattern, handlers, prefix_name=None): try: if prefix_name: new_name = '%s-%s' % (prefix_name, '%s') else: new_name = '%s' warnings.warn( "you should give a 'prefix_name' for include urls,to avoid naming conflicts" ) if handlers and isinstance(handlers, str): handlers = import_object(handlers) else: handlers = handlers urlspecs = [] if not pattern.endswith('/'): pattern += '/' if handlers and isinstance(handlers, (tuple, list)): for handler in handlers: if handler and isinstance(handler, urlspec): patt = pattern + handler.repr_pattern \ .lstrip('^').lstrip('//').lstrip('/') urlspecs.append( urlspec( patt, handler.handler_class, kwargs=handler.kwargs, name=new_name % handler.name if handler.name else handler.name)) return urlspecs else: raise UrlError('url error,it is must be an tuple or list') except Exception: raise
def load_application(self, application=None): if self.settings.TRANSLATIONS: try: from tornado import locale locale.load_translations(self.settings.TRANSLATIONS_CONF.translations_dir) except: warnings.warn('locale dir load failure,maybe your config file is not set correctly.') if not application: if not self.urls: raise BaseError("urls not found.") from torngas.application import Application self.application = Application(handlers=self.urls, default_host='', transforms=None, wsgi=False, **self.settings.TORNADO_CONF) else: self.application = application tmpl = self.settings.TEMPLATE_CONFIG.template_engine self.application.tmpl = import_object(tmpl) if tmpl else None return self
def wrapper(self, *args, **kwargs): #print self._locale.code form_name = name if name.find('.') == 0 : module_name = self.__class__.__module__ if len(module_name.split('.')) == 4 : arr = module_name.split('.') arr.pop() module_name = '.'.join(arr) form_name = module_name + '.forms' + name translate = None if hasattr(self,'_'): translate = self._ # 加载表单 self.form = import_object(form_name)( translate = translate , handler = self ) # 封装 form.validate def get_form_data(): form = self.form args = self.request.arguments if form.validate(args): return form.values() return False self.get_form_data = get_form_data return method(self, *args, **kwargs)
def include(pattern, handlers, prefix_name=None): """ 当你有多组url分布在不同的文件,或者你有多组url前缀不同,include可以帮你组织路由 eg: url1.py: url=Url('handler_abc') URLS = route( url(r'/add/','add.AddHandler'), ... ) url2.py: url=Url() URLS = route( url(r'/list/','handler_efg.list.ListHandler'), ..., include('/admin','url1.URLS') ) 最终的url可能类似于这样: url = [ r'/list/','handler_efg.list.ListHandler', ..., r'/admin/add/' , 'handler_abc.add.AddHandler', ... ] app = Application(url) """ try: if prefix_name: new_name = '%s-%s' % (prefix_name, '%s') else: new_name = '%s' if handlers and isinstance(handlers, str): handlers = import_object(handlers) else: handlers = handlers urlspecs = [] if not pattern.endswith('/'): pattern += '/' if handlers and isinstance(handlers, (tuple, list)): for handler in handlers: if handler and isinstance(handler, urlspec): patt = pattern + handler.repr_pattern \ .lstrip('^').lstrip('//').lstrip('/') urlsp = urlspec( patt, handler.handler_class, kwargs=handler.kwargs, name=new_name % handler.name if handler.name else handler.name) urlsp.repr_pattern = patt urlspecs.append(urlsp) return urlspecs else: raise UrlError('url error,it is must be an tuple or list') except Exception: raise
def execute(self): if type(self.action) == str: obj = import_object(self.action)() if hasattr(obj, "execute"): obj.execute() elif isfunction(self.action): self.action()
def create_editform(self): obj = import_object(self.entity_full_name)() metas = obj.cols_meta() col_defs = list() for meta in metas: if meta["name"] == "id": continue col_def = dict() col_def["name"] = meta["name"] col_def["type"] = "" col_def["required"] = "" if meta["length"] > 0: col_def["length"] = 'maxlength="%s"' % meta["length"] else: col_def["length"] = "" if not meta["nullable"]: col_def["required"] = "required" if meta["type"] == "int": col_def["type"] = "digits" elif meta["type"] == "numeric": col_def["type"] = "number" elif meta["type"] == "date": col_def["type"] = "date" col_defs.append(col_def) return col_defs
def wrapper(self, *args, **kwargs): form_name = name if name.find('.') == 0: module_name = self.__class__.__module__ if len(module_name.split('.')) == 4: arr = module_name.split('.') arr.pop() module_name = '.'.join(arr) form_name = module_name + '.forms' + name translate = None if hasattr(self, 'get_user_locale'): translate = self.get_user_locale() # 加载表单 self.form = import_object(form_name)(translate=translate) # 封装 form.validate def get_form_data(): form = self.form args = self.request.arguments if form.validate(args): return form.values() return False self.get_form_data = get_form_data return method(self, *args, **kwargs)
def delete(self, id_): self.set_header("Content-Type", "text/json;charset=utf-8") meta = DataTableModule.__entity_mapping__.get(id_) if not meta: self.set_status(403, "Error!") entity = import_object(meta["name"]) custom_filter = ObjectPool.datatable_provider.get(meta["name"]) custom_filter_obj = None if custom_filter: custom_filter_obj = custom_filter() valid_msg = "" message = dict() message["flag"] = "delete" rec_id = self.get_argument("id") sf = SessionFactory.new() cur_row = sf.query(entity).get(rec_id) if hasattr(custom_filter_obj, "before_delete"): valid_msg = custom_filter_obj.before_delete(cur_row, sf, self) if not valid_msg: sf.delete(cur_row) sf.commit() if hasattr(custom_filter_obj, "after_delete"): custom_filter_obj.after_delete(cur_row, sf, self) message["success"] = True message["msg"] = "Deleted" self.write(Utils.encode(message)) else: message["success"] = False message["msg"] = valid_msg self.write(Utils.encode(message))
def load_application(self, application=None): """ :type application: torngas.application.Application subclass or instance :return: """ self._patch_httpserver() if settings.TRANSLATIONS: try: from tornado import locale locale.load_translations(settings.TRANSLATIONS_CONF.translations_dir) except: warnings.warn('locale dir load failure,maybe your config file is not set correctly.') if not application: self._install_application(application) elif isinstance(application, Application): self.application = application elif issubclass(application, Application): self._install_application(application) else: raise ArgumentError('need torngas.application.Application instance object or subclass.') tmpl = settings.TEMPLATE_CONFIG.template_engine self.application.tmpl = import_object(tmpl) if tmpl else None return self.application
def load_application(self, default_host='', transforms=None, wsgi=False): #加载app,进行初始化配置,如无ap参数,则使用内置app初始化 logger_module.logger.load_config() tornado.options.parse_command_line() #tornado把默认的根logger加了handler #把根logger的handler去除,然后重新绑定在tornado的logger下 logging.getLogger().handlers = [] enable_pretty_logging(None, logging.getLogger('tornado')) #加载本地化配置 if self.settings.TRANSLATIONS: try: tornado.locale.load_translations(self.settings.TRANSLATIONS_CONF.translations_dir) except: warnings.warn('locale dir load failure,maybe your config file is not set correctly.') #初始化app if not self.application: self.application = application_module.AppApplication(handlers=self.urls, default_host=default_host, transforms=transforms, wsgi=wsgi, **self.settings.get_settings('TORNADO_CONF')) self.application.project_path = self.proj_path if self.proj_path.endswith('/') else self.proj_path + '/' self.application.tmpl = import_object(self.settings.TEMPLATE_ENGINE) if self.settings.TEMPLATE_ENGINE else None return self.application
def load_application(self, application=None): if settings.TRANSLATIONS: try: from tornado import locale locale.load_translations( settings.TRANSLATIONS_CONF.translations_dir) except: warnings.warn( 'locale dir load failure,maybe your config file is not set correctly.' ) if not application: if not self.urls: raise BaseError("urls not found.") from torngas.application import Application tornado_conf = settings.TORNADO_CONF tornado_conf['debug'] = settings.DEBUG self.application = Application( handlers=self.urls, default_host='', transforms=None, wsgi=False, middlewares=settings.MIDDLEWARE_CLASSES, **tornado_conf) else: self.application = application tmpl = settings.TEMPLATE_CONFIG.template_engine self.application.tmpl = import_object(tmpl) if tmpl else None return self.application
def settings_object(cls): if not hasattr(cls, '_sett'): cls._sett = global_settings try: sett_obj = import_object(options.settings) cls._sett.__dict__.update(sett_obj.__dict__) except Exception: if os.environ.get(SETTINGS_MODULE_ENVIRON, None): try: sett_obj = import_object(os.environ[SETTINGS_MODULE_ENVIRON] or None) cls._sett.__dict__.update(sett_obj.__dict__) except: warnings.warn('settings import error.') return cls._sett
def uninstall(plugin_name, callback=None): register = import_object(str(plugin_name).strip() + '.register') name = register._handler.__module__ + \ '.' + register._handler.__name__ plugin_configs = yield gen.Task(_application.cache.get, _cache_key, []) for plugin_data in plugin_configs: if plugin_data.get('name') == name: plugin_configs.remove(plugin_data) yield gen.Task(_application.cache.set, _cache_key, plugin_configs) # 通知 application 同步 if _application: yield gen.Task(_application.sync_ping) if callback: callback(True) return if callback: callback(False) return
def include(pattern, handlers, prefix_name=None): try: if prefix_name: new_name = '%s-%s' % (prefix_name, '%s') else: new_name = '%s' warnings.warn("you should give a 'prefix_name' for include urls,to avoid naming conflicts") if handlers and isinstance(handlers, str): handlers = import_object(handlers) else: handlers = handlers urlspecs = [] if not pattern.endswith('/'): pattern += '/' if handlers and isinstance(handlers, (tuple, list)): for handler in handlers: if handler and isinstance(handler, urlspec): patt = pattern + handler.repr_pattern \ .lstrip('^').lstrip('//').lstrip('/') urlspecs.append(urlspec(patt, handler.handler_class, kwargs=handler.kwargs, name=new_name % handler.name if handler.name else handler.name)) return urlspecs else: raise UrlError('url error,it is must be an tuple or list') except Exception: raise
def load(self): if hasattr(settings_module.settings, 'MIDDLEWARE_CLASSES') and len( settings_module.settings.MIDDLEWARE_CLASSES) > 0: for mclass in settings_module.settings.MIDDLEWARE_CLASSES: try: cls = import_object(mclass) except ImportError, ex: raise try: inst = cls() except Exception, ex: raise if hasattr(inst, 'process_init'): self.init_middleware.append(inst) if hasattr(inst, 'process_request'): self.request_middleware.append(inst) if hasattr(inst, 'process_response'): self.response_middleware.append(inst) if hasattr(inst, 'process_call'): self.call_middleware.append(inst) if hasattr(inst, 'process_endcall'): self.endcall_middleware.append(inst)
def run(self): if not hasattr(self, 'loop'): palette = STYLES additional_opts = { 'screen': urwid.raw_display.Screen(), 'unhandled_input': self.header_hotkeys, 'handle_mouse': False } if self.common['opts'].run_on_serial: palette = STYLES_MONO else: additional_opts['screen'].set_terminal_properties(colors=256) additional_opts['screen'].reset_default_terminal_palette() evl = urwid.TornadoEventLoop(IOLoop()) self.common['loop'] = urwid.MainLoop(self.common['ui'], palette, event_loop=evl, **additional_opts) log.debug("Running event loop: {}".format( self.common['loop'].event_loop)) try: self.set_alarm_in(0.05, self.next_screen) for k in self.common['controllers']: log.debug("Importing controller: {}".format(k)) klass = import_object( ("%s.controllers.{}Controller" % self.project).format(k)) self.common['controllers'][k] = klass(self.common) log.debug("*** %s", self.common['controllers']) self._connect_base_signals() self.common['loop'].run() except: log.exception("Exception in controller.run():") raise
def configure(impl, **kwargs): """Configures the AsyncHTTPClient subclass to use. AsyncHTTPClient() actually creates an instance of a subclass. This method may be called with either a class object or the fully-qualified name of such a class (or None to use the default, SimpleAsyncHTTPClient) If additional keyword arguments are given, they will be passed to the constructor of each subclass instance created. The keyword argument max_clients determines the maximum number of simultaneous fetch() operations that can execute in parallel on each IOLoop. Additional arguments may be supported depending on the implementation class in use. Example:: AsyncHTTPClient.configure("tornado.curl_httpclient.CurlAsyncHTTPClient") """ if isinstance(impl, (unicode, bytes_type)): impl = import_object(impl) if impl is not None and not issubclass(impl, AsyncHTTPClient): raise ValueError("Invalid AsyncHTTPClient implementation") AsyncHTTPClient._impl_class = impl AsyncHTTPClient._impl_kwargs = kwargs
def load_interceptor(self): self.interceptor_intercept = [] for interceptor_path in settings.INTERCEPTOR_CLASSES: ic_class = import_object(interceptor_path) ic = ic_class() if hasattr(ic, 'intercept'): self.interceptor_intercept.append(ic.intercept)
def load_application(self, application=None): #加载app,进行初始化配置,如无ap参数,则使用内置app初始化 #加载本地化配置 if self.settings.TRANSLATIONS: try: from tornado import locale locale.load_translations(self.settings.TRANSLATIONS_CONF.translations_dir) except: warnings.warn('locale dir load failure,maybe your config file is not set correctly.') if not application: if not self.urls: raise TorngasError("urls not found.") self.application = application_module.Application(handlers=self.urls, default_host='', transforms=None, wsgi=False, **self.settings.TORNADO_CONF) else: if isinstance(application, tornado.web.Application): self.application = application else: self.application = application(handlers=self.urls, default_host='', transforms=None, wsgi=False, **self.settings.TORNADO_CONF) self.application.project_path = self.proj_path \ if self.proj_path.endswith('/') else self.proj_path + '/' tmpl = self.settings.TEMPLATE_CONFIG.template_engine self.application.tmpl = import_object(tmpl) if tmpl else None return self
def urlhelper(self, *urllist): """ 路由列表list """ urls = [] for u in urllist: handler_path = '.'.join([self.path_prefix, u.get('handler_path')]) pattern = u.get('pattern') if pattern.endswith('/'): pattern += '?' else: pattern += '/?' path = u.get('path', None) if path: if path != '/': pattern = path + pattern else: pattern = self.path + pattern kw = dict(u.get('kwargs', {})) kw['app_name'] = self.app_name url_name = self.app_name + '-' + u.get('name') urls.append( urlspec(pattern, import_object(handler_path), kwargs=kw, name=url_name)) return urls
def register(self, name): if isinstance(name, ( str, unicode, )): name = import_object(name) #此处是将MIDDLEWARE_CLASSES中的类进行实例化 name = name() if hasattr(name, 'process_init'): _INIT_LIST.append(name) if hasattr(name, 'process_call'): _CALL_LIST.insert(0, name) if hasattr(name, 'process_request'): _REQUEST_LIST.insert(0, name) if hasattr(name, 'process_render'): _RENDER_LIST.append(name) if hasattr(name, 'process_response'): _RESPONSE_LIST.append(name) if hasattr(name, 'process_endcall'): _ENDCALL_LIST.append(name) if hasattr(name, 'process_exception'): _EXCEPTION_LIST.insert(0, name)
def load(self): middlewares = self.settings.get('middleware_classes', []) if middlewares: for mclass in middlewares: try: cls = import_object(mclass) except ImportError, ex: logging.error( 'middleware error. module __import__ failed,msg:', ex) try: inst = cls() except Exception, ex: logging.error( 'middleware error. cant instantiate cls(),msg:', ex) if hasattr(inst, 'process_init'): self.init_middleware.append(inst) if hasattr(inst, 'process_request'): self.request_middleware.append(inst) if hasattr(inst, 'process_response'): self.response_middleware.append(inst) if hasattr(inst, 'process_call'): self.call_middleware.append(inst) if hasattr(inst, 'process_endcall'): self.endcall_middleware.append(inst)