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

Python web.loadhook函数代码示例

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

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



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

示例1: test_processors

    def test_processors(self):
        urls = (
            "/(.*)", "blog"
        )
        class blog:
            def GET(self, path):
                return 'blog ' + path

        state = web.storage(x=0, y=0)
        def f():
            state.x += 1

        app_blog = web.application(urls, locals())
        app_blog.add_processor(web.loadhook(f))
        
        urls = (
            "/blog", app_blog,
            "/(.*)", "index"
        )
        class index:
            def GET(self, path):
                return "hello " + path
        app = web.application(urls, locals())
        def g():
            state.y += 1
        app.add_processor(web.loadhook(g))

        app.request('/blog/foo')
        assert state.x == 1 and state.y == 1, repr(state)
        app.request('/foo')
        assert state.x == 1 and state.y == 2, repr(state)
开发者ID:yejun,项目名称:webpy,代码行数:31,代码来源:application.py


示例2: run

	def run(self):
		"""
		启动网站
		"""
		# 初始化
		Common.init();
		
		# 创建web应用
		Logger.info('创建web应用')
		Common.app = web.application(Common.urls, globals())
		
		# 创建session
		Logger.info('创建session')
		Common.initSession(Common.app);
		Common.session.menu = MenuManagement();
		
		# 加载模板
		Logger.info('加载模板')
		Common.render = web.template.render('templates/', base='baseframe', globals={'context': Common.session})
		# 
		# 设置错误页面
		# Common.app.notfound = Common.notfound
		# Common.app.internalerror = Common.internalerror
		# 加载设置
		Logger.info('加载设置')
		# Common.app.add_processor(Common.error_precessor);
		Common.app.add_processor(web.loadhook(Common.session_hook));
		# Common.app.add_processor(web.loadhook(Common.session.menu.setSelectedMenu));
		Common.app.add_processor(web.loadhook(AuthorityManagement.checkAuthority))
		# Common.app.add_processor(web.unloadhook(AuthorityManagement.checkAuthority))
		
		Logger.debug('网站启动')
		Common.initFinish = True
		Common.app.run();
开发者ID:SealOfFire,项目名称:webpy_test,代码行数:34,代码来源:Common.py


示例3: __init__

    def __init__(self):

        #Initialize mappings manager and set main mappings
        self.mappings = mappings.Manager(self, API_URL, ADMIN_API_URL)
        #Initialize main web application here
        self.app = web.application(self.mappings.get_main_mappings(), fvars=globals())



        #All Mappings must be done before web application instance
        #Admin mappings
        self.mappings.add_map_resource('/server/admin/app', 'Admin', api_class_prefix=API_CLASS_PREFIX)
        #Api mappings
        self.mappings.add_map_resource('/server/api/admin_resources', 'ApiAdminResources', api_class_prefix=API_CLASS_PREFIX)
        self.mappings.add_map_resource('/server/api/private_resources', 'ApiPrivateResources', api_class_prefix=API_CLASS_PREFIX)
        self.mappings.add_map_resource('/server/api/public_resources', 'ApiPublicResources', api_class_prefix=API_CLASS_PREFIX)
        #Site mappings
        self.mappings.add_map_resource('/server/app', 'Site', api_class_prefix=API_CLASS_PREFIX)

        #Set new session with initializers
        db = dbs.DBS.dbStore('mysql')
        store = web.session.DBStore(db, 'sessions')
        #Start session
        self.session = web.session.Session(self.app, store,
            initializer={
                'userid': 'anonymous',
                'priv_lev':'',
                'authenticated':False,
                'language': quetzal_config['default_language']
            }
        )
        #Add login session & language hooks
        self.app.add_processor(web.loadhook(self.login_session_hook))
        self.app.add_processor(web.loadhook(self.language_session_hook))
开发者ID:ivanjzr,项目名称:QuetzalCMS,代码行数:34,代码来源:base.py


