def test_get_script_name(self): # Regression test for #23173 # Test first without PATH_INFO script_name = get_script_name({'SCRIPT_URL': '/foobar/'}) self.assertEqual(script_name, '/foobar/') script_name = get_script_name({'SCRIPT_URL': '/foobar/', 'PATH_INFO': '/'}) self.assertEqual(script_name, '/foobar')
def test_get_script_name(self): # Regression test for #23173 # Test first without PATH_INFO script_name = get_script_name({"SCRIPT_URL": "/foobar/"}) self.assertEqual(script_name, "/foobar/") script_name = get_script_name({"SCRIPT_URL": "/foobar/", "PATH_INFO": "/"}) self.assertEqual(script_name, "/foobar")
def test_get_script_name(self): # Regression test for #23173 # Test first without PATH_INFO script_name = get_script_name({"SCRIPT_URL": "/foobar/"}) self.assertEqual(script_name, "/foobar/") script_name = get_script_name({ "SCRIPT_URL": "/foobar/", "PATH_INFO": "/" }) self.assertEqual(script_name, "/foobar")
def get(self, *args, **kwargs): # type: (*Any, **Any) -> None environ = WSGIContainer.environ(self.request) environ['PATH_INFO'] = urllib.parse.unquote(environ['PATH_INFO']) request = WSGIRequest(environ) request._tornado_handler = self set_script_prefix(get_script_name(environ)) signals.request_started.send(sender=self.__class__) try: response = self.get_response(request) if not response: return finally: signals.request_finished.send(sender=self.__class__) self.set_status(response.status_code) for h in response.items(): self.set_header(h[0], h[1]) if not hasattr(self, "_new_cookies"): self._new_cookies = [] # type: List[http.cookie.SimpleCookie] self._new_cookies.append(response.cookies) self.write(response.content) self.finish()
async def convert_tornado_request_to_django_request(self) -> HttpRequest: # This takes the WSGI environment that Tornado received (which # fully describes the HTTP request that was sent to Tornado) # and pass it to Django's WSGIRequest to generate a Django # HttpRequest object with the original Tornado request's HTTP # headers, parameters, etc. environ = WSGIContainer.environ(self.request) environ["PATH_INFO"] = urllib.parse.unquote(environ["PATH_INFO"]) # Django WSGIRequest setup code that should match logic from # Django's WSGIHandler.__call__ before the call to # `get_response()`. set_script_prefix(get_script_name(environ)) await sync_to_async( lambda: signals.request_started.send(sender=self.__class__), thread_sensitive=True)() self._request = WSGIRequest(environ) # We do the import during runtime to avoid cyclic dependency from zerver.lib.request import RequestNotes # Provide a way for application code to access this handler # given the HttpRequest object. RequestNotes.get_notes( self._request).tornado_handler_id = self.handler_id return self._request
def get(self): from tornado.wsgi import WSGIContainer from django.core.handlers.wsgi import WSGIRequest, get_script_name import urllib environ = WSGIContainer.environ(self.request) environ['PATH_INFO'] = urllib.unquote(environ['PATH_INFO']) request = WSGIRequest(environ) request._tornado_handler = self set_script_prefix(get_script_name(environ)) signals.request_started.send(sender=self.__class__) try: response = self.get_response(request) if not response: return finally: signals.request_finished.send(sender=self.__class__) self.set_status(response.status_code) for h in response.items(): self.set_header(h[0], h[1]) if not hasattr(self, "_new_cookies"): self._new_cookies = [] self._new_cookies.append(response.cookies) self.write(response.content) self.finish()
def distributed_sqlite(environ, start_response): """ Custom WSGI application meant to work with ara.server.db.backends.distributed_sqlite in order to dynamically load different databases at runtime. """ # This endpoint is read only, do not accept write requests. if environ["REQUEST_METHOD"] not in ["GET", "HEAD", "OPTIONS"]: handle_405(start_response) script_name = get_script_name(environ) path_info = get_path_info(environ) from django.conf import settings # The root under which database files are expected root = settings.DISTRIBUTED_SQLITE_ROOT # The prefix after which everything should be delegated (ex: /ara-report) prefix = settings.DISTRIBUTED_SQLITE_PREFIX # Static assets should always be served by the regular app if path_info.startswith(settings.STATIC_URL): return application(environ, start_response) if prefix not in path_info: logger.warn("Ignoring request: URL does not contain delegated prefix (%s)" % prefix) return handle_404(start_response) # Slice path_info up until after the prefix to obtain the requested directory i = path_info.find(prefix) + len(prefix) fs_path = path_info[:i] # Make sure we aren't escaping outside the root and the directory exists db_dir = os.path.abspath(os.path.join(root, fs_path.lstrip("/"))) if not db_dir.startswith(root): logger.warn("Ignoring request: path is outside the root (%s)" % db_dir) return handle_404(start_response) elif not os.path.exists(db_dir): logger.warn("Ignoring request: database directory not found (%s)" % db_dir) return handle_404(start_response) # Find the database file and make sure it exists db_file = os.path.join(db_dir, "ansible.sqlite") if not os.path.exists(db_file): logger.warn("Ignoring request: database file not found (%s)" % db_file) return handle_404(start_response) # Tell Django about the new URLs it should be using environ["SCRIPT_NAME"] = script_name + fs_path environ["PATH_INFO"] = path_info[len(fs_path) :] # noqa: E203 # Store the path of the database in a thread so the distributed_sqlite # database backend can retrieve it. from ara.server.db.backends.distributed_sqlite.base import local_storage local_storage.db_path = db_file try: return application(environ, start_response) finally: del local_storage.db_path
def test_get_script_name_double_slashes(self): """ WSGI squashes multiple successive slashes in PATH_INFO, get_script_name should take that into account when forming SCRIPT_NAME (#17133). """ script_name = get_script_name( {"SCRIPT_URL": "/mst/milestones//accounts/login//help", "PATH_INFO": "/milestones/accounts/login/help"} ) self.assertEqual(script_name, "/mst")
def __init__(self, environ): self.environ = environ self.path_info = wsgi.get_path_info(environ) self.script_name = wsgi.get_script_name(environ) self.path = "unknown" self.META = environ self.META['PATH_INFO'] = self.path_info self.META['SCRIPT_NAME'] = self.script_name self.method = environ['REQUEST_METHOD'].upper() self.status = ""
def test_get_script_name_double_slashes(self): """ WSGI squashes multiple successive slashes in PATH_INFO, get_script_name should take that into account when forming SCRIPT_NAME (#17133). """ script_name = get_script_name({ 'SCRIPT_URL': '/mst/milestones//accounts/login//help', 'PATH_INFO': '/milestones/accounts/login/help', }) self.assertEqual(script_name, '/mst')
def convert_tornado_request_to_django_request(self) -> HttpRequest: # This takes the WSGI environment that Tornado received (which # fully describes the HTTP request that was sent to Tornado) # and pass it to Django's WSGIRequest to generate a Django # HttpRequest object with the original Tornado request's HTTP # headers, parameters, etc. environ = WSGIContainer.environ(self.request) environ['PATH_INFO'] = urllib.parse.unquote(environ['PATH_INFO']) # Django WSGIRequest setup code that should match logic from # Django's WSGIHandler.__call__ before the call to # `get_response()`. set_script_prefix(get_script_name(environ)) signals.request_started.send(sender=self.__class__) request = WSGIRequest(environ) # Provide a way for application code to access this handler # given the HttpRequest object. request._tornado_handler = self return request
def __call__(self, environ, start_response): # Generate a compatible url from the ROOT_SUBDIRECTORY_PATH pre_path = django.conf.settings.ROOT_SUBDIRECTORY_PATH if len(pre_path): # Confirm that the first character is a forward slash if pre_path[0] != '/': # No, insert a forward slash pre_path = "/" + pre_path # Confirm that the last character is not a forward slash if pre_path[-1] == '/': # Remove the forward slash pre_path = pre_path[:-1] # Override the environment paths #environ['RAW_URI'] = "{}{}".format(pre_path, environ['RAW_URI']) #environ['PATH_INFO'] = "{}{}".format(pre_path, environ['PATH_INFO']) set_script_prefix(get_script_name(environ)) signals.request_started.send(sender=self.__class__, environ=environ) request = self.request_class(environ) response = self.get_response(request) response._handler_class = self.__class__ status = '%d %s' % (response.status_code, response.reason_phrase) response_headers = [(str(k), str(v)) for k, v in response.items()] for c in response.cookies.values(): response_headers.append( (str('Set-Cookie'), str(c.output(header='')))) start_response(force_str(status), response_headers) if getattr(response, 'file_to_stream', None) is not None and environ.get('wsgi.file_wrapper'): response = environ['wsgi.file_wrapper'](response.file_to_stream) return response
from django.conf.urls import url, include from django.conf import settings from importlib import import_module from django.contrib.staticfiles.urls import staticfiles_urlpatterns from django.core.handlers.wsgi import get_script_name from django.urls import set_script_prefix set_script_prefix(get_script_name({})) api_module = import_module('.'.join(settings.TASTYPIE_DOC_API.split('.')[:-1])) try: version = api_module.__version__ except AttributeError: version = None info = getattr(settings, 'API_INFO') urlpatterns =[ url(r'^{0}/'.format(settings.SERVER_BASE_PATH[1:]), include('chembl_webservices.urls')), url(r'^{0}/'.format(settings.SERVER_BASE_PATH[1:]), include('tastypie_spore_docs.urls')) ] urlpatterns += staticfiles_urlpatterns() def handler500(request): """ 500 error handler which includes ``request`` in the context. Templates: `500.html` Context: None """