Exemple #1
0
    def __call__(self, request, c):
        """:meth:`pluggdapps.web.interfaces.IHTTPView.__call__` interface
        method.
        """
        resp = request.response
        path = request.uriparts["path"].lstrip("/") or resp.webapp["index_page"]
        if path == "favicon.ico":
            path = self.webapp["favicon"]
        c["rootloc"] = self.view.get("rootloc", self.webapp["rootloc"])
        docfile = join(c["rootloc"], path)

        if docfile and isfile(docfile):
            # Collect information about the document, for response.
            resp.set_status(b"200")
            stat = os.stat(docfile)
            (typ, enc) = mimetypes.guess_type(docfile)
            if typ:
                resp.media_type = typ
            if enc:
                resp.content_coding = enc
            # Populate the context
            c.etag["body"] = open(docfile, "rb").read()
            c["last_modified"] = h.http_fromdate(stat.st_mtime)
            cc = ("public,max-age=%s" % str(self["max_age"])).encode("utf-8")
            resp.set_header("cache_control", cc)
            # Send Response
            resp.write(c["body"])
            resp.flush(finishing=True)
        else:
            resp.pa.logdebug("Not found %r" % docfile)
            resp.set_status(b"404")
            resp.flush(finishing=True)
Exemple #2
0
    def __call__( self, request, c ):
        """:meth:`pluggdapps.web.interfaces.IHTTPView.__call__` interface
        method.
        """
        resp = request.response
        assetpath = h.abspath_from_asset_spec( self.view['rootloc'] )
        docfile = join( assetpath, request.matchdict['path'] )

        if docfile and isfile( docfile ) :
            # Collect information about the document, for response.
            resp.set_status( b'200' )
            stat = os.stat( docfile )
            (typ, enc) = mimetypes.guess_type( docfile )
            if typ :
                resp.media_type = typ
            if enc :
                resp.content_coding = enc
            # Populate the context
            c.etag['body'] = open( docfile, 'rb' ).read()
            c['last_modified'] = h.http_fromdate( stat.st_mtime )
            cc = ('public,max-age=%s' % str(self['max_age']) ).encode('utf-8')
            resp.set_header( 'cache_control', cc )
            # Send Response
            resp.write( c['body'] )
            resp.flush( finishing=True )
        else :
            resp.pa.logwarn( "Not found %r" % docfile )
            resp.set_status( b'404' )
            resp.flush( finishing=True )
    def __call__(self, request, c):
        """:meth:`pluggdapps.web.interfaces.IHTTPView.__call__` interface
        method.
        """
        resp = request.response
        path = request.uriparts['path'].lstrip(
            '/') or resp.webapp['index_page']
        if path == 'favicon.ico':
            path = self.webapp['favicon']
        c['rootloc'] = self.view.get('rootloc', self.webapp['rootloc'])
        docfile = join(c['rootloc'], path)

        if docfile and isfile(docfile):
            # Collect information about the document, for response.
            resp.set_status(b'200')
            stat = os.stat(docfile)
            (typ, enc) = mimetypes.guess_type(docfile)
            if typ:
                resp.media_type = typ
            if enc:
                resp.content_coding = enc
            # Populate the context
            c.etag['body'] = open(docfile, 'rb').read()
            c['last_modified'] = h.http_fromdate(stat.st_mtime)
            cc = ('public,max-age=%s' % str(self['max_age'])).encode('utf-8')
            resp.set_header('cache_control', cc)
            # Send Response
            resp.write(c['body'])
            resp.flush(finishing=True)
        else:
            resp.pa.logdebug("Not found %r" % docfile)
            resp.set_status(b'404')
            resp.flush(finishing=True)
    def transform(self, request, data, finishing=False):
        """:meth:`pluggdapps.web.interfaces.IHTTPOutBound.transform`
        interface method."""
        resp = request.response
        c = resp.context
        if resp.isstarted() == False:
            resp.set_header('date', h.http_fromdate(time.time()))
            resp.set_header('server', resp.httpconn.product)

            # Content negotiated headers
            if resp.media_type:
                mt = resp.media_type
                if resp.charset:
                    mt = '%s;charset=%s' % (mt, resp.charset)
                resp.set_header('content_type', mt)
            if resp.language:
                resp.set_header('content_language', resp.language)
            if resp.content_coding:
                resp.set_header('content_encoding', resp.content_coding)

            # For HTTP/1.1 connection can be kept alive across multiple request
            # and response.
            if request.supports_http_1_1():
                connection = h.parse_connection(
                    request.headers.get("connection", b''))
                if b'keep-alive' in connection:
                    resp.set_header("connection", b"Keep-Alive")

            # Update Last-modified header field and If-* request headers
            last_modified = resp.context.get('last_modified', '')
            if last_modified:
                resp.set_header('last_modified', last_modified)

            if resp.ischunked() == False and last_modified:
                ims = request.headers.get('if_modified_since', b'')
                iums = request.headers.get('if_umodified_since', b'')
                ims = ims and h.parse_date(ims.strip())
                iums = iums and h.parse_date(iums.strip())
                last_modified = h.parse_date(last_modified)
                if ((ims and ims >= last_modified)
                        or (iums and iums < last_modified)):
                    resp.set_status(b'304')
                    return b''

            # If etag is available from context, compute and subsequently
            # clear them.
            # IMPORANT : Do not change this sequence of last-modified and etag
            etag = c.etag.hashout(prefix="view-", joinwith=c.pop('etag', ''))
            etag = ('"%s"' % etag).encode('utf-8') if etag else etag
            c.etag.clear()
            if (resp.ischunked() == False and resp.statuscode == b'200'
                    and request.method in (b'GET', b'HEAD') and etag):
                resp.set_header("etag", etag)

        return data