示例4: __init__

    def __init__(self, mapping, fvars):

        # Parent constructor
        web.application.__init__(self, mapping, fvars) #@UndefinedVariable

        # The views are bound once for all to the configuration
        config.views = web.template.render("app/views/", globals={
            "all_seasons": lambda: Season.all(),
            "all_polls": lambda: Poll.all(),
            "webparts": webparts,
            "formatting": formatting,
            "dates": dates,
            "zip": zip,
            "getattr": getattr,
            "hasattr": hasattr,
            "class_name": lambda x: x.__class__.__name__,
            "namedtuple": collections.namedtuple,
            "config": config,
            "result_statuses": Result.STATUSES,
            "Events": Events
        })

        # The ORM is bound once since it dynamically loads the engine from the configuration
        config.orm = meta.init_orm(lambda : config.engine)

        # Binds the hooking mechanism & the SQL Alchemy processor
        self.add_processor(web.loadhook(http.init_hooks))
        self.add_processor(web.unloadhook(http.execute_hooks))        
        self.add_processor(http.sqlalchemy_processor)

        # Binds the webparts initialization mechanism
        self.add_processor(web.loadhook(webparts.init_webparts))
开发者ID:franck260,项目名称:vpt,代码行数:32,代码来源:application.py


示例5: run_web_server

 def run_web_server(self):
     self.render = web.template.render('templates/')
     
     urls = (
         '/', 'Home',
         '/api/color', 'API_Color',
         '/api/brightness', 'API_Brightness'
     )
     self.app = web.application(urls, globals())
     self.app.add_processor(web.loadhook(self.load_plasma_trim))
     self.app.add_processor(web.loadhook(self.load_renderer))
     self.app.add_processor(web.loadhook(self.load_main_thread_queue))
     
     self.web_server_thread = Thread(None, self.app.run)
     self.web_server_thread.start()
开发者ID:grantjbutler,项目名称:Radiance,代码行数:15,代码来源:server.py


示例6: setUp

    def setUp(self):
        '''
        :return:
        '''
        settings.IS_UNITTEST = True
        settings.DEBUG = True
        ''' 配置测试用的redis配置信息  '''
        settings.REDIS_HOST = "localhost"
        # settings.REDIS_PORT = 8911
        # settings.REDIS_DB = 0

        ''' redisco连接 '''
        settings.rd = redisco.connection_setup(host=settings.REDIS_HOST, port=settings.REDIS_PORT, db=settings.REDIS_DB)

        # ''' 额外的redis连接 '''
        self.redis = redis.StrictRedis(host=settings.REDIS_HOST, port=settings.REDIS_PORT, db=settings.REDIS_DB)

        ''' 启动服务 '''
        web.config.debug = settings.DEBUG

        self.appM = web.application(URLS, HANDLER, autoreload=False)
        application = self.appM.wsgifunc()

        self.appM.notfound = notfound
        self.appM.internalerror = internalerror
        self.appM.add_processor(web.loadhook(header_html))

        session.init(web.session.Session(self.appM, web.session.DiskStore('sessions'), initializer=Initializer(
                                                                                                              User=models.user.User,
                                                                                                              UserGroup=models.usergroup.UserGroup,
                                                                                                              BanLogin=controllers.login_handler.BanLogin,
                                                                                                              settings=settings,
                                                                                                              session=session,
                                                                                                              ))
        )

        ''' 校验session, 添加到app的 processor 流程中,顺序需要在 session初始化之后 '''
        self.appM.add_processor(web.loadhook(verify_session))
        ''' 初始化 html 头, 添加到app的 processor 流程中 '''
        self.appM.add_processor(web.loadhook(header_html))

        web.config.session_parameters['cookie_name'] = 'webpy_session_id'
        web.config.session_parameters['cookie_domain'] = None
        web.config.session_parameters['timeout'] = 10
        web.config.session_parameters['ignore_expiry'] = True
        web.config.session_parameters['ignore_change_ip'] = False
        web.config.session_parameters['secret_key'] = 'akdnA0FJsdJFLSlvno92'
        web.config.session_parameters['expired_message'] = 'Session expired'
开发者ID:lamter,项目名称:WBFSystem,代码行数:48,代码来源:test_static.py


示例7: __new__

  def __new__(cls, *args, **kwargs):
    app = web.application(*args, **kwargs)

    app.add_processor(web.loadhook(cls._connect))
    app.add_processor(web.unloadhook(cls._disconnect))

    return app
开发者ID:AmitShah,项目名称:numenta-apps,代码行数:7,代码来源:__init__.py


示例8: init_app

