def router(conf, session_key, zcml, dsn, name): allowed = ('de',) register_allowed_languages(allowed) config.ALLOWED_LANGUAGES = None load_zcml(zcml) setSecurityPolicy(GenericSecurityPolicy) # We register our SQLengine under a given name engine = create_engine(dsn, name) # We use a declarative base, if it exists we bind it and create engine.bind(Base) metadata = Base.metadata metadata.create_all(engine.engine, checkfirst=True) # Router root = URLMap() admin_app = Admin(session_key, engine, name) root['/admin'] = localize(admin_app) root['/'] = localize(User(session_key, engine, name)) root.__runner__ = admin_app.__runner__ return root
def __init__(self, settings): URLMap.__init__(self) map = {} if settings.MEDIA_URL.startswith('/'): for app_name in settings.INSTALLED_APPS: if app_name == 'django.contrib.admin': continue mod = __import__(app_name, globals(), locals(), ['']) dirname = os.path.dirname(os.path.abspath(mod.__file__)) medias = glob.glob(os.path.join(dirname, 'media*', '*')) for media in medias: dummy, name = os.path.split(media) if not dirname.startswith('.'): map[settings.MEDIA_URL+name] = StaticURLParser(media) map[settings.MEDIA_URL] = StaticURLParser(settings.MEDIA_ROOT) # admin medias if hasattr(settings, "ADMIN_MEDIA_PREFIX"): if settings.ADMIN_MEDIA_PREFIX.startswith('/'): import django.contrib.admin dirname = os.path.dirname(os.path.abspath(django.contrib.admin.__file__)) map[settings.ADMIN_MEDIA_PREFIX] = StaticURLParser(os.path.join(dirname, 'media')) for k in sorted(map, reverse=True): v = map[k] print '%s -> %s' % (k, v.directory) self[k] = v
def get_app(opts, args, config, as_standalone = False, with_testuser = False): """ creates and sets up the app, *but does not run it through flask server unless told to* This intends to return a valid WSGI app to later be called by say gunicorn todo: I would like to use @pumazi approach of only importing _standalone server as needed returns a Flask app.wsgi_app, which can be passed into wsgi chain """ app = make_app(config) app.debug = True if as_standalone: if not os.path.isdir(opts.jslocation): raise IOError( "dir to serve static files (%s) does not exist" % opts.jslocation) ### Creating a mapping of URLS to file locations ### TODO: simplify this - proabbly need change atc and this ### may want to consider a config list of dirs, or grab ### list of dirs from FS (at jslocation) at startup time sloc = opts.jslocation stat = StaticURLParser(sloc) stat_config = StaticURLParser(os.path.join(sloc, "config")) stat_lib = StaticURLParser(os.path.join(sloc, "lib")) stat_bookish = StaticURLParser(os.path.join(sloc, "bookish")) stat_helpers = StaticURLParser(os.path.join(sloc, "helpers")) stat_node_modules = StaticURLParser(os.path.join(sloc, "node_modules")) ### give repo a simple response - /api/ will get rewritten ### todo: can I force URLMap not to adjust PATH info etc? mymaps = {"/": app.wsgi_app, "/js/": stat, "/js/config/": stat_config, "/js/lib/": stat_lib, "/js/bookish/": stat_bookish, "/js/helpers/": stat_helpers, "/js/node_modules/": stat_node_modules} urlmap = URLMap() urlmap.update(mymaps) # Need a fake user for testing, especially in the standalone case wrappedapp = urlmap else: wrappedapp = app.wsgi_app if with_testuser: wrappedapp = AddTestUser(wrappedapp) return wrappedapp
def main(argv=None): """Start up a CherryPy server to serve the SRU, OAI-PMH applications.""" global argparser, c3_session, c3_server global sru_app, oaipmh_app # WSGI Apps if argv is None: args = argparser.parse_args() else: args = argparser.parse_args(argv) c3_session = Session() c3_server = SimpleServer(c3_session, args.serverconfig) # Init SRU App sru_configs = get_configsFromServer(c3_session, c3_server) sru_app = SRUWsgiHandler(c3_session, sru_configs) # Init OAI-PMH App dbs, oaipmh_configs = get_databasesAndConfigs(c3_session, c3_server) oaipmh_app = OAIPMHWsgiApplication(c3_session, oaipmh_configs, dbs) # Mount various Apps and static directories urlmap = URLMap() urlmap['/docs'] = make_pkg_resources(None, 'cheshire3', 'docs/build/html') urlmap['/api/sru'] = sru_app urlmap['/api/oaipmh/2.0'] = oaipmh_app url = "http://{0}:{1}/".format(args.hostname, args.port) if args.browser: webbrowser.open(url) print("Hopefully a new browser window/tab should have opened " "displaying the application.") paste.httpserver.serve( urlmap, host=args.hostname, port=args.port, )
def build_url_map(app, global_conf, local_conf): from paste.urlmap import URLMap from galaxy.web.framework.middleware.static import CacheableStaticURLParser as Static urlmap = URLMap() # Merge the global and local configurations conf = global_conf.copy() conf.update(local_conf) # Get cache time in seconds cache_time = conf.get("static_cache_time", None) if cache_time is not None: cache_time = int(cache_time) # Send to dynamic app by default urlmap["/"] = app def get_static_from_config(option_name, default_path): config_val = conf.get(option_name, default_url_path(default_path)) per_host_config_option = f"{option_name}_by_host" per_host_config = conf.get(per_host_config_option) return Static(config_val, cache_time, directory_per_host=per_host_config) # Define static mappings from config urlmap["/static"] = get_static_from_config("static_dir", "static/") urlmap["/images"] = get_static_from_config("static_images_dir", "static/images") urlmap["/static/scripts"] = get_static_from_config("static_scripts_dir", "static/scripts/") urlmap["/static/welcome.html"] = get_static_from_config("static_welcome_html", "static/welcome.html") urlmap["/favicon.ico"] = get_static_from_config("static_favicon_dir", "static/favicon.ico") urlmap["/robots.txt"] = get_static_from_config("static_robots_txt", "static/robots.txt") if 'static_local_dir' in conf: urlmap["/static_local"] = Static(conf["static_local_dir"], cache_time) return urlmap, cache_time
def build_url_map(app, global_conf, local_conf): from paste.urlmap import URLMap from galaxy.web.framework.middleware.static import CacheableStaticURLParser as Static urlmap = URLMap() # Merge the global and local configurations conf = global_conf.copy() conf.update(local_conf) # Get cache time in seconds cache_time = conf.get("static_cache_time", None) if cache_time is not None: cache_time = int(cache_time) # Send to dynamic app by default urlmap["/"] = app # Define static mappings from config urlmap["/static"] = Static(conf.get("static_dir", "./static/"), cache_time) urlmap["/images"] = Static( conf.get("static_images_dir", "./static/images"), cache_time) urlmap["/static/scripts"] = Static( conf.get("static_scripts_dir", "./static/scripts/"), cache_time) urlmap["/static/style"] = Static( conf.get("static_style_dir", "./static/style/blue"), cache_time) urlmap["/favicon.ico"] = Static( conf.get("static_favicon_dir", "./static/favicon.ico"), cache_time) urlmap["/robots.txt"] = Static( conf.get("static_robots_txt", "./static/robots.txt"), cache_time) return urlmap, cache_time
def _init_listen_rules(self): self._wsgi_apps = {} static_path = os.path.join(os.path.split(os.path.abspath(__file__))[0], 'static') for rule in self._config.rules['Listen']: wsgi_app = URLMap() wsgi_app['/static'] = static.Cling(static_path) if 'ws' in rule.protocols: wsgi_app['/ws'] = eventlet.websocket.WebSocketWSGI(self._wsgi_websocket) if 'csp' in rule.protocols: wsgi_app['/csp'] = self._csp_sock self._wsgi_apps[(rule.interface, rule.port)] = wsgi_app
def make_app(global_conf, full_stack=True, static_files=True, **app_conf): """Create a Pylons WSGI application and return it ``global_conf`` The inherited configuration for this application. Normally from the [DEFAULT] section of the Paste ini file. ``full_stack`` Whether or not this application provides a full WSGI stack (by default, meaning it handles its own exceptions and errors). Disable full_stack when this application is "managed" by another WSGI middleware. ``app_conf`` The application's local configuration. Normally specified in the [app:<name>] section of the Paste ini file (where <name> defaults to main). """ # Configure the Pylons environment load_environment(global_conf, app_conf) # The Pylons WSGI app app = PylonsApp() app = RoutesMiddleware(app, config['routes.map']) app = SessionMiddleware(app, config) app = CacheMiddleware(app, config) # CUSTOM MIDDLEWARE HERE (filtered by error handling middlewares) if asbool(full_stack): # Handle Python exceptions app = ErrorHandler(app, global_conf, **config['pylons.errorware']) # Display error documents for 401, 403, 404 status codes (and # 500 when debug is disabled) if asbool(config['debug']): app = StatusCodeRedirect(app) else: app = StatusCodeRedirect(app, [401, 403, 404, 500]) # Establish the Registry for this application app = RegistryManager(app) # Static files if asbool(static_files): static_app = StaticURLParser(config['pylons.paths']['static_files']) media_app = StaticURLParser(config['app_conf']['media_dir']) thumb_app = StaticURLParser(config['app_conf']['thumb_dir']) urlmap = URLMap() urlmap['/media'] = media_app urlmap['/thumb'] = thumb_app app = Cascade([urlmap, static_app, app]) return app
def main(): urlmap = URLMap({}) urlmap['/hello'] = hello urlmap['/calc'] = calc urlmap['/address'] = address urlmap['/tunes'] = tunes urlmap['/sampler'] = sampler urlmap['/colorpicker'] = colorpicker urlmap['/codemirror'] = codemirror urlmap['/googlemaps'] = googlemaps run_wsgi_app(urlmap)
def main(): app = URLMap() app['/echo'] = handle static_path = os.path.join( os.path.split(os.path.abspath(__file__))[0], 'static') app['/'] = static.Cling(static_path) # run an example app from the command line listener = eventlet.listen(('localhost', 8013)) print "\nListening http://localhost:8013/ in your websocket-capable browser.\n" eventlet.spawn(listen_tcp) wsgi.server(listener, app)
def __init__(self, settings): URLMap.__init__(self) map = {} if settings.MEDIA_URL.startswith('/'): for app_name in settings.INSTALLED_APPS: if app_name == 'django.contrib.admin': continue mod = __import__(app_name, globals(), locals(), ['']) dirname = os.path.dirname(os.path.abspath(mod.__file__)) medias = glob.glob(os.path.join(dirname, 'media*', '*')) for media in medias: dummy, name = os.path.split(media) if not dirname.startswith('.'): map[settings.MEDIA_URL + name] = StaticURLParser(media) map[settings.MEDIA_URL] = StaticURLParser(settings.MEDIA_ROOT) # staticfiles has_statics = False if hasattr(settings, "STATIC_URL"): if settings.STATIC_URL.startswith('/'): try: map[settings.STATIC_URL] = StaticFiles(settings) except ImportError: pass else: has_statics = True # admin medias if not has_statics and hasattr(settings, "ADMIN_MEDIA_PREFIX"): if settings.ADMIN_MEDIA_PREFIX.startswith('/'): import django.contrib.admin dirname = os.path.dirname(os.path.abspath( django.contrib.admin.__file__)) map[settings.ADMIN_MEDIA_PREFIX] = StaticURLParser( os.path.join(dirname, 'media')) for k in sorted(map, reverse=True): v = map[k] self[k] = v
def test_middleware_app_non_profiler(self): temp_filename = get_temporary_filename() profiler_path = "/__profiler__" try: # Use a sample WSGI app map_app = URLMap() pm = linesman.middleware.ProfilingMiddleware( map_app, profiler_path=profiler_path) app = TestApp(pm) app.get("/not/profiled/url", status=404) finally: # Clean up after ourselves try: os.remove(temp_filename) except: pass
def main(): options, args = parser.parse_args() if options.clear: if os.path.exists(options.dir): print 'Deleting %s' % options.dir shutil.rmtree(options.dir) from cutout.sync import Application db_app = Application(dir=options.dir, include_syncclient=True) from webob.static import DirectoryApp from paste.urlmap import URLMap map = URLMap() map['/'] = DirectoryApp(os.path.join(here, 'cutout', 'tests', 'syncclient')) map['/db'] = TestAuthMiddleware(db_app) from paste.httpserver import serve serve(map, host=options.host, port=int(options.port))
def main(): options, args = parser.parse_args() if options.clear: if os.path.exists(options.dir): print 'Deleting %s' % options.dir shutil.rmtree(options.dir) mapper = URLMap() for arg in args: if '=' in arg: path, dir = arg.split('=', 1) else: path, dir = '/', arg mapper[path] = DirectoryApp(dir) from cutout.sync import Application db_app = Application(dir=options.dir, include_syncclient=True) mapper['/sync'] = db_app serve(mapper, host=options.host, port=int(options.port))
def wrap_in_static(app, global_conf, **local_conf): from paste.urlmap import URLMap from biobench.middleware.static import CacheableStaticURLParser as Static urlmap = URLMap() # Merge the global and local configurations conf = global_conf.copy() conf.update(local_conf) # Get cache time in seconds cache_time = conf.get("static_cache_time", None) if cache_time is not None: cache_time = int(cache_time) # Send to dynamic app by default urlmap["/"] = app # Define static mappings from config urlmap["/static"] = Static(conf.get("static_dir"), cache_time) urlmap["/staticpdb"] = Static(conf.get("pdb_dataset_link"), cache_time) urlmap["/staticjob"] = Static(conf.get("job_link"), cache_time) print conf.get("static_favicon_dir") #urlmap["/favicon.ico"] = Static( conf.get( "static_favicon_dir" ), cache_time ) return urlmap
def add_media_to_app(django_app): """ Return a WSGI application made up of the Django application, its media and the Django Admin media. """ app = URLMap() app['/'] = django_app # The Django App has been loaded, so it's now safe to access the settings: from django.conf import settings # Setting up the Admin media: admin_media = path.join(_DJANGO_ROOT, "contrib", "admin", "media") app[settings.ADMIN_MEDIA_PREFIX] = StaticURLParser(admin_media) # Setting up the media for the Django application: app[settings.MEDIA_URL] = StaticURLParser(settings.MEDIA_ROOT) return app
def wrap_in_static( app, global_conf, **local_conf ): from paste.urlmap import URLMap from galaxy.web.framework.middleware.static import CacheableStaticURLParser as Static urlmap = URLMap() # Merge the global and local configurations conf = global_conf.copy() conf.update(local_conf) # Get cache time in seconds cache_time = conf.get( "static_cache_time", None ) if cache_time is not None: cache_time = int( cache_time ) # Send to dynamic app by default urlmap["/"] = app # Define static mappings from config urlmap["/static"] = Static( conf.get( "static_dir" ), cache_time ) urlmap["/images"] = Static( conf.get( "static_images_dir" ), cache_time ) urlmap["/static/scripts"] = Static( conf.get( "static_scripts_dir" ), cache_time ) urlmap["/static/style"] = Static( conf.get( "static_style_dir" ), cache_time ) urlmap["/favicon.ico"] = Static( conf.get( "static_favicon_dir" ), cache_time ) # URL mapper becomes the root webapp return urlmap
def wrap_in_static(app, global_conf, plugin_frameworks=None, **local_conf): from paste.urlmap import URLMap from galaxy.web.framework.middleware.static import CacheableStaticURLParser as Static urlmap = URLMap() # Merge the global and local configurations conf = global_conf.copy() conf.update(local_conf) # Get cache time in seconds cache_time = conf.get("static_cache_time", None) if cache_time is not None: cache_time = int(cache_time) # Send to dynamic app by default urlmap["/"] = app # Define static mappings from config urlmap["/static"] = Static(conf.get("static_dir", "./static/"), cache_time) urlmap["/images"] = Static( conf.get("static_images_dir", "./static/images"), cache_time) urlmap["/static/scripts"] = Static( conf.get("static_scripts_dir", "./static/scripts/"), cache_time) urlmap["/static/style"] = Static( conf.get("static_style_dir", "./static/style/blue"), cache_time) urlmap["/favicon.ico"] = Static( conf.get("static_favicon_dir", "./static/favicon.ico"), cache_time) urlmap["/robots.txt"] = Static( conf.get("static_robots_txt", "./static/robots.txt"), cache_time) # wrap any static dirs for plugins plugin_frameworks = plugin_frameworks or [] for framework in plugin_frameworks: if framework and framework.serves_static: # invert control to each plugin for finding their own static dirs for plugin_url, plugin_static_path in framework.get_static_urls_and_paths( ): plugin_url = '/plugins/' + plugin_url urlmap[(plugin_url)] = Static(plugin_static_path, cache_time) log.debug('added url, path to static middleware: %s, %s', plugin_url, plugin_static_path) # URL mapper becomes the root webapp return urlmap
def setup(): # Monkeypatch webtest TestRequest to inject our custom TestResponse # for now, hopefully subclass approach (demonstrated above to no effect) # will be merged to WebTest trunk (from bitbucket.org/ejucovy/webtest) TestRequest.ResponseClass = HtmlTestResponse global raw_app, rule_filename, deliv_filename, deliv_url app = URLMap() app['/theme.html'] = make_response(get_text("theme.html")) app['/blog/index.html'] = make_response(get_text("blog_index.html")) app['/about.html'] = make_response(get_text("about.html")) app['/magic'] = make_response(get_text("magic.html"), headerlist=[ ('Content-Type', "text/html"), ('X-No-Deliverate', "1")]) app['/magic2'] = make_response(get_text("magic2.html")) app['/foo'] = make_response(get_text("foo.html")) app['/empty'] = make_response("") app['/html_entities.html'] = make_response(get_text("html_entities.html")) app['/xhtml_doctype.html'] = make_response(get_text("xhtml_doctype.html")) app['/no_xhtml_doctype.html'] = make_response(get_text("no_xhtml_doctype.html")) app['/scriptcomments'] = make_response(get_text("scriptcomments.html")) app['/xhtml_scriptcomments'] = make_response(get_text("xhtml_scriptcomments.html")) app['/cdata.html'] = make_response(get_text("cdata.html")) app['/newfooter.html'] = make_response(get_text("newfooter.html")) app['/newfooter_sneaky_cdata.html'] = make_response(get_text("newfooter_sneaky_cdata.html")) app['/reddot.html'] = make_response(get_text("reddot.html")) app['/reddot2.html'] = make_response(get_text("reddot2.html")) app['/ellipse.html'] = make_response(get_text("ellipse.html")) app['/collapse_theme.html'] = make_response(get_text("collapse_theme.html")) app['/collapse_content.html'] = make_response(get_text("collapse_content.html")) app['/redirect_test/theme.html'] = make_redirect("/theme.html") app['/redirect_test/dynamic_topnav/logged_in.html'] = make_response( get_text("logged_in_topnav.html")) app['/redirect_test/dynamic_topnav'] = make_redirect( "/redirect_test/dynamic_topnav/logged_in.html") app['/redirect_test/dynamic_topnav'] = make_redirect( "/redirect_test/dynamic_topnav/logged_in.html") app['/redirect_test'] = make_redirect("/redirect_test/welcome.html") app['/redirect_test/welcome.html'] = make_response(get_text("welcome.html")) rule_xml = get_text("rule.xml") # Rule files can be read directly from the filesystem: rule_filename_pos, rule_filename = tempfile.mkstemp() f = open(rule_filename, 'w+') f.write(rule_xml) f.close() # Rule files can also be published and fetched with an HTTP subrequest: def read_rule_file(environ, start_response): f = open(rule_filename) content = f.read() f.close() return Response(content, content_type="application/xml")(environ, start_response) app['/mytheme/rules.xml'] = read_rule_file # We'll set up one DeliveranceMiddleware using the published rules, # and another using the rule file: deliv_filename = DeliveranceMiddleware( app, FileRuleGetter(rule_filename), PrintingLogger, log_factory_kw=dict(print_level=logging.WARNING)) deliv_url = DeliveranceMiddleware( app, SubrequestRuleGetter('http://localhost/mytheme/rules.xml'), PrintingLogger, log_factory_kw=dict(print_level=logging.WARNING)) raw_app = HtmlTestApp(app) deliv_filename = HtmlTestApp(deliv_filename) deliv_url = HtmlTestApp(deliv_url)
for file in os.listdir(path): _file = file file = req.path_info.rstrip('/') + '/' + file data = {'url': file} filepath = os.path.join(path, _file) if os.path.isdir(filepath): _req = Request(req.environ.copy()) _req.path_info = file subfiles = scan(_req, filepath) data['children'] = subfiles files.append(data) return files def linker_app(environ, start_response): req = Request(environ) path = req.path_info path = path.split('/') path = [os.getcwd()] + path path = os.path.join(*path) assert os.path.exists(path) files = scan(req, path) return Response(json.dumps(files), )(environ, start_response) app = URLMap() app['/linker_backend'] = linker_app app['/'] = static_app serve(app, port='8080')
def __init__(self, *args, **kwargs): URLMap.__init__(self, *args, **kwargs) self['/__about__'] = HubDetails(self) self['/login'] = login_center(self) self['/logout'] = logout_app
from chiral.web.introspector import Introspector from chiral.web.comet import CometClock, CometLibServer from chiral.web.servers import StaticFileServer from chiral.web.framework import * print "Initializing..." @coroutine_page() @use_template("genshi", "chiral.web.templates.helloworld") def asyncpagetest(): yield raise StopIteration({ "foo": "Test Page" }) introspector = Introspector() application = URLMap() application.update({ "/pony": PonyMiddleware(HTTPNotFound()), "/introspector": Introspector(), "/static": StaticFileServer("/home/jacob/code/chiral/static"), "/asyncpagetest": asyncpagetest, "/cometlib": CometLibServer(), "/": CometClock() }) HTTPServer( bind_addr = ('', 8081), application = application ).start() ChiralShellServer(
address = ApplicationServlet(SimpleAddressBook) tunes = ApplicationServlet(MuntjacTunesLayout) sampler = ApplicationServlet( SamplerApplication, widgetset='com.vaadin.demo.sampler.gwt.SamplerWidgetSet') colorpicker = ApplicationServlet(ColorPickerApplication) codemirror = ApplicationServlet(CodeMirrorApplication) googlemaps = ApplicationServlet(GoogleMapWidgetApp) urlmap = URLMap({}) urlmap['/hello'] = hello urlmap['/calc'] = calc urlmap['/address'] = address urlmap['/tunes'] = tunes urlmap['/sampler'] = sampler urlmap['/colorpicker'] = colorpicker urlmap['/codemirror'] = codemirror urlmap['/googlemaps'] = googlemaps ws_app = DirectoryApp(join(dirname(muntjac.__file__), 'public', 'VAADIN')) urlmap['/VAADIN'] = ws_app def main(): logging.basicConfig(stream=sys.stdout, level=logging.DEBUG)
irc_conn = IRCBot( server=("irc.freenode.net", 6667), nick="j4bot", username="******", realname="jacob" ) @coroutine_page() def last_page(): yield print "returning: %s" % repr("\n".join(last_messages)) raise StopIteration("\n".join(last_messages)) application = URLMap() application.update({ "/pony": PonyMiddleware(HTTPNotFound()), "/introspector": Introspector(), "/irc": CometIRCReader(irc_conn), "/last": last_page, "/static": StaticFileServer("/home/jacob/code/chiral/irc-static") }) HTTPServer( bind_addr = ('', 8081), application = application ).start() print "Running..."
def make_app(global_conf, full_stack=True, static_files=True, **app_conf): """Create a Pylons WSGI application and return it ``global_conf`` The inherited configuration for this application. Normally from the [DEFAULT] section of the Paste ini file. ``full_stack`` Whether this application provides a full WSGI stack (by default, meaning it handles its own exceptions and errors). Disable full_stack when this application is "managed" by another WSGI middleware. ``static_files`` Whether this application serves its own static files; disable when another web server is responsible for serving them. ``app_conf`` The application's local configuration. Normally specified in the [app:<name>] section of the Paste ini file (where <name> defaults to main). """ # Configure the Pylons environment config = load_environment(global_conf, app_conf) alembic_migrations = MediaCoreMigrator.from_config(config, log=log) if alembic_migrations.is_db_scheme_current(): events.Environment.database_ready() else: log.warn( 'Running with an outdated database scheme. Please upgrade your database.' ) plugin_mgr = config['pylons.app_globals'].plugin_mgr # The Pylons WSGI app app = PylonsApp(config=config) # Allow the plugin manager to tweak our WSGI app app = plugin_mgr.wrap_pylons_app(app) # Routing/Session/Cache Middleware app = RoutesMiddleware(app, config['routes.map'], singleton=False) app = SessionMiddleware(app, config) # CUSTOM MIDDLEWARE HERE (filtered by error handling middlewares) # add repoze.who middleware with our own authorization library app = add_auth(app, config) # ToscaWidgets Middleware app = setup_tw_middleware(app, config) # Strip the name of the .fcgi script, if using one, from the SCRIPT_NAME app = FastCGIScriptStripperMiddleware(app) # If enabled, set up the proxy prefix for routing behind # fastcgi and mod_proxy based deployments. if config.get('proxy_prefix', None): app = setup_prefix_middleware(app, global_conf, config['proxy_prefix']) # END CUSTOM MIDDLEWARE if asbool(full_stack): # Handle Python exceptions app = ErrorHandler(app, global_conf, **config['pylons.errorware']) # by default Apache uses a global alias for "/error" in the httpd.conf # which means that users can not send error reports through MediaCore's # error page (because that POSTs to /error/report). # To make things worse Apache (at least up to 2.4) has no "unalias" # functionality. So we work around the issue by using the "/errors" # prefix (extra "s" at the end) error_path = '/errors/document' # Display error documents for 401, 403, 404 status codes (and # 500 when debug is disabled) if asbool(config['debug']): app = StatusCodeRedirect(app, path=error_path) else: app = StatusCodeRedirect(app, errors=(400, 401, 403, 404, 500), path=error_path) # Cleanup the DBSession only after errors are handled app = DBSessionRemoverMiddleware(app) # Establish the Registry for this application app = RegistryManager(app) app = setup_db_sanity_checks(app, config) if asbool(static_files): # Serve static files from our public directory public_app = StaticURLParser(config['pylons.paths']['static_files']) static_urlmap = URLMap() # Serve static files from all plugins for dir, path in plugin_mgr.public_paths().iteritems(): static_urlmap[dir] = StaticURLParser(path) # Serve static media and podcast images from outside our public directory for image_type in ('media', 'podcasts'): dir = '/images/' + image_type path = os.path.join(config['image_dir'], image_type) static_urlmap[dir] = StaticURLParser(path) # Serve appearance directory outside of public as well dir = '/appearance' path = os.path.join(config['app_conf']['cache_dir'], 'appearance') static_urlmap[dir] = StaticURLParser(path) # We want to serve goog closure code for debugging uncompiled js. if config['debug']: goog_path = os.path.join(config['pylons.paths']['root'], '..', 'closure-library', 'closure', 'goog') if os.path.exists(goog_path): static_urlmap['/scripts/goog'] = StaticURLParser(goog_path) app = Cascade([public_app, static_urlmap, app]) if asbool(config.get('enable_gzip', 'true')): app = setup_gzip_middleware(app, global_conf) app.config = config return app
def make_app(global_conf, full_stack=True, static_files=True, **app_conf): """Create a Pylons WSGI application and return it ``global_conf`` The inherited configuration for this application. Normally from the [DEFAULT] section of the Paste ini file. ``full_stack`` Whether this application provides a full WSGI stack (by default, meaning it handles its own exceptions and errors). Disable full_stack when this application is "managed" by another WSGI middleware. ``static_files`` Whether this application serves its own static files; disable when another web server is responsible for serving them. ``app_conf`` The application's local configuration. Normally specified in the [app:<name>] section of the Paste ini file (where <name> defaults to main). """ # Configure the Pylons environment config = load_environment(global_conf, app_conf) plugin_mgr = config['pylons.app_globals'].plugin_mgr # The Pylons WSGI app app = PylonsApp(config=config) # Allow the plugin manager to tweak our WSGI app app = plugin_mgr.wrap_pylons_app(app) # Routing/Session/Cache Middleware app = RoutesMiddleware(app, config['routes.map'], singleton=False) app = SessionMiddleware(app, config) # CUSTOM MIDDLEWARE HERE (filtered by error handling middlewares) # Set up repoze.what-quickstart authentication: # http://wiki.pylonshq.com/display/pylonscookbook/Authorization+with+repoze.what app = add_auth(app, config) # ToscaWidgets Middleware app = setup_tw_middleware(app, config) # Strip the name of the .fcgi script, if using one, from the SCRIPT_NAME app = FastCGIScriptStripperMiddleware(app) # If enabled, set up the proxy prefix for routing behind # fastcgi and mod_proxy based deployments. if config.get('proxy_prefix', None): app = setup_prefix_middleware(app, global_conf, config['proxy_prefix']) # END CUSTOM MIDDLEWARE if asbool(full_stack): # Handle Python exceptions app = ErrorHandler(app, global_conf, **config['pylons.errorware']) # Display error documents for 401, 403, 404 status codes (and # 500 when debug is disabled) if asbool(config['debug']): app = StatusCodeRedirect(app) else: app = StatusCodeRedirect(app, [400, 401, 403, 404, 500]) # Cleanup the DBSession only after errors are handled app = DBSessionRemoverMiddleware(app) # Establish the Registry for this application app = RegistryManager(app) if asbool(static_files): # Serve static files from our public directory public_app = StaticURLParser(config['pylons.paths']['static_files']) static_urlmap = URLMap() # Serve static files from all plugins for dir, path in plugin_mgr.public_paths().iteritems(): static_urlmap[dir] = StaticURLParser(path) # Serve static media and podcast images from outside our public directory for image_type in ('media', 'podcasts'): dir = '/images/' + image_type path = os.path.join(config['image_dir'], image_type) static_urlmap[dir] = StaticURLParser(path) # Serve appearance directory outside of public as well dir = '/appearance' path = os.path.join(config['app_conf']['cache_dir'], 'appearance') static_urlmap[dir] = StaticURLParser(path) # We want to serve goog closure code for debugging uncompiled js. if config['debug']: goog_path = os.path.join(config['pylons.paths']['root'], '..', 'closure-library', 'closure', 'goog') if os.path.exists(goog_path): static_urlmap['/scripts/goog'] = StaticURLParser(goog_path) app = Cascade([public_app, static_urlmap, app]) if asbool(config.get('enable_gzip', 'true')): app = setup_gzip_middleware(app, global_conf) app.config = config return app
default=8888, type='int', ) api.env.in_server = True api.env.startup_traceback = True (options, args) = api.bootstrap_with_global_options(parser, context='lite') api.env._merge( lite_port=options.port, lite_host=options.host, webui_prod=options.prod, lite_pem=api.env._join('dot_ipa', 'lite.pem'), ) api.finalize() urlmap = URLMap() apps = [ ('IPA', KRBCheater(api.Backend.wsgi_dispatch)), ('webUI', KRBCheater(WebUIApp())), ] for (name, app) in apps: urlmap[app.url] = app api.log.info('Mounting %s at %s', name, app.url) if path.isfile(api.env.lite_pem): pem = api.env.lite_pem else: api.log.info('To enable SSL, place PEM file at %r', api.env.lite_pem) pem = None httpserver.serve(
def get_info(environ, start_response): # command = dict(parse_querystring(environ)).get('command','') page = str(parse_querystring(environ)) # if command == 'clear': # if 'REMOTE_USER' in environ: # del environ['REMOTE_USER'] # if 'REMOTE_SESSION' in environ: # del environ['REMOTE_SESSION'] # else: # environ['REMOTE_SESSION'] = authfunc(environ, my_realm, environ['REMOTE_USER'] ) # if environ.get('REMOTE_USER'): # page = '<html><body>Welcome %s (%s)</body></html>' # page %= (environ['REMOTE_USER'], environ['REMOTE_SESSION']) # else: # page = ('<html><body><form><input name="user" />' # '<input type="submit" /></form></body></html>') return DataApp(page, content_type="text/plain")(environ, start_response) root_app = URLMap() root_app['/get_info'] = get_info serve(EvalException( cookie_m.AuthCookieHandler(AuthDigestHandler(root_app, my_realm, authfunc), secret="TEST2", timeout=60)), host='0.0.0.0', port=8041)