Exemple #5
0
    def transform( self, request, data, finishing=False ): 
        """:meth:`pluggdapps.web.interfaces.IHTTPOutBound.transform`
        interface method."""
        resp = request.response
        c = resp.context
        if resp.isstarted() == False :
            resp.set_header( 'date', h.http_fromdate( time.time() ))
            resp.set_header( 'server', resp.httpconn.product )

            # Content negotiated headers
            if resp.media_type :
                mt = resp.media_type
                if resp.charset :
                    mt = '%s;charset=%s' % (mt, resp.charset)
                resp.set_header( 'content_type', mt ) 
            if resp.language :
                resp.set_header( 'content_language', resp.language )
            if resp.content_coding :
                resp.set_header( 'content_encoding', resp.content_coding )

            # For HTTP/1.1 connection can be kept alive across multiple request
            # and response.
            if request.supports_http_1_1() :
                connection = h.parse_connection(
                                    request.headers.get( "connection", b'' ))
                if b'keep-alive' in connection :
                    resp.set_header( "connection", b"Keep-Alive" )

            # Update Last-modified header field and If-* request headers
            last_modified = resp.context.get( 'last_modified', '' )
            if last_modified :
                resp.set_header( 'last_modified', last_modified )

            if resp.ischunked() == False and last_modified :
                ims = request.headers.get( 'if_modified_since', b'' )
                iums = request.headers.get( 'if_umodified_since', b'' )
                ims = ims and h.parse_date( ims.strip() )
                iums = iums and h.parse_date( iums.strip() )
                last_modified = h.parse_date( last_modified )
                if ( (ims and ims >= last_modified) or
                     (iums and iums < last_modified) ) :
                    resp.set_status( b'304' )
                    return b''

            # If etag is available from context, compute and subsequently
            # clear them.
            # IMPORANT : Do not change this sequence of last-modified and etag
            etag = c.etag.hashout( prefix="view-", joinwith=c.pop('etag','') )
            etag = ('"%s"' % etag).encode( 'utf-8' ) if etag else etag
            c.etag.clear()
            if ( resp.ischunked() == False and resp.statuscode == b'200' and
                 request.method in (b'GET', b'HEAD') and etag ) :
                resp.set_header( "etag", etag )

        return data
