def add(self, value, entry=IndexEntry, **kwargs): ''' Shortcut factory method to add an IndexEntry to an index. ''' if entry == IndexEntry: if self.entry_base != _DEFAULT_ENTRY_PATH: entry = import_string(self.entry_base) else: ## validate base for k in self.entry_kind: found = False try: m = import_string(k) assert m == entry except AssertionError: continue except ImportError: continue else: found = True break if not found: raise ValueError("Must pass in the EntryBase or a compatible EntryKind for this Index upon add.") return entry.new(self, value, **kwargs)
def test_import_string(self): self.assertEqual(webapp2.import_string('webob.exc'), webob.exc) self.assertEqual(webapp2.import_string('webob'), webob) self.assertEqual(webapp2.import_string('asdfg', silent=True), None) self.assertEqual(webapp2.import_string('webob.asdfg', silent=True), None) self.assertRaises(webapp2.ImportStringError, webapp2.import_string, 'asdfg') self.assertRaises(webapp2.ImportStringError, webapp2.import_string, 'webob.asdfg')
def test_import_string(self): self.assertEqual(webapp2.import_string('webob.exc'), webob.exc) self.assertEqual(webapp2.import_string('webob'), webob) self.assertEqual(webapp2.import_string('dfasfasdfdsfsd', silent=True), None) self.assertEqual(webapp2.import_string('webob.dfasfasdfdsfsd', silent=True), None) self.assertRaises(ImportError, webapp2.import_string, 'dfasfasdfdsfsd') self.assertRaises(AttributeError, webapp2.import_string, 'webob.dfasfasdfdsfsd')
def test_import_string(self): self.assertEqual(webapp2.import_string('webob.exc'), webob.exc) self.assertEqual(webapp2.import_string('webob'), webob) self.assertEqual(webapp2.import_string('dfasfasdfdsfsd', silent=True), None) self.assertEqual( webapp2.import_string('webob.dfasfasdfdsfsd', silent=True), None) self.assertRaises(ImportError, webapp2.import_string, 'dfasfasdfdsfsd') self.assertRaises(AttributeError, webapp2.import_string, 'webob.dfasfasdfdsfsd')
def test_import_string(self): self.assertEqual(webapp2.import_string("webob.exc"), webob.exc) self.assertEqual(webapp2.import_string("webob"), webob) self.assertEqual(webapp2.import_string("asdfg", silent=True), None) self.assertEqual(webapp2.import_string("webob.asdfg", silent=True), None) self.assertRaises(webapp2.ImportStringError, webapp2.import_string, "asdfg") self.assertRaises(webapp2.ImportStringError, webapp2.import_string, "webob.asdfg")
def oauth_config(self): try: oauth_config = webapp2.import_string("oauth_config.{0}".format(self.request.host.replace(":", "_"))) except webapp2.ImportStringError: try: oauth_config = webapp2.import_string("oauth_config.{0}".format(self.request.host.split(":", 1)[0])) except webapp2.ImportStringError as e: logging.warning(e) try: from oauth_config import default as oauth_config except ImportError: return return oauth_config
def list( self, class_name ): # 文字列からモデルクラス、エンティティ取得 classPath_str = "models."+ class_name.capitalize() klass = webapp2.import_string( classPath_str ) # entities = klass.query( klass.is_deleted==False ).order( -klass.created_at ) entities = klass.query() entities_json = [] for entity in entities: entities_json.append( entity.toDict() ) # プロパティ情報を dict に入れる props = [] for prop in klass.__dict__["_properties"]: props.append({ "name": prop, "className": getattr(klass,prop).__class__.__name__, }) # logging.info( props ) res = jinja2.get_jinja2().render_template( 'admin/list.html', **{ "entities": entities, "entities_json": json.encode( entities_json ), "props": props, "class_name": class_name, }) self.response.out.write( res )
def show(self, class_name): id = self.request.get("id", None) if id is None: out = { "meta": functions.createMetaData( status="fail", code=400, method_name="showObjects", message="parameter missing" ) } self.response.out.write(json.encode(out)) return # 文字列からモデルクラス取得 classPath_str = "models." + functions.convertFromSnakeCaseToCamelCase(class_name) klass = webapp2.import_string(classPath_str) obj = klass.get_by_id(int(id)) if obj and obj.is_deleted == False: out = { "meta": functions.createMetaData(status="ok", code=200, method_name="showObjects"), "response": {"objects": [obj.toDict(full=True)]}, } else: out = { "meta": functions.createMetaData( status="fail", code=400, method_name="showObjects", message="object not found" ) } self.response.out.write(json.encode(out))
def __getitem__(self, module): """Returns the configuration for a module. If it is not already set, loads a ``default_config`` variable from the given module and updates the configuration with those default values Every module that allows some kind of configuration sets a ``default_config`` global variable that is loaded by this function, cached and used in case the requested configuration was not defined by the user. :param module: The module name. :returns: A configuration value. """ if module not in self.loaded: # Load default configuration and update config. values = webapp2.import_string(module + '.default_config', silent=True) if values: self.setdefault(module, values) self.loaded.append(module) try: return dict.__getitem__(self, module) except KeyError: raise KeyError('Module %r is not configured.' % module)
def readConfig(config=_config): ''' Parses extra config files and combines into one global config. ''' global _compiled_config from webapp2 import import_string if _compiled_config is not None: return _compiled_config else: if config['apptools.system'].get( 'include', False) is not False and len( config['apptools.system']['include']) > 0: systemLog('Considering system config includes...') for name, configpath in config['apptools.system']['include']: systemLog('Checking include "' + str(name) + '" at path "' + str(configpath) + '".') try: for key, cfg in import_string( '.'.join(configpath.split('.') + ['config'])).items(): config[key] = cfg except Exception, e: systemLog('Encountered exception of type "' + str(e.__class__) + '" when trying to parse config include "' + str(name) + '" at path "' + str(configpath)) if debug: raise else: continue if len(config) > 0 and _compiled_config is None: _compiled_config = config return config
def __init__(self, *args, **kwargs): super(BaseTestCase, self).__init__(*args, **kwargs) try: app = webapp2.import_string('main.app') except webapp2.ImportStringError: app = None self.app = app
def user_model(self): """Configured user model.""" cls = self.config['user_model'] if isinstance(cls, basestring): cls = self.config['user_model'] = webapp2.import_string(cls) return cls
def get_api(): import endpoints api_services = list() for api in config.API: module = webapp2.import_string(api) api_services.extend(module.api_services) return endpoints.api_server(api_services)
def user_model(self): """Configured user model.""" cls = self.config['user_model'] if isinstance(cls, six.string_types): cls = self.config['user_model'] = webapp2.import_string(cls) return cls
def create(self, class_name): logging.info(self.request.arguments()) if self.checkModel(class_name) == False: return if models.BlackList.checkBanned(): return # 文字列からモデルクラス、エンティティ取得 classPath_str = "models." + functions.convertFromSnakeCaseToCamelCase(class_name) klass = webapp2.import_string(classPath_str) # マスタデータかどうかチェック & マスターデータだったら管理者以外は作成できないように。 if klass.isMasterData == True and users.is_current_user_admin() == False: logging.warn("管理者以外がマスタデータを作成しようとしました") return False # 保存開始 entity = klass() self.setPropertyFromRequestData(entity, self.request) entity.put() # 出力 out = { "meta": functions.createMetaData(status="ok", code=200, method_name="createCustomObject"), "response": {"objects": [entity.toDict()]}, } self.response.out.write(json.encode(out))
def custom_dispatcher(router, request, response): route, args, kwargs = rv = router.match(request) request.route, request.route_args, request.route_kwargs = rv handler = route.handler if isinstance(handler, basestring): handler, args, kwargs = parse_handler_template(request, handler, args, kwargs) # debug logging # logging.info('handler is %s' % handler) # logging.info(request.route_args) # logging.info(request.route_kwargs) # for x in request.params: # logging.info('Param is %s' % x) # logging.info(args) # logging.info(kwargs) try: handler = webapp2.import_string(handler) # Module, Controller, Action 文字列格納 handler.adapted_handler_spec = kwargs # jinjaテンプレート定義 handler.JINJA_ENVIRONMENT = jinja2.Environment( loader=jinja2.FileSystemLoader( spy_setting.MODULES_DIR + "/" + kwargs["module"] + "/views/templates/" + kwargs["controller"] ), extensions=["jinja2.ext.autoescape"], ) router.handlers[handler] = handler except webapp2.ImportStringError: webapp2.abort(404) return router.adapt(handler)(request, response)
def user_model(self): """Configured user model.""" cls = self.config["user_model"] if isinstance(cls, str): cls = self.config["user_model"] = webapp2.import_string(cls) return cls
def custom_dispatcher(router, request, response): route, args, kwargs = rv = router.match(request) request.route, request.route_args, request.route_kwargs = rv handler = route.handler if isinstance(handler, basestring): handler, args, kwargs = parse_handler_template(request, handler, args, kwargs) # debug logging # logging.info('handler is %s' % handler) # logging.info(request.route_args) # logging.info(request.route_kwargs) # for x in request.params: # logging.info('Param is %s' % x) # logging.info(args) # logging.info(kwargs) try: handler = webapp2.import_string(handler) # Module, Controller, Action 文字列格納 handler.adapted_handler_spec = kwargs # jinjaテンプレート定義 handler.JINJA_ENVIRONMENT = jinja2.Environment( loader=jinja2.FileSystemLoader(spy_setting.MODULES_DIR + '/' + kwargs['module'] + '/views/templates/' + kwargs['controller']), extensions=['jinja2.ext.autoescape']) router.handlers[handler] = handler except webapp2.ImportStringError: webapp2.abort(404) return router.adapt(handler)(request, response)
def readConfig(config=_config): ''' Parses extra config files and combines into one global config. ''' global _compiled_config from webapp2 import import_string if _compiled_config is not None: return _compiled_config else: if config['apptools.system'].get('include', False) is not False and len(config['apptools.system']['include']) > 0: systemLog('Considering system config includes...') for name, configpath in config['apptools.system']['include']: systemLog('Checking include "' + str(name) + '" at path "' + str(configpath) + '".') try: for key, cfg in import_string('.'.join(configpath.split('.') + ['config'])).items(): config[key] = cfg except Exception, e: systemLog('Encountered exception of type "' + str(e.__class__) + '" when trying to parse config include "' + str(name) + '" at path "' + str(configpath)) if debug: raise else: continue if len(config) > 0 and _compiled_config is None: _compiled_config = config return config
def create( self ): target_model = self.request.get( 'target_model', None ); target_id = self.request.get( 'target_id', None ); # パラメータが足りなかったらエラー if target_model is None or target_id is None: message = "parameter missing" logging.warn( message ); out = {"meta": functions.createMetaData( status="fail", code=400, method_name="createReport", message=message )}; self.response.out.write( json.encode(out) ) return # 文字列からターゲットのモデルクラス取得 classPath_str = "models."+ target_model.capitalize() klass = webapp2.import_string( classPath_str ) target_obj = klass.get_by_id( int(target_id) ); # ターゲットオブジェクトがなければエラー if target_obj is None: message = "target object not found" logging.warn( message ); out = {"meta": functions.createMetaData( status="fail", code=400, method_name="createReport", message=message )}; self.response.out.write( json.encode(out) ) return # 保存 entity = models.Report() entity.target_key = target_obj.key entity.user_key = self.user.key if self.user else None entity.put(); # 出力 out = { "meta": functions.createMetaData( status="ok", code=200, method_name="createReport" ), "response": { "reports":[ entity.toDict(), ], }, }; self.response.out.write( json.encode(out) ) # 管理者にメール sender_address = "*****@*****.**" recipient = "*****@*****.**" subject = "通報を確認してください。" targetKey_str = str( target_obj.key.id() ) modelName = target_model.capitalize().encode() gql = "SELECT * FROM "+ modelName +" where __key__ = Key( '"+ modelName +"', "+ targetKey_str +" )" body = """ 通報がありました。 ターゲットのkeyは %(targetKey_str)s です 検索用 GQL は以下のとおりです。 %(gql)s """ % locals() mail.send_mail( sender_address, recipient, subject, body )
def load_inherited_models(app): """ Load correct modules to resolve polymodels Returns the modules loaded """ model_modules = [] for game_name, game in app.config['games'].iteritems(): model_modules.append(webapp2.import_string(game['model'])) return model_modules
def create( self ): target_model = self.request.get( 'target_model', None ); target_id = self.request.get( 'target_id', None ); # パラメータが足りなかったらエラー if target_model is None or target_id is None: message = "parameter missing" logging.warn( message ); out = {"meta": functions.createMetaData( status="fail", code=400, method_name="createLike", message=message )}; self.response.out.write( json.encode(out) ) return # ゲストならエラー if self.user is None: message = "login required" logging.warn( message ); out = {"meta": functions.createMetaData( status="fail", code=401, method_name="createLike", message=message )}; self.response.out.write( json.encode(out) ) return # 文字列からターゲットのモデルクラス取得 classPath_str = "models."+ target_model.capitalize() klass = webapp2.import_string( classPath_str ) target_obj = klass.get_by_id( int(target_id) ); # ターゲットオブジェクトがなければエラー if target_obj is None: message = "target object not found" logging.warn( message ); out = {"meta": functions.createMetaData( status="fail", code=400, method_name="createLike", message=message )}; self.response.out.write( json.encode(out) ) return # 重複チェック query = models.Like.query( models.Like.target_key==target_obj.key, models.Like.user_key==self.user.key, models.Like.is_deleted==False ) if query.get(): message = "already liked" logging.warn( message ); out = {"meta": functions.createMetaData( status="fail", code=400, method_name="createLike", message=message )}; self.response.out.write( json.encode(out) ) return # 保存 entity = models.Like() entity.target_key = target_obj.key entity.user_key = self.user.key entity.put(); # 出力 out = { "meta": functions.createMetaData( status="ok", code=200, method_name="createLike" ), "response": { "likes":[ entity.toDict(), ], }, }; self.response.out.write( json.encode(out) )
def import_class(input_cls): if not isinstance(input_cls, str): # It's a class - return as-is return input_cls try: input_cls = webapp2.import_string(input_cls) return input_cls except Exception, exc: # Couldn't import the class raise ValueError("Couldn't import the model class '%s': %s: %s" % (input_cls, Exception, exc))
def create( self ): target_model = self.request.get( 'target_model', None ); target_id = self.request.get( 'target_id', None ); content = self.request.get( 'content', None ); rating = self.request.get( 'rating', None ); # パラメータが足りなかったらエラー if content is None or target_model is None or target_id is None: message = "parameter missing" logging.error( message ) out = { "meta": functions.createMetaData( status="fail", code=400, method_name="createComment", message=message ), }; self.response.out.write( json.encode(out) ) return # 文字列からモデルクラス取得 classPath_str = "models."+ target_model.capitalize() klass = webapp2.import_string( classPath_str ) target_obj = klass.get_by_id( int(target_id) ); # ターゲットオブジェクトがなければエラー if target_obj is None: message = target_model +"#"+ target_id +" is not found" logging.error( message ) out = { "meta": functions.createMetaData( status="fail", code=400, method_name="createComment", message=message ), }; self.response.out.write( json.encode(out) ) return # 保存 comment = models.Comment() comment.content = content comment.rating = rating comment.target_key = target_obj.key if self.user: comment.user_key = self.user.key comment.put(); # 出力 out = { "meta": functions.createMetaData( status="ok", code=200, method_name="createComment" ), "response": { "comments":[ comment.toDict(), ], }, }; self.response.out.write( json.encode(out) )
def get_resource_code(resources): try: import fanstatic except ImportError: return "" needed = fanstatic.NeededResources(**tap.config.FANSTATIC) for resource in resources: if isinstance(resource, basestring): resource = webapp2.import_string(resource, silent=True) if resource is None: continue needed.need(resource) return needed.render_inclusions(needed.resources())
def set_timezone_selector(self, func): """Sets the function that defines the timezone for a request. :param func: A callable that receives (request, store) and returns the timezone for a request. """ if func is None: func = self._timezone_selector elif isinstance(func, basestring): func = webapp2.import_string(func) self.timezone_selector = func
def __call__(self, request, remote_path, remote_method): ''' Handle a remote service call. ''' global _middleware_cache self.request = request if request.method.lower() == 'options': return self.options() # Extract response request.clock = {} request.clock['threadstart'] = time.time() response = request.response # Manufacture service + handler service = self.service_factory() # Consider service middleware middleware = self._servicesConfig.get('middleware', False) if middleware is not False and len(middleware) > 0: for name, cfg in middleware: self.logging.debug('Considering ' + str(name) + ' middleware...') if cfg['enabled'] is True: try: if name not in _middleware_cache or ((not config) or config.debug): middleware_class = webapp2.import_string(cfg['path']) else: middleware_class = _middleware_cache[name] middleware_object = middleware_class(debug=cfg['debug'], config=self._servicesConfig, opts=cfg.get('args', {})) service.middleware[name] = middleware_object if hasattr(middleware_object, 'before_request'): service, request, response = middleware_object.before_request(service, request, response) continue else: self.logging.debug('Middleware ' + str(name) + ' does not have pre_request method. Continuing.') continue except Exception, e: self.logging.error('Middleware "' + str(name) + '" raise an unhandled exception of type "' + str(e) + '".') if (not config) or config.debug: raise else: continue else: self.logging.debug('Middleware ' + str(name) + ' is disabled.') continue
def get_app(): config_dict = config_to_dict(config) config_dict.update({ "webapp2_extras.jinja2": { "compiled_path": tuple([os.path.join(ROOT_DIR_PATH, path) for path in config.JINJA2_COMPILED_PATH]), "template_path": tuple([os.path.join(ROOT_DIR_PATH, path) for path in config.JINJA2_TEMPLATE_PATH]), "environment_args": {"extensions": ["jinja2.ext.i18n"]}, "force_compiled": config.JINJA2_FORCE_COMPILED, }, "webapp2_extras.sessions": { "cookie_name": "__s", "secret_key": config.SECRET_KEY, "session_max_age": config.SESSION_MAX_AGE, }, }) config_WEBAPP2_CONFIG = config_dict.pop("WEBAPP2_CONFIG") if config_WEBAPP2_CONFIG is not None: config_dict.update(config_WEBAPP2_CONFIG) routes_list = list() routes_list.extend(config.ROUTES) routes_list.extend(( webapp2.Route("/oauth/signout", handler="tap.ext.OAuth:_signout", name="oauth_signout"), webapp2.Route("/oauth/<provider>", handler="tap.ext.OAuth:_simple_auth", name="oauth_signin"), webapp2.Route("/oauth/<provider>/callback", handler="tap.ext.OAuth:_auth_callback", name="oauth_callback"), webapp2.Route("/_tap/i18n/<domain>.<language>.js", "tap.ext.I18Njs", name="I18Njs"), )) if config.BANG_REDIRECTOR: routes_list.append(webapp2.Route("/!<key:[^/]+>", "tap.ext.BangRedirector", name="bang-redirector")) for domain, values in config.APP.viewitems(): app_routes_by_domain = list() for value in values: prefix, app, namespace = (value + (None,))[:3] module = webapp2.import_string(app) if hasattr(module, "routes"): app_routes = module.routes else: logging.warning("{0} has not `routes`".format(module)) continue if namespace is not None: setattr(module, NAMESPACE_KEY, namespace) if prefix: app_routes = [routes.PathPrefixRoute(prefix, app_routes)] app_routes_by_domain.extend(app_routes) if domain: app_routes_by_domain = [routes.DomainRoute(domain, app_routes_by_domain)] routes_list.extend(app_routes_by_domain) if config.DRIVE_PROXY_UID is not None: routes_list.append(routes.DomainRoute(r"<domain:^.+?\.[a-zA-Z]{2,5}$>", [webapp2.Route(r"<path:.*>", "tap.ext.DriveProxy")])) elif config.DROPBOX_PROXY_UID is not None: routes_list.append(routes.DomainRoute(r"<domain:^.+?\.[a-zA-Z]{2,5}$>", [webapp2.Route(r"<path:.*>", "tap.ext.DropboxProxy")])) return webapp2.WSGIApplication(routes=routes_list, debug=config.DEBUG, config=config_dict)
def set_timezone_selector(self, func): """Sets the function that defines the timezone for a request. :param func: A callable that receives (store, request) and returns the timezone for a request. """ if func is None: self.timezone_selector = self.default_timezone_selector else: if isinstance(func, basestring): func = webapp2.import_string(func) self.timezone_selector = func.__get__(self, self.__class__)
def set_timezone_selector(self, func): """Sets the function that defines the timezone for a request. :param func: A callable that receives (store, request) and returns the timezone for a request. """ if func is None: self.timezone_selector = self.default_timezone_selector else: if isinstance(func, six.string_types): func = webapp2.import_string(func) self.timezone_selector = func.__get__(self, self.__class__)
def get_backend(self, name): """Returns a configured session backend, importing it if needed. :param name: The backend keyword. :returns: A :class:`BaseSessionFactory` subclass. """ backends = self.config['backends'] backend = backends[name] if isinstance(backend, basestring): backend = backends[name] = webapp2.import_string(backend) return backend
def get_backend(self, name): """Returns a configured session backend, importing it if needed. :param name: The backend keyword. :returns: A :class:`BaseSessionFactory` subclass. """ backends = self.config['backends'] backend = backends[name] if isinstance(backend, six.string_types): backend = backends[name] = webapp2.import_string(backend) return backend
def query(self, class_name): if self.checkModel(class_name) == False: return page = self.request.get("page", 1) per_page = self.request.get("per_page", 10) limit = self.request.get("limit", 100) skip = self.request.get("skip", 0) where = self.request.get("where") order = self.request.get("order") mine = self.request.get("mine", None) response_json_depth = self.request.get("response_json_depth", 3) # 出力ひな形作成 out = { "meta": functions.createMetaData(status="ok", code=200, method_name="queryCustomObjects"), "response": {"objects": []}, } # 文字列からモデルクラス取得 classPath_str = "models." + functions.convertFromSnakeCaseToCamelCase(class_name) klass = webapp2.import_string(classPath_str) gql_str = "" if where: gql_str = "WHERE " + where + " AND" else: gql_str = "WHERE" gql_str += " is_deleted=False" # モデルに is_public プロパティがあれば、それを暗黙で考慮する if hasattr(klass, "is_public") == True: gql_str += " AND is_public=True" # mine フラグがあったら自分の投稿したエントリーをフィルタ if (mine == "true") and (self.user is not None): gql_str += " AND user_key=" + self.user.key.id() if order: gql_str = gql_str + " ORDER BY " + order q = klass.gql(gql_str) results = q.fetch(int(limit)) klass.prefetchReferences(results) for result in results: out["response"]["objects"].append(result.toDict(full=False)) self.response.out.write(json.encode(out))
def set_locale_selector(self, func): """Sets the function that defines the locale for a request. :param func: A callable that receives (store, request) and returns the locale for a request. """ if func is None: self.locale_selector = self.default_locale_selector else: if isinstance(func, six.string_types): func = webapp2.import_string(func) # Functions are descriptors, so bind it to this instance with # __get__. self.locale_selector = func.__get__(self, self.__class__)
def set_locale_selector(self, func): """Sets the function that defines the locale for a request. :param func: A callable that receives (store, request) and returns the locale for a request. """ if func is None: self.locale_selector = self.default_locale_selector else: if isinstance(func, basestring): func = webapp2.import_string(func) # Functions are descriptors, so bind it to this instance with # __get__. self.locale_selector = func.__get__(self, self.__class__)
def __call__(self, request, remote_path, remote_method): ''' Handle a remote service call. ''' global _middleware_cache global_debug = config.debug ## Extract response response = request.response ## Manufacture service + handler service = self.service_factory() service._initializeRemoteService() ## Consider service middleware middleware = self.servicesConfig.get('middleware', False) if middleware is not False and len(middleware) > 0: for name, cfg in middleware: self.log('Considering '+str(name)+' middleware...') if cfg['enabled'] is True: try: if name not in _middleware_cache or config.debug: middleware_class = webapp2.import_string(cfg['path']) else: middleware_class = _middleware_cache[name] middleware_object = middleware_class(debug=cfg['debug'], config=self.servicesConfig, opts=cfg.get('args', {})) service.middleware[name] = middleware_object if hasattr(middleware_object, 'before_request'): service, request, response = middleware_object.before_request(service, request, response) continue else: self.log('Middleware '+str(name)+' does not have pre_request method. Continuing.') continue except Exception, e: self.error('Middleware "'+str(name)+'" raise an unhandled exception of type "'+str(e)+'".') if config.debug: raise else: continue else: self.log('Middleware '+str(name)+' is disabled.') continue
def query( self ): target_model = self.request.get( 'target_model', None ); target_id = self.request.get( 'target_id', None ); page = self.request.get( "page", 1 ); per_page = self.request.get( "per_page", 10 ); limit = self.request.get( "limit", 100 ); skip = self.request.get( "skip", 0 ); where = self.request.get( "where" ); order = self.request.get( "order" ); response_json_depth = self.request.get( "response_json_depth", 3 ); # 文字列からモデルクラス取得 classPath_str = "models."+ target_model.capitalize() klass = webapp2.import_string( classPath_str ) gql_str = "" if where: gql_str = "WHERE "+ where +" AND is_deleted=False" else: gql_str = "WHERE is_deleted=False" gql_str = gql_str +" AND target_key = key('%s',%d)" % ( target_model.capitalize(), int(target_id) ) if order: gql_str = gql_str +" ORDER BY "+ order q = models.Comment.gql( gql_str ) results = q.fetch( int(limit) ) klass.prefetchReferences( results ) # 出力ひな形作成 out = { "meta": functions.createMetaData( status="ok", code=200, method_name="queryComments" ), "response": { "comments":[], }, }; for result in results: out["response"]["comments"].append( result.toDict( full=False ) ) self.response.out.write( json.encode(out) )
def _normalize_services(mixed_services): if isinstance(mixed_services, dict): mixed_services = mixed_services.iteritems() services = [] for service_item in mixed_services: if isinstance(service_item, (list, tuple)): path, service = service_item else: path = None service = service_item if isinstance(service, basestring): # Lazily import the service class. service = webapp2.import_string(service) services.append((path, service)) return services
def get_rules(): """Returns a list of URL rules for the application. The list can be defined entirely here or in separate ``urls.py`` files. :param app: The WSGI application instance. :return: A list of class:`tipfy.Rule` instances. """ # Here we show an example of joining all rules from the # ``apps_installed`` definition set in config.py. rules = [] for app_module in config.get('webapp2')['apps_installed']: try: # Load the urls module from the app and extend our rules. app_rules = import_string('%s.routing' % app_module) rules.extend(app_rules.get_rules()) except ImportError: pass return rules
def get_rules(): ''' Get installed apps, get each one's rules. Also include URL mappings for builtin AppTools apps. ''' rules = [] for app_module in config.get('webapp2')['apps_installed'] + dispatch.get_builtin_apps(): if not isinstance(app_module, webapp2.WSGIApplication): try: # Load the urls module from the app and extend our rules. app_rules = import_string('%s.routing' % app_module) rules.extend(app_rules.get_rules()) except ImportError: continue else: try: # Load the urls from the app itself. app_rules = app_module.router.match_routes rules.extend(app_rules) except (AttributeError, TypeError): continue return rules
# marty mc fly imports from __future__ import absolute_import # stdlib imports import itertools # third-party imports import webapp2 # local imports from nacelle.conf import settings # use webapp2's import_string function to lazily import required modules for # WSGI config try: routes = webapp2.import_string(settings.ROUTES_MODULE) except webapp2.ImportStringError: routes = [] dispatcher = webapp2.import_string(settings.DISPATCHER_MODULE) error_handler_404 = webapp2.import_string(settings.ERROR_HANDLER_MODULE_404) error_handler_500 = webapp2.import_string(settings.ERROR_HANDLER_MODULE_500) secret_key_store = webapp2.import_string( 'nacelle.core.sessions.models.SecretKey') # some of nacelle's contrib apps have routes, so we need to make sure and # append those to our routes list before passing it into the WSGI app mail_routes = webapp2.import_string('nacelle.contrib.mail.routes.ROUTES') routes = list(itertools.chain(routes, mail_routes)) # Define our WSGI app so GAE can run it wsgi = webapp2.WSGIApplication(routes,
def __init__(self): try: self._user_settings = webapp2.import_string('settings') except webapp2.ImportStringError: self._user_settings = None self._default_settings = webapp2.import_string('nacelle.conf.default_settings')
def test_get_valid_setting(self): """Test getting a setting that exists """ settings = webapp2.import_string('nacelle.conf.settings') self.assertEqual(settings.TEST_SETTING, '12345')
def test_get_invalid_setting(self): """Test that getting a setting that doesn't exist throws an AttributeError """ settings = webapp2.import_string('nacelle.conf.settings') with self.assertRaises(AttributeError): settings.UNDEFINED_MADE_UP_SETTING
('/r_json_unencodable', r_json_unencodable), ] wsgi = webapp2.WSGIApplication(routes, debug=True, config={ 'webapp2_extras.sessions': { 'secret_key': 'xxxxxxxxxxxxxxxxxxxxxx' }, 'webapp2_extras.jinja2': { 'template_path': 'tests/templates' }, }) # attach dispatcher and error_handler to the WSGI app dispatcher = webapp2.import_string(settings.DISPATCHER_MODULE) wsgi.router.set_dispatcher(dispatcher) class RenderJinja2DecoratorTests(NacelleTestCase): def test_render_jinja2_existing_template(self): """Test rendering a template with Jinja2 """ response = wsgi.get_response('/r_jinja2') self.assertEqual(200, response.status_int) self.assertIn('<!DOCTYPE html>', response.body) def test_render_jinja2_override_response(self): """Test that a webapp2.Response is rendered when explicitly returned from a jinja2 handler """ response = wsgi.get_response('/r_jinja2_r')
lockdown_username = '******' lockdown_password = '******' def get(self): self.response.write('success') # Define our WSGI app so GAE can run it routes = [('/', locked_handler), ('/ld', LDTestHandler)] wsgi = webapp2.WSGIApplication(routes, debug=True, config={ 'webapp2_extras.sessions': {'secret_key': 'xxxxxxxxxxxxxxxxxxxxxx'} }) # attach dispatcher and error_handler to the WSGI app dispatcher = webapp2.import_string('nacelle.core.dispatcher.nacelle_dispatcher') wsgi.router.set_dispatcher(dispatcher) class LockdownDecoratorTests(NacelleTestCase): def test_properly_returns_401_when_no_headers(self): """@locked_down decorator returns a 401 when no auth headers present """ response = wsgi.get_response('/') self.assertEqual(401, response.status_int) self.assertIn('WWW-Authenticate', response.headers) self.assertIn('Could not verify your access level for that URL. ' 'You have to login with proper credentials', response.body) def test_properly_unlocks_when_valid_headers(self):