• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python webapp2.import_string函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中webapp2.import_string函数的典型用法代码示例。如果您正苦于以下问题:Python import_string函数的具体用法?Python import_string怎么用?Python import_string使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了import_string函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: add

    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)
开发者ID:openfire,项目名称:openfire_old,代码行数:26,代码来源:index.py


示例2: test_import_string

    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')
开发者ID:karlwmacmillan,项目名称:webapp2,代码行数:9,代码来源:misc_test.py


示例3: test_import_string

    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')
开发者ID:aswadrangnekar,项目名称:webapp-improved,代码行数:9,代码来源:misc_test.py


示例4: oauth_config

 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
开发者ID:MiCHiLU,项目名称:gae-tap,代码行数:13,代码来源:ext.py


示例5: custom_dispatcher

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)
开发者ID:potch8228,项目名称:spyhopReader,代码行数:32,代码来源:router.py


示例6: get_api

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)
开发者ID:MiCHiLU,项目名称:gae-tap,代码行数:7,代码来源:__init__.py


示例7: create

    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))
开发者ID:noughts,项目名称:openfish,代码行数:28,代码来源:objects.py


示例8: show

    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))
开发者ID:noughts,项目名称:openfish,代码行数:29,代码来源:objects.py


示例9: __getitem__

    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)
开发者ID:404minds,项目名称:quiz-forest,代码行数:28,代码来源:config.py


示例10: list

	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 )
开发者ID:noughts,项目名称:openfish,代码行数:30,代码来源:admin.py


示例11: readConfig

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
开发者ID:bsd,项目名称:Harvest-D3-Experiments,代码行数:26,代码来源:__init__.py


示例12: __init__

 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
开发者ID:scyros,项目名称:stones-server,代码行数:7,代码来源:utils.py


示例13: user_model

    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
开发者ID:mambaru,项目名称:webapp2example,代码行数:7,代码来源:auth.py


示例14: create

	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 = "[email protected]"
		recipient = "[email protected]"
		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 )
开发者ID:noughts,项目名称:openfish,代码行数:59,代码来源:reports.py


示例15: load_inherited_models

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
开发者ID:COMP3001,项目名称:Mulitplayr,代码行数:8,代码来源:handlers.py


示例16: create

	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) )
开发者ID:noughts,项目名称:openfish,代码行数:58,代码来源:likes.py


示例17: create

	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) )
开发者ID:noughts,项目名称:openfish,代码行数:52,代码来源:comments.py


示例18: get_resource_code

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())
开发者ID:MiCHiLU,项目名称:gae-tap,代码行数:13,代码来源:ext.py


示例19: set_timezone_selector

    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
开发者ID:mark0978,项目名称:webapp-improved,代码行数:13,代码来源:i18n.py


示例20: get_app

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)
开发者ID:MiCHiLU,项目名称:gae-tap,代码行数:51,代码来源:__init__.py



注:本文中的webapp2.import_string函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python webapp2.redirect函数代码示例发布时间:2022-05-26
下一篇:
Python webapp2.get_request函数代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap