From 5393ea0fe5d746702cb4b2638a290a5188da2ea5 Mon Sep 17 00:00:00 2001 From: Aber Date: Wed, 6 Dec 2023 20:26:04 +0800 Subject: [PATCH] Follow https://github.com/django/asgiref/issues/229#issuecomment-765583185 (#40) --- a2wsgi/asgi.py | 7 +++++-- a2wsgi/wsgi.py | 20 +++++++++++--------- 2 files changed, 16 insertions(+), 11 deletions(-) diff --git a/a2wsgi/asgi.py b/a2wsgi/asgi.py index 7a9396a..6fb549a 100644 --- a/a2wsgi/asgi.py +++ b/a2wsgi/asgi.py @@ -93,6 +93,9 @@ def build_scope(environ: Environ) -> Scope: else: client = None + root_path = environ.get("SCRIPT_NAME", "").encode("latin1").decode("utf8") + path = root_path + environ["PATH_INFO"].encode("latin1").decode("utf8") + return { "wsgi_environ": environ, "type": "http", @@ -100,9 +103,9 @@ def build_scope(environ: Environ) -> Scope: "http_version": environ.get("SERVER_PROTOCOL", "http/1.0").split("/")[1], "method": environ["REQUEST_METHOD"], "scheme": environ.get("wsgi.url_scheme", "http"), - "path": environ["PATH_INFO"].encode("latin1").decode("utf8"), + "path": path, "query_string": environ["QUERY_STRING"].encode("ascii"), - "root_path": environ.get("SCRIPT_NAME", "").encode("latin1").decode("utf8"), + "root_path": root_path, "client": client, "server": (environ["SERVER_NAME"], int(environ["SERVER_PORT"])), "headers": headers, diff --git a/a2wsgi/wsgi.py b/a2wsgi/wsgi.py index b68adaf..999ddd3 100644 --- a/a2wsgi/wsgi.py +++ b/a2wsgi/wsgi.py @@ -91,18 +91,20 @@ def build_environ(scope: Scope, body: Body) -> Environ: """ Builds a scope and request body into a WSGI environ object. """ - allow_rewrite_environ = { - "SCRIPT_NAME": scope.get("root_path", "").encode("utf8").decode("latin1"), - } - for key in allow_rewrite_environ.keys(): - environ_var = os.environ.get(key, "") - if environ_var: - allow_rewrite_environ[key] = unicode_to_wsgi(environ_var) + script_name = scope.get("root_path", "").encode("utf8").decode("latin1") + path_info = scope["path"].encode("utf8").decode("latin1") + if path_info.startswith(script_name): + path_info = path_info[len(script_name):] + + script_name_environ_var = os.environ.get("SCRIPT_NAME", "") + if script_name_environ_var: + script_name = unicode_to_wsgi(script_name_environ_var) + environ = { - **allow_rewrite_environ, "asgi.scope": scope, "REQUEST_METHOD": scope["method"], - "PATH_INFO": scope["path"].encode("utf8").decode("latin1"), + "SCRIPT_NAME": script_name, + "PATH_INFO": path_info, "QUERY_STRING": scope["query_string"].decode("ascii"), "SERVER_PROTOCOL": f"HTTP/{scope['http_version']}", "wsgi.version": (1, 0),