File manager - Edit - /home/newsbmcs.com/public_html/static/img/logo/wsgi.py.tar
Back
usr/local/CyberCP/lib/python3.10/site-packages/asgiref/wsgi.py 0000644 00000015141 15030004273 0020006 0 ustar 00 from io import BytesIO from tempfile import SpooledTemporaryFile from asgiref.sync import AsyncToSync, sync_to_async class WsgiToAsgi: """ Wraps a WSGI application to make it into an ASGI application. """ def __init__(self, wsgi_application): self.wsgi_application = wsgi_application async def __call__(self, scope, receive, send): """ ASGI application instantiation point. We return a new WsgiToAsgiInstance here with the WSGI app and the scope, ready to respond when it is __call__ed. """ await WsgiToAsgiInstance(self.wsgi_application)(scope, receive, send) class WsgiToAsgiInstance: """ Per-socket instance of a wrapped WSGI application """ def __init__(self, wsgi_application): self.wsgi_application = wsgi_application self.response_started = False self.response_content_length = None async def __call__(self, scope, receive, send): if scope["type"] != "http": raise ValueError("WSGI wrapper received a non-HTTP scope") self.scope = scope with SpooledTemporaryFile(max_size=65536) as body: # Alright, wait for the http.request messages while True: message = await receive() if message["type"] != "http.request": raise ValueError("WSGI wrapper received a non-HTTP-request message") body.write(message.get("body", b"")) if not message.get("more_body"): break body.seek(0) # Wrap send so it can be called from the subthread self.sync_send = AsyncToSync(send) # Call the WSGI app await self.run_wsgi_app(body) def build_environ(self, scope, body): """ Builds a scope and request body into a WSGI environ object. """ 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) :] environ = { "REQUEST_METHOD": scope["method"], "SCRIPT_NAME": script_name, "PATH_INFO": path_info, "QUERY_STRING": scope["query_string"].decode("ascii"), "SERVER_PROTOCOL": "HTTP/%s" % scope["http_version"], "wsgi.version": (1, 0), "wsgi.url_scheme": scope.get("scheme", "http"), "wsgi.input": body, "wsgi.errors": BytesIO(), "wsgi.multithread": True, "wsgi.multiprocess": True, "wsgi.run_once": False, } # Get server name and port - required in WSGI, not in ASGI if "server" in scope: environ["SERVER_NAME"] = scope["server"][0] environ["SERVER_PORT"] = str(scope["server"][1]) else: environ["SERVER_NAME"] = "localhost" environ["SERVER_PORT"] = "80" if scope.get("client") is not None: environ["REMOTE_ADDR"] = scope["client"][0] # Go through headers and make them into environ entries for name, value in self.scope.get("headers", []): name = name.decode("latin1") if name == "content-length": corrected_name = "CONTENT_LENGTH" elif name == "content-type": corrected_name = "CONTENT_TYPE" else: corrected_name = "HTTP_%s" % name.upper().replace("-", "_") # HTTPbis say only ASCII chars are allowed in headers, but we latin1 just in case value = value.decode("latin1") if corrected_name in environ: value = environ[corrected_name] + "," + value environ[corrected_name] = value return environ def start_response(self, status, response_headers, exc_info=None): """ WSGI start_response callable. """ # Don't allow re-calling once response has begun if self.response_started: raise exc_info[1].with_traceback(exc_info[2]) # Don't allow re-calling without exc_info if hasattr(self, "response_start") and exc_info is None: raise ValueError( "You cannot call start_response a second time without exc_info" ) # Extract status code status_code, _ = status.split(" ", 1) status_code = int(status_code) # Extract headers headers = [ (name.lower().encode("ascii"), value.encode("ascii")) for name, value in response_headers ] # Extract content-length self.response_content_length = None for name, value in response_headers: if name.lower() == "content-length": self.response_content_length = int(value) # Build and send response start message. self.response_start = { "type": "http.response.start", "status": status_code, "headers": headers, } @sync_to_async def run_wsgi_app(self, body): """ Called in a subthread to run the WSGI app. We encapsulate like this so that the start_response callable is called in the same thread. """ # Translate the scope and incoming request body into a WSGI environ environ = self.build_environ(self.scope, body) # Run the WSGI app bytes_sent = 0 for output in self.wsgi_application(environ, self.start_response): # If this is the first response, include the response headers if not self.response_started: self.response_started = True self.sync_send(self.response_start) # If the application supplies a Content-Length header if self.response_content_length is not None: # The server should not transmit more bytes to the client than the header allows bytes_allowed = self.response_content_length - bytes_sent if len(output) > bytes_allowed: output = output[:bytes_allowed] self.sync_send( {"type": "http.response.body", "body": output, "more_body": True} ) bytes_sent += len(output) # The server should stop iterating over the response when enough data has been sent if bytes_sent == self.response_content_length: break # Close connection if not self.response_started: self.response_started = True self.sync_send(self.response_start) self.sync_send({"type": "http.response.body"}) usr/local/CyberCP/lib/python3.10/site-packages/tornado/wsgi.py 0000644 00000025101 15030023746 0020037 0 ustar 00 # # Copyright 2009 Facebook # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """WSGI support for the Tornado web framework. WSGI is the Python standard for web servers, and allows for interoperability between Tornado and other Python web frameworks and servers. This module provides WSGI support via the `WSGIContainer` class, which makes it possible to run applications using other WSGI frameworks on the Tornado HTTP server. The reverse is not supported; the Tornado `.Application` and `.RequestHandler` classes are designed for use with the Tornado `.HTTPServer` and cannot be used in a generic WSGI container. """ import concurrent.futures from io import BytesIO import tornado import sys from tornado.concurrent import dummy_executor from tornado import escape from tornado import httputil from tornado.ioloop import IOLoop from tornado.log import access_log from typing import List, Tuple, Optional, Callable, Any, Dict, Text from types import TracebackType import typing if typing.TYPE_CHECKING: from typing import Type # noqa: F401 from _typeshed.wsgi import WSGIApplication as WSGIAppType # noqa: F401 # PEP 3333 specifies that WSGI on python 3 generally deals with byte strings # that are smuggled inside objects of type unicode (via the latin1 encoding). # This function is like those in the tornado.escape module, but defined # here to minimize the temptation to use it in non-wsgi contexts. def to_wsgi_str(s: bytes) -> str: assert isinstance(s, bytes) return s.decode("latin1") class WSGIContainer(object): r"""Makes a WSGI-compatible application runnable on Tornado's HTTP server. .. warning:: WSGI is a *synchronous* interface, while Tornado's concurrency model is based on single-threaded *asynchronous* execution. Many of Tornado's distinguishing features are not available in WSGI mode, including efficient long-polling and websockets. The primary purpose of `WSGIContainer` is to support both WSGI applications and native Tornado ``RequestHandlers`` in a single process. WSGI-only applications are likely to be better off with a dedicated WSGI server such as ``gunicorn`` or ``uwsgi``. Wrap a WSGI application in a `WSGIContainer` to make it implement the Tornado `.HTTPServer` ``request_callback`` interface. The `WSGIContainer` object can then be passed to classes from the `tornado.routing` module, `tornado.web.FallbackHandler`, or to `.HTTPServer` directly. This class is intended to let other frameworks (Django, Flask, etc) run on the Tornado HTTP server and I/O loop. Realistic usage will be more complicated, but the simplest possible example uses a hand-written WSGI application with `.HTTPServer`:: def simple_app(environ, start_response): status = "200 OK" response_headers = [("Content-type", "text/plain")] start_response(status, response_headers) return [b"Hello world!\n"] async def main(): container = tornado.wsgi.WSGIContainer(simple_app) http_server = tornado.httpserver.HTTPServer(container) http_server.listen(8888) await asyncio.Event().wait() asyncio.run(main()) The recommended pattern is to use the `tornado.routing` module to set up routing rules between your WSGI application and, typically, a `tornado.web.Application`. Alternatively, `tornado.web.Application` can be used as the top-level router and `tornado.web.FallbackHandler` can embed a `WSGIContainer` within it. If the ``executor`` argument is provided, the WSGI application will be executed on that executor. This must be an instance of `concurrent.futures.Executor`, typically a ``ThreadPoolExecutor`` (``ProcessPoolExecutor`` is not supported). If no ``executor`` is given, the application will run on the event loop thread in Tornado 6.3; this will change to use an internal thread pool by default in Tornado 7.0. .. warning:: By default, the WSGI application is executed on the event loop's thread. This limits the server to one request at a time (per process), making it less scalable than most other WSGI servers. It is therefore highly recommended that you pass a ``ThreadPoolExecutor`` when constructing the `WSGIContainer`, after verifying that your application is thread-safe. The default will change to use a ``ThreadPoolExecutor`` in Tornado 7.0. .. versionadded:: 6.3 The ``executor`` parameter. .. deprecated:: 6.3 The default behavior of running the WSGI application on the event loop thread is deprecated and will change in Tornado 7.0 to use a thread pool by default. """ def __init__( self, wsgi_application: "WSGIAppType", executor: Optional[concurrent.futures.Executor] = None, ) -> None: self.wsgi_application = wsgi_application self.executor = dummy_executor if executor is None else executor def __call__(self, request: httputil.HTTPServerRequest) -> None: IOLoop.current().spawn_callback(self.handle_request, request) async def handle_request(self, request: httputil.HTTPServerRequest) -> None: data = {} # type: Dict[str, Any] response = [] # type: List[bytes] def start_response( status: str, headers: List[Tuple[str, str]], exc_info: Optional[ Tuple[ "Optional[Type[BaseException]]", Optional[BaseException], Optional[TracebackType], ] ] = None, ) -> Callable[[bytes], Any]: data["status"] = status data["headers"] = headers return response.append loop = IOLoop.current() app_response = await loop.run_in_executor( self.executor, self.wsgi_application, self.environ(request), start_response, ) try: app_response_iter = iter(app_response) def next_chunk() -> Optional[bytes]: try: return next(app_response_iter) except StopIteration: # StopIteration is special and is not allowed to pass through # coroutines normally. return None while True: chunk = await loop.run_in_executor(self.executor, next_chunk) if chunk is None: break response.append(chunk) finally: if hasattr(app_response, "close"): app_response.close() # type: ignore body = b"".join(response) if not data: raise Exception("WSGI app did not call start_response") status_code_str, reason = data["status"].split(" ", 1) status_code = int(status_code_str) headers = data["headers"] # type: List[Tuple[str, str]] header_set = set(k.lower() for (k, v) in headers) body = escape.utf8(body) if status_code != 304: if "content-length" not in header_set: headers.append(("Content-Length", str(len(body)))) if "content-type" not in header_set: headers.append(("Content-Type", "text/html; charset=UTF-8")) if "server" not in header_set: headers.append(("Server", "TornadoServer/%s" % tornado.version)) start_line = httputil.ResponseStartLine("HTTP/1.1", status_code, reason) header_obj = httputil.HTTPHeaders() for key, value in headers: header_obj.add(key, value) assert request.connection is not None request.connection.write_headers(start_line, header_obj, chunk=body) request.connection.finish() self._log(status_code, request) def environ(self, request: httputil.HTTPServerRequest) -> Dict[Text, Any]: """Converts a `tornado.httputil.HTTPServerRequest` to a WSGI environment. .. versionchanged:: 6.3 No longer a static method. """ hostport = request.host.split(":") if len(hostport) == 2: host = hostport[0] port = int(hostport[1]) else: host = request.host port = 443 if request.protocol == "https" else 80 environ = { "REQUEST_METHOD": request.method, "SCRIPT_NAME": "", "PATH_INFO": to_wsgi_str( escape.url_unescape(request.path, encoding=None, plus=False) ), "QUERY_STRING": request.query, "REMOTE_ADDR": request.remote_ip, "SERVER_NAME": host, "SERVER_PORT": str(port), "SERVER_PROTOCOL": request.version, "wsgi.version": (1, 0), "wsgi.url_scheme": request.protocol, "wsgi.input": BytesIO(escape.utf8(request.body)), "wsgi.errors": sys.stderr, "wsgi.multithread": self.executor is not dummy_executor, "wsgi.multiprocess": True, "wsgi.run_once": False, } if "Content-Type" in request.headers: environ["CONTENT_TYPE"] = request.headers.pop("Content-Type") if "Content-Length" in request.headers: environ["CONTENT_LENGTH"] = request.headers.pop("Content-Length") for key, value in request.headers.items(): environ["HTTP_" + key.replace("-", "_").upper()] = value return environ def _log(self, status_code: int, request: httputil.HTTPServerRequest) -> None: if status_code < 400: log_method = access_log.info elif status_code < 500: log_method = access_log.warning else: log_method = access_log.error request_time = 1000.0 * request.request_time() assert request.method is not None assert request.uri is not None summary = ( request.method # type: ignore[operator] + " " + request.uri + " (" + request.remote_ip + ")" ) log_method("%d %s %.2fms", status_code, summary, request_time) HTTPRequest = httputil.HTTPServerRequest
| ver. 1.4 |
Github
|
.
| PHP 8.2.28 | Generation time: 0.02 |
proxy
|
phpinfo
|
Settings