Exemple #1
0
    def handle( self, body=None, chunk=None, trailers=None ):
        """:meth:`pluggdapps.web.interfaces.IHTTPRequest.handle`
        interface method."""
        self.cookies = self.cookie.parse_cookies( self.headers )

        # In case of `chunked` encoding, check whether this is the last chunk.
        finishing = body or ( chunk and trailers and chunk[0] == 0)

        # Apply IHTTPInBound transformers on this request.
        data = body if body != None else (chunk[2] if chunk else b'')
        for tr in self.webapp.in_transformers :
            data = tr.transform( self, data, finishing=finishing )

        # Update the request plugin with attributes.
        if body :
            self.body = data
        elif chunk :
            self.chunks.append( (chunk[0], chunk[1], data) )
        self.trailers = trailers or self.trailers

        # Process POST and PUT request interpreting multipart content.
        if self.method in ( b'POST', b'PUT' ) :
            self.postparams, self.multiparts = \
                    h.parse_formbody( self.content_type, self.body )
            self.postparams = { h.strof(k) : list( map( h.strof, vs )) 
                                for k,vs in self.postparams.items() }
            [ self.params.setdefault( name, [] ).extend( value )
              for name, value in self.postparams.items() ]
            [ self.params.setdefault( name, [] ).extend( value )
              for name, value in self.multiparts.items() ]
            [ self.files.setdefault( name, [] 
                                   ).extend( (f['filename'], f['value'] ) )
              for name, value in self.multiparts.items() ]