def init_app():
    app = web.application(urls, globals())
    #app.notfound = api_notfound
    #app.internalerror = api_internalerror
    app.add_processor(web.loadhook(api_loadhook))
    app.add_processor(web.unloadhook(api_unloadhook))    
    return app
开发者ID:gaotianpu,项目名称:todolist,代码行数:7,代码来源:api.py


示例9: test_hook

 def test_hook(self):
     app.add_processor(web.loadhook(before))
     app.add_processor(web.unloadhook(after))
    
     self.assertEqual(app.request('/hello').data, 'yx')
     global str
     self.assertEqual(str, 'yxz')
开发者ID:492852238,项目名称:SourceLearning,代码行数:7,代码来源:myapplication.py


示例10: application

def application(urls, env):
  '''
  A pythonic web.py application

  def hello(ctx, name):
  	if not name:
  		name = 'World'
  	return 'Hello, ' + name + '!'

  urls = ('GET', '/(.*)', hello)
  app = application(urls, locals())
  '''
  def webpy_handler_class(method, pattern, handler):
    ''' convert functional view to class based view consumable by rest of webpy '''
    class _Handler:
      pass
    def wrap(_handler):
      def wrapped(self, *args, **kwargs):
        return _handler(web.ctx, *args, **kwargs)
      return wrapped
    _Handler.__dict__[method] = wrap(handler)
    env[handler.__name__] = _Handler
    return pattern, handler.__name__
  def compile_to_webpy(urls):
    ''' convert to webpy format '''
    return [component
            for method, pattern, handler in urls
            for component in webpy_handler_class(method, pattern, handler) ]
  app = web.application(compile_to_webpy(chunk_urls(urls)), env)
  app.add_processor(web.loadhook(hook_less(app)))
  return app
开发者ID:pavanmishra,项目名称:lesswebpy,代码行数:31,代码来源:lessweb.py


示例11: __init__

    def __init__(self, app):
        self.main_app = app
        self.session = web.session.Session(self.main_app, web.session.DiskStore('sessions'))

        def session_hook():
            web.ctx.session = self.session

        self.main_app.add_processor(web.loadhook(session_hook))
开发者ID:Jamongkad,项目名称:webpy-mvc,代码行数:8,代码来源:SprocketAuth.py


示例12: setup_rendering

 def setup_rendering():
     html = partial(web.template.render, '%s/templates/' % _path)
     slender = html(globals=env)
     render = html(base='base', globals=env)
     def render_hook():
         web.ctx.render = render
         web.ctx.slender = slender
     app.add_processor(web.loadhook(render_hook))
     env['render'] = slender
开发者ID:mekarpeles,项目名称:waltz,代码行数:9,代码来源:setup.py


示例13: main

def main():
    urls = [
            "/", TodosCollection,
            "/(.+)", TodoItem
            ]

    app = web.application(urls, globals())
    app.add_processor(web.loadhook(cors_headers))
    app.run()
开发者ID:vzelmanov,项目名称:todo-backend-py,代码行数:9,代码来源:todo-backend.py


示例14: start_wsgi

def start_wsgi():
    common.load_plugins()
    constants.init_urls()
    app = web.application(constants.urls, globals())
    check_database()
    create_session(app)
    for hook in constants.plugin_hooks_server_start:
        hook()
    app.add_processor(web.loadhook(localization_hook))
    return app.wsgifunc(httpserver.PluginStaticMiddleware)
开发者ID:riolet,项目名称:SAM,代码行数:10,代码来源:server_webserver.py


示例15: init_sessions

def init_sessions(web, app, store, session):
    """kwargs is used to inject options like 'cart' into session."""
    web.config.session_parameters['ignore_expiry'] = True
    session = web.session.Session(app, store, initializer=session)
    def inject_session():
        """closure; uncalled function which wraps session is
        passed to the web loadhook and invoked elsewhere and at a
        later point in time
        """
        web.ctx.session = session
    app.add_processor(web.loadhook(inject_session))
    return session
开发者ID:mekarpeles,项目名称:waltz,代码行数:12,代码来源:setup.py


