U
    d"                     @   s   d Z ddlZddlmZ ddlZddlmZ ddlmZ ddlmZ ddl	m
Z
mZmZmZmZmZmZ ddlmZ ddl	Z	e	jrdd	l	mZ dd
lmZ eedddZG dd deZejZdS )a  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.

    N)BytesIO)escape)httputil)
access_log)ListTupleOptionalCallableAnyDictText)TracebackType)Type)WSGIApplication)sreturnc                 C   s   t | tst| dS )Nlatin1)
isinstancebytesAssertionErrordecode)r    r   0/tmp/pip-unpacked-wheel-fekwu36z/tornado/wsgi.pyto_wsgi_str3   s    r   c                   @   sd   e Zd ZdZdddddZejdddd	Zeeje	e
ef dd
dZeejddddZdS )WSGIContainera  Makes a WSGI-compatible function runnable on Tornado's HTTP server.

    .. warning::

       WSGI is a *synchronous* interface, while Tornado's concurrency model
       is based on single-threaded asynchronous execution.  This means that
       running a WSGI app with Tornado's `WSGIContainer` is *less scalable*
       than running the same app in a multi-threaded WSGI server like
       ``gunicorn`` or ``uwsgi``.  Use `WSGIContainer` only when there are
       benefits to combining Tornado and WSGI in the same process that
       outweigh the reduced scalability.

    Wrap a WSGI function in a `WSGIContainer` and pass it to `.HTTPServer` to
    run it. For example::

        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())

    This class is intended to let other frameworks (Django, web.py, etc)
    run on the Tornado HTTP server and I/O loop.

    The `tornado.web.FallbackHandler` class is often useful for mixing
    Tornado and WSGI apps in the same server.  See
    https://github.com/bdarnell/django-tornado-demo for a complete example.
    WSGIAppTypeN)wsgi_applicationr   c                 C   s
   || _ d S N)r   )selfr   r   r   r   __init__^   s    zWSGIContainer.__init__)requestr   c              	      s  i  g dt ttt t f  ttdtt tt f  ttgtf d fdd}| 	t
||}z| d}W 5 t|dr|  X  std d d	d
\}}t|} d }tdd |D }	t|}|dkrd|	kr|dt t|f d|	kr|d d|	kr8|ddtj f td||}
t }|D ]\}}||| qR|jd k	szt|jj |
||d |j!  | "|| d S )NzOptional[Type[BaseException]])statusheadersexc_infor   c                    s   |  d< | d< j S )Nr!   r"   )append)r!   r"   r#   dataresponser   r   start_responsee   s    z.WSGIContainer.__call__.<locals>.start_responseclose    z$WSGI app did not call start_responser!       r"   c                 s   s   | ]\}}|  V  qd S r   )lower).0kvr   r   r   	<genexpr>   s     z)WSGIContainer.__call__.<locals>.<genexpr>i0  zcontent-lengthContent-Lengthzcontent-type)Content-Typeztext/html; charset=UTF-8serverServerzTornadoServer/%szHTTP/1.1)chunk)N)#strr   r   r   BaseExceptionr   r	   r   r
   r   r   environhasattrr)   extendjoin	Exceptionsplitintsetr   utf8r$   lentornadoversionr   ZResponseStartLineZHTTPHeadersadd
connectionr   Zwrite_headersfinish_log)r   r    r(   Zapp_responsebodyZstatus_code_strreasonstatus_coder"   Z
header_setZ
start_lineZ
header_objkeyvaluer   r%   r   __call__a   s^      









zWSGIContainer.__call__c                 C   s   | j d}t|dkr.|d }t|d }n| j }| jdkrBdnd}| jdttj| j	d	d
d| j
| j|t|| jd| jtt| jtjd
dd
d}d| jkr| jd|d< d| jkr| jd|d< | j D ] \}}||d|dd  < q|S )zFConverts a `tornado.httputil.HTTPServerRequest` to a WSGI environment.:   r   r,   httpsi  P    NF)encodingplus)r,   r   T)REQUEST_METHODZSCRIPT_NAMEZ	PATH_INFOQUERY_STRINGZREMOTE_ADDRZSERVER_NAMEZSERVER_PORTZSERVER_PROTOCOLzwsgi.versionzwsgi.url_schemez
wsgi.inputzwsgi.errorszwsgi.multithreadzwsgi.multiprocesszwsgi.run_oncer3   CONTENT_TYPEr2   CONTENT_LENGTHZHTTP_-_)hostr>   rB   r?   protocolmethodr   r   Zurl_unescapepathquery	remote_ipr7   rD   r   rA   rI   sysstderrr"   popitemsreplaceupper)r    hostportr\   portr9   rL   rM   r   r   r   r9      s>    

zWSGIContainer.environ)rK   r    r   c                 C   s~   |dk rt j}n|dk r t j}nt j}d|  }|jd k	s@t|jd k	sNt|jd |j d |j d }|d||| d S )Ni  i  g     @@r+   z ()z%d %s %.2fms)	r   infowarningerrorrequest_timer^   r   urira   )r   rK   r    Z
log_methodrn   summaryr   r   r   rH      s*    zWSGIContainer._log)__name__
__module____qualname____doc__r   r   HTTPServerRequestrN   staticmethodr   r   r
   r9   r?   rH   r   r   r   r   r   8   s   %5$r   )rt   rb   ior   rC   r   r   Ztornado.logr   typingr   r   r   r	   r
   r   r   typesr   TYPE_CHECKINGr   Z_typeshed.wsgir   r   r   r7   r   objectr   ru   ZHTTPRequestr   r   r   r   <module>   s    $ 