def serve_http(transport, host=None, port=None, inet=None, client_timeout=None): # TODO: if we supported inet to pass requests in and respond to them, # then it would be easier to test the full stack, but it probably # means routing around paste.httpserver.serve which probably # isn't testing the full stack from paste.httpexceptions import HTTPExceptionHandler from paste.httpserver import serve _ensure_loggerhead_path() from loggerhead.apps.http_head import HeadMiddleware from loggerhead.apps.transport import BranchesFromTransportRoot from loggerhead.config import LoggerheadConfig from loggerhead.main import setup_logging if host is None: host = DEFAULT_HOST if port is None: port = DEFAULT_PORT argv = ['--host', host, '--port', str(port), '--', transport.base] if not transport.is_readonly(): argv.insert(0, '--allow-writes') config = LoggerheadConfig(argv) setup_logging(config, init_logging=False, log_file=sys.stderr) app = BranchesFromTransportRoot(transport.base, config) # Bug #758618, HeadMiddleware seems to break HTTPExceptionHandler from # actually sending appropriate return codes to the client. Since nobody # desperately needs HeadMiddleware right now, just ignoring it. # app = HeadMiddleware(app) app = HTTPExceptionHandler(app) serve(app, host=host, port=port)
def factory(global_conf, **app_conf): """create a sample redirector""" assert 'app.directory' in app_conf directory = app_conf['app.directory'] assert os.path.isdir(directory) keystr = 'redirector.' args = dict([(key.split(keystr, 1)[-1], value) for key, value in app_conf.items() if key.startswith(keystr) ]) app = StaticURLParser(directory) redirector = Redirector(app, **args) return HTTPExceptionHandler(redirector)
def load(self): self._load_bzr_plugins() with open(os.path.join(config.root, config.codebrowse.secret_path)) as secret_file: secret = secret_file.read() app = RootApp(SESSION_VAR) app = HTTPExceptionHandler(app) app = SessionHandler(app, SESSION_VAR, secret) app = log_request_start_and_stop(app) app = PrefixMiddleware(app) app = oops_middleware(app) return app
def setUp(self): TestCase.setUp(self) self.intercepted = [] self.session = None self.root = app = SimpleLogInRootApp(SESSION_VAR) app = session_scribbler(app, self) app = HTTPExceptionHandler(app) app = SessionHandler(app, SESSION_VAR, SECRET) self.cookie_name = app.cookie_handler.cookie_name self.intercept(config.codehosting.codebrowse_root, app) self.intercept(config.codehosting.secure_codebrowse_root, app) self.intercept(allvhosts.configs['mainsite'].rooturl, dummy_destination) install_opener() self.browser = wsgi_intercept.zope_testbrowser.WSGI_Browser() # We want to pretend we are not a robot, or else mechanize will honor # robots.txt. self.browser.mech_browser.set_handle_robots(False) self.browser.open(config.codehosting.secure_codebrowse_root + '+login')
def make_app(global_conf, **app_conf): """create the traclegos view and wrap it in middleware""" key_str = 'traclegos.' # constructor arguments list_items = [ 'conf', 'site_templates', 'available_templates', 'available_repositories', 'available_databases' ] args = dict([(key.split(key_str, 1)[-1], value) for key, value in app_conf.items() if key.startswith(key_str)]) for item in list_items: if args.has_key(item): args[item] = str2list(args[item]) # variables args['variables'] = dict([(key.split(key_str, 1)[-1], value) for key, value in global_conf.items() if key.startswith(key_str)]) app = View(**args) return HTTPExceptionHandler(app)
def factory(global_conf, editor=None, viewer=None, **app_conf): """create a webob view and wrap it in middleware""" key_str = 'svenweb.' args = dict([(key.split(key_str, 1)[-1], value) for key, value in app_conf.items() if key.startswith(key_str)]) templates_dir = args['templates_dir'] template_loader = TempitaLoader(templates_dir) del args['templates_dir'] editor = editor or BaseEditor editor = editor(template_loader) viewer = viewer or BaseReader viewer = viewer() app = SvnWikiView(template_loader=template_loader, editor=editor, viewer=viewer, **args) return HTTPExceptionHandler(app)
def __init__(self, application, dir, warning_level=None): HTTPExceptionHandler.__init__(self, application, warning_level) self.dir = dir
def setUpLoggerhead(self, **kw): branch_app = BranchWSGIApp(self.tree.branch, '', **kw).app return TestApp(HTTPExceptionHandler(branch_app))
app.create_all() connection = app.engine.connect() session = app.session_maker(bind=connection) try: environ = {} environ['sqlalchemy.session'] = session environ['sqlalchemy.model'] = app.model users = authkit.users.sqlalchemy_04_driver.UsersFromDatabase(environ) users.group_create("pylons") users.role_create("admin") users.user_create("james", password="******", group="pylons") users.user_create("ben", password="******") users.user_add_role("ben", role="admin") session.flush() session.commit() finally: session.close() connection.close() app = HTTPExceptionHandler(app) if __name__ == '__main__': import logging logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(levelname)-8s %(message)s', datefmt='%a, %d %b %Y %H:%M:%S', filename='test.log', filemode='w') from paste.httpserver import serve serve(app, host='0.0.0.0', port=8080)
def make_app_for_config_and_path(config, base): if config.get_option('trunk_dir') and not config.get_option('user_dirs'): print "--trunk-dir is only valid with --user-dirs" sys.exit(1) if config.get_option('reload'): if Reloader.is_installed(): Reloader.install() else: return Reloader.restart_with_reloader() if config.get_option('user_dirs'): if not config.get_option('trunk_dir'): print "You didn't specify a directory for the trunk directories." sys.exit(1) app = UserBranchesFromTransportRoot(base, config) else: app = BranchesFromTransportRoot(base, config) setup_logging(config) if config.get_option('profile'): from loggerhead.middleware.profile import LSProfMiddleware app = LSProfMiddleware(app) if config.get_option('memory_profile'): from dozer import Dozer app = Dozer(app) if not config.get_option('user_prefix'): prefix = '/' else: prefix = config.get_option('user_prefix') if not prefix.startswith('/'): prefix = '/' + prefix try: from paste.deploy.config import PrefixMiddleware except ImportError: cant_proxy_correctly_message = ( 'Unsupported configuration: PasteDeploy not available, but ' 'loggerhead appears to be behind a proxy.') def check_not_proxied(app): def wrapped(environ, start_response): if 'HTTP_X_FORWARDED_SERVER' in environ: exc = HTTPInternalServerError() exc.explanation = cant_proxy_correctly_message raise exc return app(environ, start_response) return wrapped app = check_not_proxied(app) else: app = PrefixMiddleware(app, prefix=prefix) app = HTTPExceptionHandler(app) app = ErrorHandlerApp(app) app = TransLogger(app, logger=logging.getLogger('loggerhead')) return app
def middleware(app, app_conf=None, global_conf=None, prefix='authkit.', handle_httpexception=True, middleware=None, **options): """ This function sets up the AuthKit authenticate middleware and its use and options are described in detail in the AuthKit manual. The function takes the following arguments and returns a WSGI application wrapped in the appropriate AuthKit authentication middleware based on the options specified: ``app`` The WSGI application the authenticate middleware should wrap ``app_conf`` A paste deploy ``app_conf`` dictionary to be used to setup the middleware ``global_conf`` A paste deploy ``global_conf`` dictionary ``prefix`` The prefix which all authkit related options in the config file will have prefixed to their names. This defaults to ``authkit.`` and shouldn't normally need overriding. ``middleware`` A make_middleware function which should be called directly instead of loading and calling a function based on the method name. If this is set then ``authkit.setup.methof`` should not be set. ``**options`` Any AuthKit options which are setup directly in Python code. If specified, these options will override any options specifed in a config file. All option names specified in the config file will have their prefix removed and any ``.`` characters replaced by ``_`` before the options specified by ``options`` are merged in. This means that the the option ``authkit.cookie.name`` specified in a config file sets the same options as ``cookie_name`` specified directly as an option. """ if handle_httpexception: app = HTTPExceptionHandler(app) # Configure the config files if global_conf is None: global_conf = {} if app_conf is None: app_conf = {} if not isinstance(app_conf, dict): raise AuthKitConfigError( "Expected app_conf to be paste deploy app_conf dictionary " "from not %r" % app_conf) # Merge config file and options available_methods = get_methods() all_conf = load_config(options, app_conf, prefix) if middleware is not None and all_conf.has_key('setup.method'): raise AuthKitConfigError('You cannot specify a middleware function ' 'and an authkit.setup.method') if not middleware and not all_conf.has_key('setup.method'): raise AuthKitConfigError('No authkit.setup.method was specified') # Check to see if middleware is disabled if asbool(all_conf.get('setup.enable', True)) == False: warnings.warn("AuthKit middleware has been turned off by the config " "option authkit.setup.enable") return app # Status Checking/Changing Middleware intercept = [str(x).strip() for x in \ all_conf.get('setup.intercept','401').split(',')] if not '401' in intercept: warnings.warn( "AuthKit is configured via the authkit.setup.intercept option not " "to intercept 401 responses so the authentication middleware will " "not be triggered even if a 401 Unauthenticated response is " "returned.") if middleware: prefix_ = prefix app = middleware( app, auth_conf=all_conf, app_conf=app_conf, global_conf=global_conf, prefix=prefix_, ) else: methods = [ method.strip() for method in all_conf['setup.method'].split(',') ] log.debug("Trying to load the following methods: %r", methods) for method in methods: if method in ['setup', 'config']: raise AuthKitConfigError( "The name %s is reserved cannot be used " "as a method name" % method) if not available_methods.has_key(method): raise AuthKitConfigError( 'The authkit method %r is not available. The available methods ' 'are %s and %s' % ( all_conf['setup.method'], ', '.join(available_methods.keys()[:-1]), available_methods.keys()[-1], )) prefix_ = prefix + method + '.' auth_conf = strip_base(all_conf, method + '.') app = available_methods[method].load()( app, auth_conf=auth_conf, app_conf=app_conf, global_conf=global_conf, prefix=prefix_, ) app = AddDictToEnviron( app, { 'authkit.config': strip_base(all_conf, 'config.'), 'authkit.intercept': intercept, 'authkit.authenticate': True, }) return app