示例16: run

 def run(self):
     '''
     \brief Start the web server.
     '''
     global session
     global sessionStore
     
     # log
     log.debug("starting server")
     
     # disable debug mode (which prevents sessions)
     web.config.debug = False
     
     # enable SSL, if required
     if self.keyFile and self.certFile:
         from web.wsgiserver import CherryPyWSGIServer
         CherryPyWSGIServer.ssl_private_key = self.keyFile
         CherryPyWSGIServer.ssl_certificate = self.certFile
         log.debug("enable SSL")
     
     # create main application
     self.webApp     = web.application(self.getMappingUrlToHandlerName(),
                                       self.getHandlerNameToHandlerClass())
     
     '''
     for i in range(0,len(self.getMappingUrlToHandlerName()),2):
         print '{0} -> {1}'.format(self.getMappingUrlToHandlerName()[i],self.getMappingUrlToHandlerName()[i+1])
     '''
     
     # customize error handling
     #self.webApp.notfound      = self._notfound
     #self.webApp.internalerror = self._internalerror
     
     # enable sessions
     web.config.session_parameters['cookie_name']      = 'dustLink_session_id'
     web.config.session_parameters['ignore_change_ip'] = False
     sessionStore = MemSessionStore.MemSessionStore()
     session = web.session.Session(self.webApp,
                                   sessionStore,
                                   initializer={'username': self.defaultUsername})
     self.webApp.add_processor(web.loadhook(self._session_hook))
     self.wsgifunc   = self.webApp.wsgifunc() 
     self.wsgifunc   = web.httpserver.StaticMiddleware(self.wsgifunc)
     self.webserver  = web.httpserver.WSGIServer(('0.0.0.0', 8080), self.wsgifunc) 
     
     # start server
     self.webserver.start()
     
     # you reach this line once the server has been stopped
     
     # log
     log.debug("server stopped")
开发者ID:086231600,项目名称:dustlink,代码行数:52,代码来源:DustWeb.py


示例17: createsession

def createsession():
	print 'createsession'
	db = myutil.db
	if db is None:
		print 'db error'

	sessiondb = web.session.DBStore(db, 'sessions')
	session = web.session.Session(app, sessiondb,
			initializer={"privilege": -1, 
				"authcode": pic.picChecker().getPicString()})
	def session_hook():
		web.ctx.session = session
	app.add_processor(web.loadhook(session_hook))
开发者ID:blueskyz,项目名称:miniBlog,代码行数:13,代码来源:myweb.py


示例18: add_sessions_to_app

def add_sessions_to_app(app):
    import os

    db = web.database(dbn='sqlite', db=os.path.join(site['db'], 'session.db'))
    store = web.session.DBStore(db, 'session')
    session = web.session.Session(app, store, initializer={
        'loggedin': False,
        'username': ''})

    def session_hook():
        web.ctx.session = session

    app.add_processor(web.loadhook(session_hook))
开发者ID:csdms,项目名称:wmt,代码行数:13,代码来源:session.py


示例19: create_application

def create_application():
    '''Initializes web.py application'''
    app = Application(urls, globals())
    # Session initialization
    if web.config.get('_session') is None:
        # this is required to work with reloader
        web.config._session = web.session.Session(
            app,
            DBUserStore(db, 'sessions'),
            dict(forms={}),
        )
    app.add_processor(web.loadhook(load_hook))
    return app
开发者ID:w0rm,项目名称:pre-stonegarden-dev,代码行数:13,代码来源:base.py


示例20: app_factory

def app_factory():
    """App factory."""
    import weblib.db
    from app.urls import URLS
    from app.weblib.app_processors import load_logger
    from app.weblib.app_processors import load_path_url
    from app.weblib.app_processors import load_render
    from app.weblib.app_processors import load_session
    from app.weblib.app_processors import load_and_manage_orm

    views = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'views')
    app = web.application(URLS, globals())
    dbpath = web.config.DATABASE_URL.replace('sqlite:///', '')
    db = web.database(dbn='sqlite', db=dbpath)
    session = web.session.Session(app, web.session.DBStore(db, 'session'))

    app.add_processor(web.loadhook(load_logger))
    app.add_processor(web.loadhook(load_path_url))
    app.add_processor(web.loadhook(load_render(views)))
    app.add_processor(web.loadhook(load_session(session)))
    app.add_processor(load_and_manage_orm(weblib.db.create_session()))

    return app
开发者ID:comick,项目名称:barduino,代码行数:23,代码来源:__init__.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Python web.lstrips函数代码示例发布时间:2022-05-26
下一篇:
Python web.listget函数代码示例发布时间: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