B
    `(                 @   sf   d Z ddlmZmZ ddlmZ ddlmZ dgZG dd de	Z
G dd de	ZG d	d
 d
e	ZdS )z
Decorators to wrap functions to make them WSGI applications.

The main decorator :class:`wsgify` turns a function into a WSGI
application (while also allowing normal calling of the method with an
instantiated request).
    )bytes_	text_type)Request)HTTPExceptionwsgifyc               @   s   e Zd ZdZeZdddZdd Zddd	Zd
d Z	dd Z
dddZdd Zdd ZdddZedd Zed ddZdd ZdS )!r   a  Turns a request-taking, response-returning function into a WSGI
    app

    You can use this like::

        @wsgify
        def myfunc(req):
            return webob.Response('hey there')

    With that ``myfunc`` will be a WSGI application, callable like
    ``app_iter = myfunc(environ, start_response)``.  You can also call
    it like normal, e.g., ``resp = myfunc(req)``.  (You can also wrap
    methods, like ``def myfunc(self, req)``.)

    If you raise exceptions from :mod:`webob.exc` they will be turned
    into WSGI responses.

    There are also several parameters you can use to customize the
    decorator.  Most notably, you can use a :class:`webob.Request`
    subclass, like::

        class MyRequest(webob.Request):
            @property
            def is_local(self):
                return self.remote_addr == '127.0.0.1'
        @wsgify(RequestClass=MyRequest)
        def myfunc(req):
            if req.is_local:
                return Response('hi!')
            else:
                raise webob.exc.HTTPForbidden

    Another customization you can add is to add `args` (positional
    arguments) or `kwargs` (of course, keyword arguments).  While
    generally not that useful, you can use this to create multiple
    WSGI apps from one function, like::

        import simplejson
        def serve_json(req, json_obj):
            return Response(json.dumps(json_obj),
                            content_type='application/json')

        serve_ob1 = wsgify(serve_json, args=(ob1,))
        serve_ob2 = wsgify(serve_json, args=(ob2,))

    You can return several things from a function:

    * A :class:`webob.Response` object (or subclass)
    * *Any* WSGI application
    * None, and then ``req.response`` will be used (a pre-instantiated
      Response object)
    * A string, which will be written to ``req.response`` and then that
      response will be used.
    * Raise an exception from :mod:`webob.exc`

    Also see :func:`wsgify.middleware` for a way to make middleware.

    You can also subclass this decorator; the most useful things to do
    in a subclass would be to change `RequestClass` or override
    `call_func` (e.g., to add ``req.urlvars`` as keyword arguments to
    the function).
    N c             C   sD   || _ |d k	r|| jk	r|| _t|| _|d kr4i }|| _|| _d S )N)funcRequestClasstupleargskwargsmiddleware_wraps)selfr   r	   r   r   r   r   r   Q/home/kop/projects/devel/pgwui/test_venv/lib/python3.7/site-packages/webob/dec.py__init__U   s    

zwsgify.__init__c             C   s   d| j jt| | jf S )Nz<%s at %s wrapping %r>)	__class____name__idr   )r   r   r   r   __repr__a   s    zwsgify.__repr__c             C   s(   t | jdr | | j||S | S d S )N__get__)hasattrr   cloner   )r   objtyper   r   r   r   e   s    zwsgify.__get__c       
   
   O   sX  | j }|dkr4|s|r&td| jj |}| |S t|tr2t|dksP|r^td| j  |}|d }| |}|	 |_
y&| dd\}}| j|f||}W n& tk
r } z|}W dd}~X Y nX |dkr|j
}t|trt||j}t|tr|}	|j
}||	 ||j
k	r(|j
|}|||S | ||\}}| j|f||S dS )z1Call this as a WSGI application or with a requestNz<Unbound %s can only be called with the function it will wrap   z1Calling %r as a WSGI app with the wrong signaturer   )r   	TypeErrorr   r   r   
isinstancedictlenr	   ZResponseClassresponse_prepare_args	call_funcr   r   r   charsetbyteswritemerge_cookies)
r   reqr   kwr   environZstart_responserespexcbodyr   r   r   __call__l   sF    






zwsgify.__call__c             K   s$   | dd | jj|f|}| |S )a5  Run a GET request on this application, returning a Response.

        This creates a request object using the given URL, and any
        other keyword arguments are set on the request object (e.g.,
        ``last_modified=datetime.now()``).

        ::

            resp = myapp.get('/article?id=10')
        methodGET)
setdefaultr	   blank)r   urlr'   r&   r   r   r   get   s    z
wsgify.getc             K   s,   | dd | jj|fd|i|}| |S )a  Run a POST request on this application, returning a Response.

        The second argument (`POST`) can be the request body (a
        string), or a dictionary or list of two-tuples, that give the
        POST body.

        ::

            resp = myapp.post('/article/new',
                              dict(title='My Day',
                                   content='I ate a sandwich'))
        r-   POST)r/   r	   r0   )r   r1   r3   r'   r&   r   r   r   post   s    zwsgify.postc             K   s   | j j|f|}| |S )zRun a request on this application, returning a Response.

        This can be used for DELETE, PUT, etc requests.  E.g.::

            resp = myapp.request('/article/1', method='PUT', body='New article')
        )r	   r0   )r   r1   r'   r&   r   r   r   request   s    zwsgify.requestc             O   s   | j |f||S )zdCall the wrapped function; override this in a subclass to
        change how the function is called.)r   )r   r&   r   r   r   r   r   r!      s    zwsgify.call_funcc             K   sb   i }|dk	r||d< | j | jj k	r,| j |d< | jr<| j|d< | jrL| j|d< || | jf |S )zVCreates a copy/clone of this object, but with some
        parameters rebound
        Nr   r	   r   r   )r	   r   r   r   update)r   r   r'   r   r   r   r   r      s    



zwsgify.clonec             C   s   | j S )N)r   )r   r   r   r   undecorated   s    zwsgify.undecoratedc             K   s6   |dkrt | ||S |dkr(t| ||S | |||dS )a  Creates middleware

        Use this like::

            @wsgify.middleware
            def restrict_ip(req, app, ips):
                if req.remote_addr not in ips:
                    raise webob.exc.HTTPForbidden('Bad IP: %s' % req.remote_addr)
                return app

            @wsgify
            def app(req):
                return 'hi'

            wrapped = restrict_ip(app, ips=['127.0.0.1'])

        Or as a decorator::

            @restrict_ip(ips=['127.0.0.1'])
            @wsgify
            def wrapped_app(req):
                return 'hi'

        Or if you want to write output-rewriting middleware::

            @wsgify.middleware
            def all_caps(req, app):
                resp = req.get_response(app)
                resp.body = resp.body.upper()
                return resp

            wrapped = all_caps(app)

        Note that you must call ``req.get_response(app)`` to get a WebOb
        response object.  If you are not modifying the output, you can just
        return the app.

        As you can see, this method doesn't actually create an application, but
        creates "middleware" that can be bound to an application, along with
        "configuration" (that is, any other keyword arguments you pass when
        binding the application).

        N)r   r   )_UnboundMiddleware_MiddlewareFactory)clsZmiddle_funcappr'   r   r   r   
middleware   s
    -zwsgify.middlewarec             C   s.   |p| j }|p| j}| jr&| jf| }||fS )N)r   r   r   )r   r   r   r   r   r   r      s
    

zwsgify._prepare_args)NNr   NN)N)N)N)NN)r   
__module____qualname____doc__r   r	   r   r   r   r,   r2   r4   r5   r!   r   propertyr7   classmethodr<   r    r   r   r   r   r      s    > 

(


2c               @   s*   e Zd ZdZdd Zdd Zd	ddZdS )
r8   zA `wsgify.middleware` invocation that has not yet wrapped a
    middleware function; the intermediate object when you do
    something like ``@wsgify.middleware(RequestClass=Foo)``
    c             C   s   || _ || _|| _d S )N)wrapper_classr;   r'   )r   rB   r;   r'   r   r   r   r     s    z_UnboundMiddleware.__init__c             C   s   d| j jt| | jf S )Nz<%s at %s wrapping %r>)r   r   r   r;   )r   r   r   r   r     s    z_UnboundMiddleware.__repr__Nc             C   s(   |d kr| j }| jj|fd|i| jS )Nr;   )r;   rB   r<   r'   )r   r   r;   r   r   r   r,   !  s    z_UnboundMiddleware.__call__)N)r   r=   r>   r?   r   r   r,   r   r   r   r   r8     s   r8   c               @   s*   e Zd ZdZdd Zdd Zd	ddZdS )
r9   zRA middleware that has not yet been bound to an application or
    configured.
    c             C   s   || _ || _|| _d S )N)rB   r<   r'   )r   rB   r<   r'   r   r   r   r   +  s    z_MiddlewareFactory.__init__c             C   s   d| j jt| | jf S )Nz<%s at %s wrapping %r>)r   r   r   r<   )r   r   r   r   r   0  s    z_MiddlewareFactory.__repr__Nc             K   s(   | j  }|| | jj| j|f|S )N)r'   copyr6   rB   r<   )r   r;   configr'   r   r   r   r,   4  s    

z_MiddlewareFactory.__call__)N)r   r=   r>   r?   r   r   r,   r   r   r   r   r9   &  s   r9   N)r?   Zwebob.compatr   r   Zwebob.requestr   Z	webob.excr   __all__objectr   r8   r9   r   r   r   r   <module>   s     