def test_dispatchermiddleware(): def null_application(environ, start_response): start_response('404 NOT FOUND', [('Content-Type', 'text/plain')]) yield b'NOT FOUND' def dummy_application(environ, start_response): start_response('200 OK', [('Content-Type', 'text/plain')]) yield to_bytes(environ['SCRIPT_NAME']) app = wsgi.DispatcherMiddleware(null_application, { '/test1': dummy_application, '/test2/very': dummy_application, }) tests = { '/test1': ('/test1', '/test1/asfd', '/test1/very'), '/test2/very': ('/test2/very', '/test2/very/long/path/after/script/name') } for name, urls in tests.items(): for p in urls: environ = create_environ(p) app_iter, status, headers = run_wsgi_app(app, environ) assert status == '200 OK' assert b''.join(app_iter).strip() == to_bytes(name) app_iter, status, headers = run_wsgi_app(app, create_environ('/missing')) assert status == '404 NOT FOUND' assert b''.join(app_iter).strip() == b'NOT FOUND'
def WSGIHandler(self): """Returns GRR's WSGI handler.""" sdm = werkzeug_wsgi.SharedDataMiddleware(self, { "/": config.CONFIG["AdminUI.document_root"], }) # Use DispatcherMiddleware to make sure that SharedDataMiddleware is not # used at all if the URL path doesn't start with "/static". This is a # workaround for cases when unicode URLs are used on systems with # non-unicode filesystems (as detected by Werkzeug). In this case # SharedDataMiddleware may fail early while trying to convert the # URL into the file path and not dispatch the call further to our own # WSGI handler. return werkzeug_wsgi.DispatcherMiddleware(self, { "/static": sdm, })
def setup_app(): root_app = flask.Flask('cloudkitty') root_api = flask_restful.Api(root_app) root_api.add_resource(api_root.CloudkittyAPIRoot, '/') dispatch_dict = { '/v1': get_v1_app(), '/v2': get_v2_app(), } # Disabling v2 api in case v1 storage is used if CONF.storage.version < 2: LOG.warning('v1 storage is used, disabling v2 API') dispatch_dict.pop('/v2') app = wsgi.DispatcherMiddleware(root_app, dispatch_dict) return app
def main(): """Parse the arguments and run the test bench application.""" parser = argparse.ArgumentParser( description='A testbench for the Google Cloud C++ Client Library') parser.add_argument('--host', default='localhost', help='The listening port') parser.add_argument('--port', help='The listening port') # By default we do not turn on the debugging. This typically runs inside a # Docker image, with a uid that has not entry in /etc/passwd, and the # werkzeug debugger crashes in that environment (as it should probably). parser.add_argument('--debug', help='Use the WSGI debugger', default=False, action='store_true') arguments = parser.parse_args() # Compose the different WSGI applications. application = wsgi.DispatcherMiddleware(root, { '/httpbin': httpbin.app, GCS_HANDLER_PATH: gcs, UPLOAD_HANDLER_PATH: upload, }) serving.run_simple(arguments.host, int(arguments.port), application, use_reloader=True, use_debugger=arguments.debug, use_evalex=True)
template_params = environ.get("pywb.template_params", {}) template_params["h_embed_url"] = embed_url environ["pywb.template_params"] = template_params return pywb.apps.wayback.application(environ, start_response) application = RequestHeaderSanitiser(app) application = ResponseHeaderSanitiser(application) application = Blocker( application, checkmate_host=os.environ["CHECKMATE_URL"], api_key=os.environ["CHECKMATE_API_KEY"], ) application = UserAgentDecorator(application, "Hypothesis-Via") application = ConfigExtractor(application) application = wsgi.DispatcherMiddleware( application, { "/favicon.ico": static.Cling("static/favicon.ico"), "/robots.txt": static.Cling("static/robots.txt"), "/static": static.Cling("static/"), "/static/__pywb": static.Cling(resource_filename("pywb", "static/")), "/static/__shared/viewer/web/viewer.html": redirect_old_viewer, "/h": redirect_strip_matched_path, "/_status": status_endpoint, }, ) application = newrelic.agent.WSGIApplicationWrapper(application, name="proxy")
raise ErrorResponse('Name not set in Objects: insert', status_code=412) object_path = bucket_name + '/o/' + object_name gcs_object = GCS_OBJECTS.get(object_path, GcsObject(bucket_name, object_name)) gcs_object.check_preconditions(flask.request) GCS_OBJECTS[object_path] = gcs_object gcs_object.insert(gcs_url, flask.request) current_version = gcs_object.get_latest() return filtered_response(flask.request, current_version.metadata) application = wsgi.DispatcherMiddleware(root, { '/httpbin': httpbin.app, GCS_HANDLER_PATH: gcs, UPLOAD_HANDLER_PATH: upload, }) def main(): """Parse the arguments and run the test bench application.""" parser = argparse.ArgumentParser( description='A testbench for the Google Cloud C++ Client Library') parser.add_argument('--host', default='localhost', help='The listening port') parser.add_argument('--port', help='The listening port') # By default we do not turn on the debugging. This typically runs inside a # Docker image, with a uid that has not entry in /etc/passwd, and the # werkzeug debugger crashes in that environment (as it should probably).
import flask from werkzeug import wsgi from common import config, constants from common import datastore_schema as ds from common import secret_keys as sk from backend.upload_server import UploadServer service_account_path = os.path.abspath('./common/service_account.json') os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = service_account_path logging.basicConfig(level=logging.DEBUG, format=constants.LOG_FMT_M_THREADED) upload_server = UploadServer( config.PROJECT_ID, sk.FLASK_SESSION_ENC_KEY, sk.GOOGLE_OAUTH2_CLIENT_ID, sk.GOOGLE_OAUTH2_CLIENT_SECRET, file_not_ready_suffix=constants.FILE_NOT_READY_SUFFIX, directory=constants.UPLOAD_DIR, datastore_kind=ds.DATASTORE_PHOTO, user_datastore_kind=ds.DATASTORE_USER, retrys=constants.RETRYS) # Set up the app so that all it's routes live under the /upload url prefix # A dummy no-op flask app is used for all other routes, so they will result in # a 404 not found error. app = wsgi.DispatcherMiddleware( flask.Flask('nop'), {constants.UPLOAD_SERVICE_URL_PREFIX: upload_server})
response = flask.make_response('') response.headers['x-goog-hash'] = revision.x_goog_hash_header() return response # Define the WSGI application to handle HMAC key requests (PROJECTS_HANDLER_PATH, projects_app) = gcs_project.get_projects_app() # Define the WSGI application to handle IAM requests (IAM_HANDLER_PATH, iam_app) = gcs_iam.get_iam_app() application = wsgi.DispatcherMiddleware( root, { '/httpbin': httpbin.app, GCS_HANDLER_PATH: gcs, UPLOAD_HANDLER_PATH: upload, XMLAPI_HANDLER_PATH: xmlapi, PROJECTS_HANDLER_PATH: projects_app, IAM_HANDLER_PATH: iam_app, }) def main(): """Parse the arguments and run the test bench application.""" parser = argparse.ArgumentParser( description='A testbench for the Google Cloud C++ Client Library') parser.add_argument('--host', default='localhost', help='The listening port') parser.add_argument('--port', help='The listening port') # By default we do not turn on the debugging. This typically runs inside a
# /foo/bar?baz -> /bar?baz # /foo/http://example.com -> /http://example.com # # and so on. @wsgi.responder def redirect_strip_matched_path(environ, start_response): request = Request(environ) path = request.path if request.query_string: path += '?' + request.query_string return redirect(path, code=301) def app(environ, start_response): embed_url = os.environ.get('H_EMBED_URL', 'https://hypothes.is/embed.js') template_params = environ.get('pywb.template_params', {}) template_params['h_embed_url'] = embed_url environ['pywb.template_params'] = template_params return pywb.apps.wayback.application(environ, start_response) application = wsgi.DispatcherMiddleware(app, { '/favicon.ico': static.Cling('static/favicon.ico'), '/static': static.Cling('static/'), '/static/__pywb': static.Cling(resource_filename('pywb', 'static/')), '/static/__shared/viewer/web/viewer.html': redirect_old_viewer, '/h': redirect_strip_matched_path, })
embed_url = os.environ.get("H_EMBED_URL", "https://hypothes.is/embed.js") template_params = environ.get("pywb.template_params", {}) template_params["h_embed_url"] = embed_url environ["pywb.template_params"] = template_params return pywb.apps.wayback.application(environ, start_response) application = RequestHeaderSanitiser(app) application = ResponseHeaderSanitiser(application) application = Blocker( application, checkmate_host=os.environ["CHECKMATE_URL"], api_key=os.environ["CHECKMATE_API_KEY"], ) application = UserAgentDecorator(application, "Hypothesis-Via") application = ConfigExtractor(application) application = wsgi.DispatcherMiddleware(application, ROUTES) application = newrelic.agent.WSGIApplicationWrapper(application, name="proxy") if os.environ.get("SENTRY_DSN"): # pragma: no cover # As both pywb and sentry shamelessly monkey patch gevent etc the order # of imports matter. Importing sentry here results in the right patching. import sentry_sdk from sentry_sdk.integrations.wsgi import SentryWsgiMiddleware # pylint: disable=redefined-variable-type sentry_sdk.init(dsn=os.environ["SENTRY_DSN"]) application = SentryWsgiMiddleware(application)