Exemple #6
0
    def collectException(self, request, etype, value, tb, limit=None):
        """``collectException( request, *sys.exc_info() )`` will return an
        instance of :class:`CollectedException`. Attibutes of this object can
        be used to render traceback.
    
        Use like::

          try:
              blah blah
          except:
              exc_data = plugin.collectException(*sys.exc_info())
        """
        # The next line provides a way to detect recursion.
        __exception_formatter__ = 1
        limit = limit or self['limit'] or getattr(sys, 'tracebacklimit', None)
        frames, ident_data, extra_data = [], [], {}

        # Collect all the frames in sys.exc_info's trace-back.
        n, tbs = 0, []
        while tb is not None and (limit is None or n < limit):
            if tb.tb_frame.f_locals.get('__exception_formatter__'):
                # Stop recursion. @@: should make a fake ExceptionFrame
                frames.append('(Recursive formatException() stopped)\n')
                break
            ef = ExceptionFrame(**self.collectFrame(request, tb, extra_data))
            if bool(ef.traceback_hide) == False and ef.filename:
                frames.append(ef)
                tbs.append(tb)
            n += 1
            tb = tb.tb_next

        if hasattr(value, 'filename'):
            tb = (value.filename, value.lineno)
        elif value.__traceback__ not in tbs:
            tb = value.__traceback__
        else:
            tb = None

        if tb:
            ef = ExceptionFrame(**self.collectFrame(request, tb, extra_data))
            if bool(ef.traceback_hide) == False and ef.filename:
                frames.append(ef)

        decorators = []
        for frame in frames:
            decorators.append(frame.traceback_decorator)
            ident_data.extend([frame.modname or '?', frame.name or '?'])

        ident_data.append(str(etype))
        ident = hash_identifier(' '.join(ident_data),
                                length=5,
                                upper=True,
                                prefix='E-')

        for decorator in filter(None, decorators):
            frames = decorator(frames)

        kwargs = {
            'frames':
            frames,
            'exception_formatted':
            '\n'.join(traceback.format_exception_only(etype, value)),
            'exception_value':
            str(value),
            'exception_type':
            etype.__name__,
            'identification_code':
            ident,
            'date':
            h.http_fromdate(time.time()),
            'extra_data':
            extra_data,
        }

        result = CollectedException(**kwargs)
        if etype is ImportError:
            extra_data[('important', 'sys.path')] = [sys.path]

        return result
Exemple #7
0
    def collectException(self, request, etype, value, tb, limit=None):
        """``collectException( request, *sys.exc_info() )`` will return an
        instance of :class:`CollectedException`. Attibutes of this object can
        be used to render traceback.
    
        Use like::

          try:
              blah blah
          except:
              exc_data = plugin.collectException(*sys.exc_info())
        """
        # The next line provides a way to detect recursion.
        __exception_formatter__ = 1
        limit = limit or self["limit"] or getattr(sys, "tracebacklimit", None)
        frames, ident_data, extra_data = [], [], {}

        # Collect all the frames in sys.exc_info's trace-back.
        n, tbs = 0, []
        while tb is not None and (limit is None or n < limit):
            if tb.tb_frame.f_locals.get("__exception_formatter__"):
                # Stop recursion. @@: should make a fake ExceptionFrame
                frames.append("(Recursive formatException() stopped)\n")
                break
            ef = ExceptionFrame(**self.collectFrame(request, tb, extra_data))
            if bool(ef.traceback_hide) == False and ef.filename:
                frames.append(ef)
                tbs.append(tb)
            n += 1
            tb = tb.tb_next

        if hasattr(value, "filename"):
            tb = (value.filename, value.lineno)
        elif value.__traceback__ not in tbs:
            tb = value.__traceback__
        else:
            tb = None

        if tb:
            ef = ExceptionFrame(**self.collectFrame(request, tb, extra_data))
            if bool(ef.traceback_hide) == False and ef.filename:
                frames.append(ef)

        decorators = []
        for frame in frames:
            decorators.append(frame.traceback_decorator)
            ident_data.extend([frame.modname or "?", frame.name or "?"])

        ident_data.append(str(etype))
        ident = hash_identifier(" ".join(ident_data), length=5, upper=True, prefix="E-")

        for decorator in filter(None, decorators):
            frames = decorator(frames)

        kwargs = {
            "frames": frames,
            "exception_formatted": "\n".join(traceback.format_exception_only(etype, value)),
            "exception_value": str(value),
            "exception_type": etype.__name__,
            "identification_code": ident,
            "date": h.http_fromdate(time.time()),
            "extra_data": extra_data,
        }

        result = CollectedException(**kwargs)
        if etype is ImportError:
            extra_data[("important", "sys.path")] = [sys.path]

        return result