class StaticJavascripts(object): """Middleware for intercepting requests for WebHelpers' included javascript files. Triggered when PATH_INFO begins with '/javascripts/'. """ def __init__(self): self.javascripts_app = \ StaticURLParser(os.path.dirname(javascript_path)) def __call__(self, environ, start_response): if environ.get('PATH_INFO', '').startswith('/javascripts/'): log.debug("Handling Javascript URL (Starts with /javascripts/)") return self.javascripts_app(environ, start_response) else: return self.javascripts_app.not_found(environ, start_response)
def __init__(self, directory, cache_seconds=None): StaticURLParser.__init__(self, directory) self.cache_seconds = cache_seconds
def save_data(self, url, data): from cPickle import dump filename = self.url_filename(url) f = open(filename, 'wb') dump(data, f) f.close() def url_filename(self, url): # Double-quoting makes the filename safe import urllib return os.path.join(self.storage_dir, urllib.quote(url, '')) import re _end_body_re = re.compile(r'</body.*?>', re.I | re.S) def add_to_end(self, html, extra_html): match = self._end_body_re.search(html) if not match: return html + extra_html else: return html[:match.start()] + extra_html + html[match.start():] if __name__ == '__main__': from paste.urlparser import StaticURLParser from paste import httpserver app = StaticURLParser(sys.argv[1]) app = Commenter(app, sys.argv[2]) httpserver.serve(app, host='127.0.0.1', port=8080)
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) # The Pylons WSGI app app = PylonsApp() # Profiling Middleware if profile_load: if asbool(config['profile']): app = AccumulatingProfileMiddleware( app, log_filename='/var/log/linotp/profiling.log', cachegrind_filename='/var/log/linotp/cachegrind.out', discard_first_request=True, flush_at_shutdown=True, path='/__profile__') # Routing/Session/Cache Middleware 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, [400, 401, 403, 404, 500]) # Establish the Registry for this application app = RegistryManager(app) if asbool(static_files): # Serve static files static_app = StaticURLParser(config['pylons.paths']['static_files']) app = Cascade([static_app, app]) # repoze.who if repoze_load: if 'who.generate_random_secret' in app_conf and not app_conf[ 'who.generate_random_secret']: app = make_who_with_config(app, global_conf, app_conf['who.config_file'], app_conf['who.log_file'], app_conf['who.log_level']) else: # Read the current configuration file and replace "secret" keys in every line who_config_lines = [] secret = binascii.hexlify(os.urandom(16)) if len(secret) != 32: raise RuntimeError( 'Could not generate random repoze.who secret, no os.urandom support?' ) with open(app_conf['who.config_file']) as f: for line in f.readlines(): who_config_lines.append( re.sub(r'^(secret)\s*=\s*.*$', r'\1 = %s' % secret, line)) with tempinput(''.join(who_config_lines)) as who_config_file: app = make_who_with_config(app, global_conf, who_config_file, app_conf['who.log_file'], app_conf['who.log_level']) # this is a compatibility hack for pylons > 1.0!!! conf = PyConf(config) conf['global_conf'] = global_conf conf['app_conf'] = app_conf conf['__file__'] = global_conf['__file__'] conf['FILE'] = global_conf['__file__'] conf['routes.map'] = config['routes.map'] if not hasattr(conf, 'init_app'): setattr(conf, 'init_app', config.init_app) app.config = conf return app
def make_app(global_conf, full_stack=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(base_wsgi_app=RedditApp) # CUSTOM MIDDLEWARE HERE (filtered by the error handling middlewares) # last thing first from here down app = CleanupMiddleware(app) app = LimitUploadSize(app) app = ProfileGraphMiddleware(app) app = ProfilingMiddleware(app) app = SourceViewMiddleware(app) app = DomainListingMiddleware(app) app = SubredditMiddleware(app) app = ExtensionMiddleware(app) app = DomainMiddleware(app) if asbool(full_stack): # Handle Python exceptions app = ErrorHandler(app, global_conf, error_template=error_template, **config['pylons.errorware']) # Display error documents for 401, 403, 404 status codes (and 500 when # debug is disabled) app = ErrorDocuments(app, global_conf, mapper=error_mapper, **app_conf) # Establish the Registry for this application app = RegistryManager(app) # Static files javascripts_app = StaticJavascripts() static_app = StaticURLParser(config['pylons.paths']['static_files']) app = Cascade([static_app, javascripts_app, app]) #add the rewrite rules app = RewriteMiddleware(app) return app
# coding: utf-8 from paste.urlparser import StaticURLParser from paste.cascade import Cascade import webapp2 from home import Home, Index, Post, Transfer from login import Login, Logout web_app = webapp2.WSGIApplication([ ('/', Home), ('/index', Index), ('/post', Post), ('/transfer', Transfer), ('/login', Login), ('/login/logout', Logout), ]) # 在真实应用中,应该让 http server 直接响应静态请求 # 此处 demo 中用 WSGI 来响应仅仅是为了方便 static_app = StaticURLParser('static/') application = Cascade([static_app, web_app])
def make_app(global_conf, full_stack=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(base_wsgi_app=RedditApp) # CUSTOM MIDDLEWARE HERE (filtered by the error handling middlewares) app = LimitUploadSize(app) app = ProfilingMiddleware(app) app = SourceViewMiddleware(app) app = DomainListingMiddleware(app) app = SubredditMiddleware(app) app = ExtensionMiddleware(app) app = DomainMiddleware(app) log_path = global_conf.get('log_path') if log_path: process_iden = global_conf.get('scgi_port', 'default') app = RequestLogMiddleware(log_path, process_iden, app) #TODO: breaks on 404 #app = make_gzip_middleware(app, app_conf) if asbool(full_stack): # Handle Python exceptions app = ErrorHandler(app, global_conf, error_template=error_template, **config['pylons.errorware']) # Display error documents for 401, 403, 404 status codes (and 500 when # debug is disabled) app = ErrorDocuments(app, global_conf, mapper=error_mapper, **app_conf) # Establish the Registry for this application app = RegistryManager(app) # Static files javascripts_app = StaticJavascripts() # Set cache headers indicating the client should cache for 7 days static_app = StaticURLParser(config['pylons.paths']['static_files'], cache_max_age=604800) app = Cascade([static_app, javascripts_app, app]) app = AbsoluteRedirectMiddleware(app) #add the rewrite rules app = RewriteMiddleware(app) app = CleanupMiddleware(app) return app
class _ModelsController(_RESTController): """A RESTful Controller bound to more tha one model. The ``model`` and ``forms`` attribute can be a list of object or a module""" engine = None model = forms = None _static_app = StaticURLParser(os.path.join(os.path.dirname(__file__), 'resources')) def Session(self): return meta.Session def models(self, format='html', **kwargs): """Models index page""" models = self.get_models() return self.render(models=models, format=format) def static(self): """Serve static files from the formalchemy package""" return self._static_app(request.environ, self.start_response) def get_models(self): """return a dict containing all model names as key and url as value""" models = {} if isinstance(self.model, list): for model in self.model: key = model.__name__ models[key] = model_url(self.collection_name, model_name=key) else: for key, obj in self.model.__dict__.iteritems(): if not key.startswith('_'): if Document is not None: try: if issubclass(obj, Document): models[key] = model_url(self.collection_name, model_name=key) continue except: pass try: class_mapper(obj) except: continue if not isinstance(obj, type): continue models[key] = model_url(self.collection_name, model_name=key) return models def get_model(self): if isinstance(self.model, list): for model in self.model: if model.__name__ == self.model_name: return model elif hasattr(self.model, self.model_name): return getattr(self.model, self.model_name) abort(404) def get_fieldset(self, id): if self.forms and hasattr(self.forms, self.model_name): fs = getattr(self.forms, self.model_name) fs.engine = fs.engine or self.engine return id and fs.bind(self.get(id)) or fs return _RESTController.get_fieldset(self, id) def get_add_fieldset(self): if self.forms and hasattr(self.forms, '%sAdd' % self.model_name): fs = getattr(self.forms, '%sAdd' % self.model_name) fs.engine = fs.engine or self.engine return fs return self.get_fieldset(id=None) def get_grid(self): model_name = self.model_name if self.forms and hasattr(self.forms, '%sGrid' % model_name): g = getattr(self.forms, '%sGrid' % model_name) g.engine = g.engine or self.engine g.readonly = True self.update_grid(g) return g return _RESTController.get_grid(self)
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 = MediaDropMigrator.from_config(config, log=log) db_is_current = True if not alembic_migrations.is_db_scheme_current(): log.warn( 'Running with an outdated database scheme. Please upgrade your database.' ) db_is_current = False plugin_mgr = config['pylons.app_globals'].plugin_mgr db_current_for_plugins = plugin_mgr.is_db_scheme_current_for_all_plugins() if db_is_current and not db_current_for_plugins: log.warn(db_current_for_plugins.message) db_is_current = False if db_is_current: events.Environment.database_ready() # 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 MediaDrop'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 get_static_urlparser(filepath, cache_max_age=1): return StaticURLParser(filepath, cache_max_age=cache_max_age)
def __init__(self): self.javascripts_app = \ StaticURLParser(os.path.dirname(javascript_path))
''' # the body of the page body = """ <button id="sql-button" class="short">SQL</button> <pre id="sql" class="sql" style="display: none">SELECT * FROM Product</pre> """ # the javascript relying on JQuery js = """ $("#sql-button").toggle(function(event){ $("#sql").hide("slow"); }, function(event){ $("#sql").show("slow"); }); """ static = StaticURLParser(directory='/tmp') def application(env, resp): """Return the JQuery-enhanced HTML page and dispatch on the static directory too""" name = shift_path_info(env) if name == 'static': return static(env, resp) resp('200 OK', [('Content-type', 'text/html')]) return [html % (js, body)] if __name__ == '__main__': serve(application, '', 8000)
def static_app(self, environ, start_response): return StaticURLParser.__call__(self, environ, start_response)
def make_app(global_conf, full_stack=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) g = config['pylons.g'] # The Pylons WSGI app app = RedditApp() app = RoutesMiddleware(app, config["routes.map"]) # CUSTOM MIDDLEWARE HERE (filtered by the error handling middlewares) # last thing first from here down app = CleanupMiddleware(app) app = LimitUploadSize(app) profile_directory = g.config.get('profile_directory') if profile_directory: app = ProfilingMiddleware(app, profile_directory) app = DomainListingMiddleware(app) app = SubredditMiddleware(app) app = ExtensionMiddleware(app) app = DomainMiddleware(app) 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) app = ErrorDocuments(app, global_conf, mapper=error_mapper, **app_conf) # Establish the Registry for this application app = RegistryManager(app) # Static files static_app = StaticURLParser(config['pylons.paths']['static_files']) static_cascade = [static_app, app] if config['r2.plugins'] and g.config['uncompressedJS']: plugin_static_apps = Cascade([ StaticURLParser(plugin.static_dir) for plugin in config['r2.plugins'] ]) static_cascade.insert(0, plugin_static_apps) app = Cascade(static_cascade) app = FullPathMiddleware(app) if not g.config['uncompressedJS'] and g.config['debug']: static_fallback = StaticTestMiddleware(static_app, g.config['static_path'], g.config['static_domain']) app = Cascade([static_fallback, app]) 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) # The Pylons WSGI app app = PylonsApp() # Routing/Session/Cache Middleware app = RoutesMiddleware(app, config['routes.map']) app = SessionMiddleware(app, config) app = CacheMiddleware(app, config) g = config['pylons.app_globals'] g.cache_manager = app.cache_manager # 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, [400, 401, 403, 404, 500]) # Establish the Registry for this application app = RegistryManager(app) if asbool(static_files): # Serve static files static_app = StaticURLParser(config['pylons.paths']['static_files']) app = Cascade([static_app, app]) # this is a compatibility hack for pylons > 1.0!!! conf = PyConf(config) conf['global_conf'] = global_conf conf['app_conf'] = app_conf conf['__file__'] = global_conf['__file__'] conf['FILE'] = global_conf['__file__'] conf['routes.map'] = config['routes.map'] if not hasattr(conf, 'init_app'): setattr(conf, 'init_app', config.init_app) app.config = conf 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 load_environment(global_conf, app_conf) # The Pylons WSGI app app = PylonsApp() # Routing/Session/Cache Middleware app = RoutesMiddleware(app, config['routes.map']) app = SessionMiddleware(app, config) app = CacheMiddleware(app, config) # CUSTOM MIDDLEWARE HERE (filtered by error handling middlewares) basicauth = BasicAuthPlugin('OpenSpending') auth_tkt = AuthTktCookiePlugin( 'RANDOM_KEY_THAT_ONLY_LOOKS_LIKE_A_PLACEHOLDER', cookie_name='openspending_login', timeout=86400 * 90, reissue_time=3600) form = FriendlyFormPlugin('/login', '/perform_login', '/after_login', '/logout', '/after_logout', rememberer_name='auth_tkt') identifiers = [('auth_tkt', auth_tkt), ('basicauth', basicauth), ('form', form)] authenticators = [('auth_tkt', auth_tkt), ('username', UsernamePasswordAuthenticator()), ('apikey', ApiKeyAuthenticator())] challengers = [('form', form), ('basicauth', basicauth)] log_stream = sys.stdout app = PluggableAuthenticationMiddleware(app, identifiers, authenticators, challengers, [], default_request_classifier, default_challenge_decider, log_stream=log_stream, log_level=logging.WARN) 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]) # Establish the Registry for this application app = RegistryManager(app) if asbool(static_files): max_age = None if asbool(config['debug']) else 3600 # Serve static files static_app = StaticURLParser(config['pylons.paths']['static_files'], cache_max_age=max_age) static_parsers = [static_app, app] app = Cascade(static_parsers) 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 load_environment(global_conf, app_conf) # The Pylons WSGI app app = PylonsApp() # Routing/Session/Cache Middleware app = RoutesMiddleware(app, config['routes.map']) app = SessionMiddleware(app, config) app = CacheMiddleware(app, config) # CUSTOM MIDDLEWARE HERE (filtered by error handling middlewares) tempdir = os.path.join(config['pylons.cache_dir'], 'fileupload') if not os.path.exists(tempdir): os.makedirs(tempdir) app = FileUpload(app, tempdir=tempdir, max_size=None) 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]) # Establish the Registry for this application app = RegistryManager(app) if asbool(static_files): # Serve static files static_app = StaticURLParser(config['pylons.paths']['static_files']) app = Cascade([static_app, app]) 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) # The Pylons WSGI app app = PylonsApp(config=config) # Routing/Session Middleware app = RoutesMiddleware(app, config['routes.map']) app = SessionMiddleware(app, config) # FTS3 authentication/authorization middleware app = FTS3AuthMiddleware(app, config) # Trap timeouts and the like app = TimeoutHandler(app, config) # Convert errors to a json representation app = ErrorAsJson(app, config) # Request logging app = RequestLogger(app, config) # Error handling if asbool(full_stack): # Handle Python exceptions app = ErrorHandler(app, global_conf, **config['pylons.errorware']) # Establish the Registry for this application app = RegistryManager(app) if asbool(static_files): # Serve static files static_app = StaticURLParser(config['pylons.paths']['static_files']) app = Cascade([static_app, app]) app.config = config # Heartbeat thread Heartbeat('fts_rest', int(config.get('fts3.HeartBeatInterval', 60))).start() return app
def __init__(self, directory, cache_seconds=None, directory_per_host=None): StaticURLParser.__init__(self, directory) self.cache_seconds = cache_seconds self.directory_per_host = directory_per_host
import webapp2 as webapp from constants import VIRTUAL_ENV_DIR, HTTP_PORT, HTTP_HOST, PRODUCTION from constants import USER_NAME try: virtenv = VIRTUAL_ENV_DIR + '/virtenv/' virtualenv = os.path.join(virtenv, 'bin/activate_this.py') execfile(virtualenv, dict(__file__=virtualenv)) #except IOError: except: pass from webpages.mainpage import RecPage from webpages.statistics import UserStatisticsPage application = webapp.WSGIApplication( [('/', RecPage), ('/users/(.+)/(' + USER_NAME + ')', UserStatisticsPage)], debug=not PRODUCTION) if __name__ == '__main__': from wsgiref.simple_server import make_server import webapp2 as webapp from paste.urlparser import StaticURLParser from paste.cascade import Cascade static_app = StaticURLParser("wsgi/") app = Cascade([static_app, application]) httpd = make_server(HTTP_HOST, HTTP_PORT, app) httpd.serve_forever()
def __init__(self, baseapp, static=None): self.pages = {} if static: for name, dirpath in static.iteritems(): self.pages[name] = StaticURLParser(directory=dirpath) self.add('', baseapp)
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) # 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']) # 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) 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 load_environment(global_conf, app_conf) # The Pylons WSGI app app = PylonsApp() # set pylons globals app_globals.reset() for plugin in PluginImplementations(IMiddleware): app = plugin.make_middleware(app, config) # Routing/Session/Cache Middleware app = RoutesMiddleware(app, config['routes.map']) app = SessionMiddleware(app, config) app = CacheMiddleware(app, config) # CUSTOM MIDDLEWARE HERE (filtered by error handling middlewares) #app = QueueLogMiddleware(app) # Fanstatic if asbool(config.get('debug', False)): fanstatic_config = { 'versioning': True, 'recompute_hashes': True, 'minified': False, 'bottom': True, 'bundle': False, } else: fanstatic_config = { 'versioning': True, 'recompute_hashes': False, 'minified': True, 'bottom': True, 'bundle': True, } app = Fanstatic(app, **fanstatic_config) 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, [400, 404]) else: app = StatusCodeRedirect(app, [400, 404, 500]) # Initialize repoze.who who_parser = WhoConfig(global_conf['here']) who_parser.parse(open(app_conf['who.config_file'])) if asbool(config.get('openid_enabled', 'true')): from repoze.who.plugins.openid.identification import OpenIdIdentificationPlugin # Monkey patches for repoze.who.openid # Fixes #1659 - enable log-out when CKAN mounted at non-root URL from ckan.lib import repoze_patch OpenIdIdentificationPlugin.identify = repoze_patch.identify OpenIdIdentificationPlugin.redirect_to_logged_in = repoze_patch.redirect_to_logged_in OpenIdIdentificationPlugin._redirect_to_loginform = repoze_patch._redirect_to_loginform OpenIdIdentificationPlugin.challenge = repoze_patch.challenge who_parser.identifiers = [i for i in who_parser.identifiers if \ not isinstance(i, OpenIdIdentificationPlugin)] who_parser.challengers = [i for i in who_parser.challengers if \ not isinstance(i, OpenIdIdentificationPlugin)] app = PluggableAuthenticationMiddleware( app, who_parser.identifiers, who_parser.authenticators, who_parser.challengers, who_parser.mdproviders, who_parser.request_classifier, who_parser.challenge_decider, logging.getLogger('repoze.who'), logging.WARN, # ignored who_parser.remote_user_key, ) # Establish the Registry for this application app = RegistryManager(app) app = I18nMiddleware(app, config) if asbool(static_files): # Serve static files static_max_age = None if not asbool(config.get('ckan.cache_enabled')) \ else int(config.get('ckan.static_max_age', 3600)) static_app = StaticURLParser(config['pylons.paths']['static_files'], cache_max_age=static_max_age) static_parsers = [static_app, app] # Configurable extra static file paths extra_static_parsers = [] for public_path in config.get('extra_public_paths', '').split(','): if public_path.strip(): extra_static_parsers.append( StaticURLParser(public_path.strip(), cache_max_age=static_max_age)) app = Cascade(extra_static_parsers + static_parsers) # Page cache if asbool(config.get('ckan.page_cache_enabled')): app = PageCacheMiddleware(app, config) # Tracking if asbool(config.get('ckan.tracking_enabled', 'false')): app = TrackingMiddleware(app, config) return app
def __init__( self, directory, cache_seconds=None ): StaticURLParser.__init__( self, directory ) self.cache_seconds = cache_seconds
def make_app(global_config, **kwargs): import os from paste.urlparser import StaticURLParser app = StaticURLParser( os.path.join(global_config['here'], 'docs/_build/html')) return Demo(app, headers=True)
if __name__ == '__main__': import optparse parser = optparse.OptionParser(usage='%prog --port=PORT BASE_DIRECTORY') parser.add_option('-p', '--port', default='8080', dest='port', type='int', help='Port to serve on (default 8080)') parser.add_option( '--comment-data', default='./comments', dest='comment_data', help='Place to put comment data into (default ./comments/)') options, args = parser.parse_args() if not args: parser.error('You must give a BASE_DIRECTORY') base_dir = args[0] from paste.urlparser import StaticURLParser app = StaticURLParser(base_dir) app = Commenter(app, options.comment_data) from wsgiref.simple_server import make_server httpd = make_server('localhost', options.port, app) print('Serving on http://localhost:%s' % options.port) try: httpd.serve_forever() except KeyboardInterrupt: print('^C')
def make_pylons_stack(conf, full_stack=True, static_files=True, **app_conf): """Create a Pylons WSGI application and return it ``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 load_environment(conf, app_conf) # The Pylons WSGI app app = PylonsApp() # set pylons globals app_globals.reset() for plugin in PluginImplementations(IMiddleware): app = plugin.make_middleware(app, config) # Routing/Session/Cache Middleware app = RoutesMiddleware(app, config['routes.map']) # we want to be able to retrieve the routes middleware to be able to update # the mapper. We store it in the pylons config to allow this. config['routes.middleware'] = app app = SessionMiddleware(app, config) app = CacheMiddleware(app, config) # CUSTOM MIDDLEWARE HERE (filtered by error handling middlewares) # app = QueueLogMiddleware(app) if asbool(config.get('ckan.use_pylons_response_cleanup_middleware', True)): app = execute_on_completion(app, config, cleanup_pylons_response_string) # Fanstatic if asbool(config.get('debug', False)): fanstatic_config = { 'versioning': True, 'recompute_hashes': True, 'minified': False, 'bottom': True, 'bundle': False, } else: fanstatic_config = { 'versioning': True, 'recompute_hashes': False, 'minified': True, 'bottom': True, 'bundle': True, } app = Fanstatic(app, **fanstatic_config) for plugin in PluginImplementations(IMiddleware): try: app = plugin.make_error_log_middleware(app, config) except AttributeError: log.critical('Middleware class {0} is missing the method' 'make_error_log_middleware.'.format( plugin.__class__.__name__)) if asbool(full_stack): # Handle Python exceptions app = ErrorHandler(app, conf, **config['pylons.errorware']) # Display error documents for 400, 403, 404 status codes (and # 500 when debug is disabled) if asbool(config['debug']): app = StatusCodeRedirect(app, [400, 403, 404]) else: app = StatusCodeRedirect(app, [400, 403, 404, 500]) # Initialize repoze.who who_parser = WhoConfig(conf['here']) who_parser.parse(open(app_conf['who.config_file'])) app = PluggableAuthenticationMiddleware( app, who_parser.identifiers, who_parser.authenticators, who_parser.challengers, who_parser.mdproviders, who_parser.request_classifier, who_parser.challenge_decider, logging.getLogger('repoze.who'), logging.WARN, # ignored who_parser.remote_user_key) # Establish the Registry for this application app = RegistryManager(app) app = I18nMiddleware(app, config) if asbool(static_files): # Serve static files static_max_age = None if not asbool(config.get('ckan.cache_enabled')) \ else int(config.get('ckan.static_max_age', 3600)) static_app = StaticURLParser(config['pylons.paths']['static_files'], cache_max_age=static_max_age) static_parsers = [static_app, app] storage_directory = uploader.get_storage_path() if storage_directory: path = os.path.join(storage_directory, 'storage') try: os.makedirs(path) except OSError, e: # errno 17 is file already exists if e.errno != 17: raise storage_app = StaticURLParser(path, cache_max_age=static_max_age) static_parsers.insert(0, storage_app) # Configurable extra static file paths extra_static_parsers = [] for public_path in config.get('extra_public_paths', '').split(','): if public_path.strip(): extra_static_parsers.append( StaticURLParser(public_path.strip(), cache_max_age=static_max_age)) app = Cascade(extra_static_parsers + static_parsers)
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) # The Pylons WSGI app app = PylonsApp(config=config) # Routing/Session Middleware app = RoutesMiddleware(app, config['routes.map'], singleton=False) app = SessionMiddleware(app, config) # CUSTOM MIDDLEWARE HERE (filtered by error handling middlewares) if 'what_log_file' in app_conf: what_log_file = app_conf['what_log_file'] # if (not os.path.exists(what_log_file) or # not os.path.isfile(what_log_file)): # what_log_file = None else: what_log_file = None what_log_level = 'DEBUG' if asbool(config['debug']) else 'INFO' app = make_middleware_with_config( app, global_conf, app_conf['what_config_file'], who_config_file=app_conf['who_config_file'], log_file=what_log_file, log_level=what_log_level) 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]) # Establish the Registry for this application app = RegistryManager(app) if asbool(static_files): # Serve static files static_app = StaticURLParser(config['pylons.paths']['static_files']) app = Cascade([static_app, app]) app.config = config return app
# defined custom error handlers class Webapp2HandlerAdapter(webapp2.BaseHandlerAdapter): def __call__(self, request, response, exception): request.route_args = {'exception': exception} logging.exception(exception) handler = self.handler(request, response) return handler.get() app.error_handlers[403] = Webapp2HandlerAdapter(errors.Error403Handler) app.error_handlers[404] = Webapp2HandlerAdapter(errors.Error404Handler) app.error_handlers[503] = Webapp2HandlerAdapter(errors.Error503Handler) app.error_handlers[500] = Webapp2HandlerAdapter(errors.Error500Handler) # Static File Serving static_app = StaticURLParser("static/") # Check static files first then fallback application = Cascade([static_app, app]) if __name__ == '__main__' and basehandler.IS_DEV: import paste.reloader as reloader reloader.install(10) from paste.translogger import TransLogger application = TransLogger(application, logger_name=None) from paste import httpserver httpserver.serve(application, host='127.0.0.1', port='8080')
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) # The Pylons WSGI app app = PylonsApp(config=config) # Routing/Session/Cache Middleware app = RoutesMiddleware(app, config['routes.map']) app = SessionMiddleware(app, config) app = CacheMiddleware(app, config) # Needed by authkit app = RecursiveMiddleware(app, global_conf) # CUSTOM MIDDLEWARE HERE (filtered by error handling middlewares) # Ponies! app = PonyMiddleware(app) # CUSTOM MIDDLEWARE END if asbool(full_stack): # Handle Python exceptions app = ErrorHandler(app, global_conf, **config['pylons.errorware']) app = authkit.authenticate.middleware(app, app_conf) # 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]) # Establish the Registry for this application app = RegistryManager(app) if asbool(static_files): # Serve static files static_app = [] for static_files_dir in config['pylons.paths']['static_files']: static_app.append(StaticURLParser(static_files_dir)) static_apps = Cascade(static_app, catch=(404, )) app = Cascade([static_apps, app]) 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) # The Pylons WSGI app app = PylonsApp(config=config) # Routing/Session/Cache Middleware app = RoutesMiddleware(app, config['routes.map'], singleton=False) app = SessionMiddleware(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, [400, 401, 403, 404, 500]) # Establish the Registry for this application app = RegistryManager(app) if asbool(static_files): # Serve static files static_app = StaticURLParser(config['pylons.paths']['static_files']) app = Cascade([static_app, app]) app.config = config # gzip middleware app = make_gzip_middleware(app, config) # Add Access-Control headers if 'allowed_origins' in config: log.info("Adding ControlHeadersMiddleware") app = ControlHeadersMiddleware(app, config) return app
def main(): assets_dir = os.path.join(os.path.dirname(__file__)) static_app = StaticURLParser(directory=assets_dir) web_app = Cascade([app, static_app]) httpserver.serve(web_app, host='localhost', port='8080')
def __init__(self, **kwargs): self.javascripts_app = \ StaticURLParser('/javascripts/', **kwargs)
def __init__(self, **kwargs): from webhelpers.rails.asset_tag import javascript_path self.javascripts_app = \ StaticURLParser(os.path.dirname(javascript_path), **kwargs)