Exemple #2
0
    def __init__( self, httpconn, method, uri, uriparts, version, headers ):
        """:meth:`pluggdapps.web.interfaces.IHTTPRequest.__init__` interface
        method."""
        self.router = self.cookie = None
        self.response = self.session = None

        self.httpconn = httpconn
        self.method, self.uri, self.uriparts, self.version = \
                method, uri, uriparts, version
        self.headers = headers

        # Initialize request handler attributes, these attributes will be
        # valid only after a call to handle() method.
        self.body = b''
        self.chunks = []
        self.trailers = {}
        self.cookies = {}

        # Only in case of POST and PUT method.
        self.postparams = {}
        self.multiparts = {}
        self.files = {}

        # Initialize
        self.params = {}
        self.getparams = { h.strof(k) : list( map( h.strof, vs )) 
                           for k,vs in self.uriparts['query'].items() }
        self.params.update( self.getparams )

        self.content_type = \
                h.parse_content_type( headers.get( 'content_type', None ))

        self.view = None
        self.receivedat = time.time()
        self.finishedat = None
    def _match_predicates( self, request, matches ):
        """Filter matching views, whose pattern matches with request-url,
        based on view-predicates. 
        
        TODO: More predicates to be added."""
        variants = []
        for viewd in matches :
            x = True
            if viewd['method'] != None :
                x = x and viewd['method'] == h.strof( request.method )
            variants.append( viewd ) if x else None

        return variants
    def handle(self, body=None, chunk=None, trailers=None):
        """:meth:`pluggdapps.web.interfaces.IHTTPRequest.handle`
        interface method."""
        self.cookies = self.cookie.parse_cookies(self.headers)

        # In case of `chunked` encoding, check whether this is the last chunk.
        finishing = body or (chunk and trailers and chunk[0] == 0)

        # Apply IHTTPInBound transformers on this request.
        data = body if body != None else (chunk[2] if chunk else b'')
        for tr in self.webapp.in_transformers:
            data = tr.transform(self, data, finishing=finishing)

        # Update the request plugin with attributes.
        if body:
            self.body = data
        elif chunk:
            self.chunks.append((chunk[0], chunk[1], data))
        self.trailers = trailers or self.trailers

        # Process POST and PUT request interpreting multipart content.
        if self.method in (b'POST', b'PUT'):
            self.postparams, self.multiparts = \
                    h.parse_formbody( self.content_type, self.body )
            self.postparams = {
                h.strof(k): list(map(h.strof, vs))
                for k, vs in self.postparams.items()
            }
            [
                self.params.setdefault(name, []).extend(value)
                for name, value in self.postparams.items()
            ]
            [
                self.params.setdefault(name, []).extend(value)
                for name, value in self.multiparts.items()
            ]
            [
                self.files.setdefault(name, []).extend(
                    (f['filename'], f['value']))
                for name, value in self.multiparts.items()
            ]
    def __init__(self, httpconn, method, uri, uriparts, version, headers):
        """:meth:`pluggdapps.web.interfaces.IHTTPRequest.__init__` interface
        method."""
        self.router = self.cookie = None
        self.response = self.session = None

        self.httpconn = httpconn
        self.method, self.uri, self.uriparts, self.version = \
                method, uri, uriparts, version
        self.headers = headers

        # Initialize request handler attributes, these attributes will be
        # valid only after a call to handle() method.
        self.body = b''
        self.chunks = []
        self.trailers = {}
        self.cookies = {}

        # Only in case of POST and PUT method.
        self.postparams = {}
        self.multiparts = {}
        self.files = {}

        # Initialize
        self.params = {}
        self.getparams = {
            h.strof(k): list(map(h.strof, vs))
            for k, vs in self.uriparts['query'].items()
        }
        self.params.update(self.getparams)

        self.content_type = \
                h.parse_content_type( headers.get( 'content_type', None ))

        self.view = None
        self.receivedat = time.time()
        self.finishedat = None
    def add_view( self, name, pattern, **kwargs ):
        """Add a router mapping rule.
        
        ``name``,
            The name of the route. This attribute is required and it must be
            unique among all defined routes in a given web-application.

        ``pattern``,
            The pattern of the route. This argument is required. If pattern
            doesn't match the current URL, route matching continues.

        For EG,

        .. code-block:: python
            :linenos:

            self.add_view( 'article', 'blog/{year}/{month}/{date}' )


        Optional key-word arguments,

        ``view``,
            A plugin name or plugin instance implementing :class:`IHTTPView`
            interface, or just a plain python callable or a string that
            imports a callable object. What ever the case, please do go 
            through the :class:`IHTTPView` interface specification before 
            authoring a view-callable.

        ``resource``,
            A plugin name or plugin instance implementing
            :class:`IHTTPResource` interface, or just a plain python callable.
            What ever the case, please do go through the :class:`IHTTPResource`
            interface specification before authoring a resource-callable.

        ``attr``,
            If view-callable is a method on ``view`` object then supply this
            argument with a valid method name.

        ``method``,
            Request predicate. HTTP-method as byte string to be matched with
            incoming request.

        ``media_type``,
            Request predicate. Media type/subtype string specifying the
            resource variant. If unspecified, will be automatically detected
            using heuristics.

        ``language``,
            Request predicate. Language-range string specifying the resource
            variant. If unspecified, assumes webapp['language'] from
            configuration settings.

        ``charset``,
            Request predicate. Charset string specifying the resource variant.
            If unspecified, assumes webapp['encoding'] from configuration
            settings.

        ``content_coding``,
            Comma separated list of content coding that will be applied, in
            the same order as given, on the resource variant. Defaults to 
            `identity`.

        ``cache_control``,
            Cache-Control response header value to be used for the resource's
            variant.

        ``rootloc``,
            To add views for static files, use this attribute. Specifies the
            root location where static files are located. Note that when using
            this option, ``pattern`` argument must end with ``*path``.

        ``media_type``, ``language``, ``content_coding`` and ``charset``
        kwargs, if supplied, will be used during content negotiation.
        """
        # Positional arguments.
        self.views[ name ] = view = {}
        view['name'] = name
        view['pattern'] = pattern
        regex, tmpl, redict = self._compile_pattern( pattern )
        view['compiled_pattern'] = re.compile( regex )
        view['path_template'] = tmpl
        view['match_segments'] = redict

        # Supported key-word arguments
        view['view'] = kwargs.pop( 'view', None )
        view['resource'] = kwargs.pop( 'resource', None )
        view['attr'] = kwargs.pop( 'attr', None )
        view['method'] = h.strof( kwargs.pop( 'method', None ))
        # Content Negotiation attributes
        view['media_type']=kwargs.pop('media_type', 'application/octet-stream')
        view['content_coding'] = kwargs.pop('content_coding',CONTENT_IDENTITY)
        view['language'] = kwargs.pop( 'language', self.webapp['language'] )
        view['charset'] = kwargs.pop( 'charset', self.webapp['encoding'] )
        
        # Content Negotiation attributes
        view.update( kwargs )
        self.viewlist.append( (name, view) )