def __init__(self, exc_type, exc_value, tb):
        self.lineno = tb.tb_lineno
        self.function_name = tb.tb_frame.f_code.co_name
        self.locals = tb.tb_frame.f_locals
        self.globals = tb.tb_frame.f_globals

        fn = inspect.getsourcefile(tb) or inspect.getfile(tb)
        if fn[-4:] in ('.pyo', '.pyc'):
            fn = fn[:-1]
        # if it's a file on the file system resolve the real filename.
        if os.path.isfile(fn):
            fn = os.path.realpath(fn)
        self.filename = to_unicode(fn, get_filesystem_encoding())
        self.module = self.globals.get('__name__')
        self.loader = self.globals.get('__loader__')
        self.code = tb.tb_frame.f_code

        # support for paste's traceback extensions
        self.hide = self.locals.get('__traceback_hide__', False)
        info = self.locals.get('__traceback_info__')
        if info is not None:
            try:
                info = text_type(info)
            except UnicodeError:
                info = str(info).decode('utf-8', 'replace')
        self.info = info
Esempio n. 2
0
    def __init__(self, exc_type, exc_value, tb):
        self.lineno = tb.tb_lineno
        self.function_name = tb.tb_frame.f_code.co_name
        self.locals = tb.tb_frame.f_locals
        self.globals = tb.tb_frame.f_globals

        fn = inspect.getsourcefile(tb) or inspect.getfile(tb)
        if fn[-4:] in ('.pyo', '.pyc'):
            fn = fn[:-1]
        # if it's a file on the file system resolve the real filename.
        if os.path.isfile(fn):
            fn = os.path.realpath(fn)
        self.filename = to_unicode(fn, get_filesystem_encoding())
        self.module = self.globals.get('__name__')
        self.loader = self.globals.get('__loader__')
        self.code = tb.tb_frame.f_code

        # support for paste's traceback extensions
        self.hide = self.locals.get('__traceback_hide__', False)
        info = self.locals.get('__traceback_info__')
        if info is not None:
            try:
                info = text_type(info)
            except UnicodeError:
                info = str(info).decode('utf-8', 'replace')
        self.info = info
Esempio n. 3
0
 def get_session_filename(self, sid):
     # out of the box, this should be a strict ASCII subset but
     # you might reconfigure the session object to have a more
     # arbitrary string.
     if isinstance(sid, text_type) and PY2:
         sid = sid.encode(get_filesystem_encoding())
     return path.join(self.path, self.filename_template % sid)
Esempio n. 4
0
 def get_session_filename(self, sid):
     # out of the box, this should be a strict ASCII subset but
     # you might reconfigure the session object to have a more
     # arbitrary string.
     if isinstance(sid, text_type) and PY2:
         sid = sid.encode(get_filesystem_encoding())
     return path.join(self.path, self.filename_template % sid)
Esempio n. 5
0
    def __init__(
        self,
        path=None,
        filename_template="werkzeug_%s.sess",
        session_class=Session,
        renew_missing=False,
        mode=0o644,
    ):
        super(FilesystemSessionStore,
              self).__init__(session_class=session_class)

        if path is None:
            path = tempfile.gettempdir()

        self.path = path

        if isinstance(filename_template, text_type) and PY2:
            filename_template = filename_template.encode(
                get_filesystem_encoding())

        assert not filename_template.endswith(_fs_transaction_suffix), (
            "filename templates may not end with %s" % _fs_transaction_suffix)
        self.filename_template = filename_template
        self.renew_missing = renew_missing
        self.mode = mode
Esempio n. 6
0
 def generate_etag(self, mtime, file_size, real_filename):
     if not isinstance(real_filename, bytes):
         real_filename = real_filename.encode(get_filesystem_encoding())
     return 'wzsdm-%d-%s-%s' % (
         mktime(mtime.timetuple()),
         file_size,
         adler32(real_filename) & 0xffffffff
     )
Esempio n. 7
0
 def generate_etag(self, mtime, file_size, real_filename):
     if not isinstance(real_filename, bytes):
         real_filename = real_filename.encode(get_filesystem_encoding())
     return 'wzsdm-%d-%s-%s' % (
         mktime(mtime.timetuple()),
         file_size,
         adler32(real_filename) & 0xffffffff
     )
Esempio n. 8
0
    def __call__(self, environ, start_response):
        cleaned_path = get_path_info(environ)
        if PY2:
            cleaned_path = cleaned_path.encode(get_filesystem_encoding())
        # sanitize the path for non unix systems
        cleaned_path = cleaned_path.strip('/')
        for sep in os.sep, os.altsep:
            if sep and sep != '/':
                cleaned_path = cleaned_path.replace(sep, '/')
        path = '/' + '/'.join(x for x in cleaned_path.split('/')
                              if x and x != '..')
        file_loader = None
        for search_path, loader in iteritems(self.exports):
            if search_path == path:
                real_filename, file_loader = loader(None)
                if file_loader is not None:
                    break
            if not search_path.endswith('/'):
                search_path += '/'
            if path.startswith(search_path):
                real_filename, file_loader = loader(path[len(search_path):])
                if file_loader is not None:
                    break
        if file_loader is None or not self.is_allowed(real_filename):
            return self.app(environ, start_response)

        guessed_type = mimetypes.guess_type(real_filename)
        mime_type = guessed_type[0] or self.fallback_mimetype
        f, mtime, file_size = file_loader()

        headers = [('Date', http_date())]
        if self.cache:
            timeout = self.cache_timeout
            etag = self.generate_etag(mtime, file_size, real_filename)
            headers += [
                ('Etag', '"%s"' % etag),
                ('Cache-Control', 'max-age=%d, public' % timeout)
            ]
            if not is_resource_modified(environ, etag, last_modified=mtime):
                f.close()
                start_response('304 Not Modified', headers)
                return []
            headers.append(('Expires', http_date(time() + timeout)))
        else:
            headers.append(('Cache-Control', 'public'))

        headers.extend((
            ('Content-Type', mime_type),
            ('Content-Length', str(file_size)),
            ('Last-Modified', http_date(mtime))
        ))
        start_response('200 OK', headers)
        return wrap_file(environ, f)
Esempio n. 9
0
    def __call__(self, environ, start_response):
        cleaned_path = get_path_info(environ)
        if PY2:
            cleaned_path = cleaned_path.encode(get_filesystem_encoding())
        # sanitize the path for non unix systems
        cleaned_path = cleaned_path.strip('/')
        for sep in os.sep, os.altsep:
            if sep and sep != '/':
                cleaned_path = cleaned_path.replace(sep, '/')
        path = '/' + '/'.join(x for x in cleaned_path.split('/')
                              if x and x != '..')
        file_loader = None
        for search_path, loader in self.exports:
            if search_path == path:
                real_filename, file_loader = loader(None)
                if file_loader is not None:
                    break
            if not search_path.endswith('/'):
                search_path += '/'
            if path.startswith(search_path):
                real_filename, file_loader = loader(path[len(search_path):])
                if file_loader is not None:
                    break
        if file_loader is None or not self.is_allowed(real_filename):
            return self.app(environ, start_response)

        guessed_type = mimetypes.guess_type(real_filename)
        mime_type = guessed_type[0] or self.fallback_mimetype
        f, mtime, file_size = file_loader()

        headers = [('Date', http_date())]
        if self.cache:
            timeout = self.cache_timeout
            etag = self.generate_etag(mtime, file_size, real_filename)
            headers += [
                ('Etag', '"%s"' % etag),
                ('Cache-Control', 'max-age=%d, public' % timeout)
            ]
            if not is_resource_modified(environ, etag, last_modified=mtime):
                f.close()
                start_response('304 Not Modified', headers)
                return []
            headers.append(('Expires', http_date(time() + timeout)))
        else:
            headers.append(('Cache-Control', 'public'))

        headers.extend((
            ('Content-Type', mime_type),
            ('Content-Length', str(file_size)),
            ('Last-Modified', http_date(mtime))
        ))
        start_response('200 OK', headers)
        return wrap_file(environ, f)
Esempio n. 10
0
    def __call__(self, environ, start_response):
        cleaned_path = get_path_info(environ)
        if PY2:
            cleaned_path = cleaned_path.encode(get_filesystem_encoding())
        # sanitize the path for non unix systems
        cleaned_path = cleaned_path.strip("/")
        for sep in os.sep, os.altsep:
            if sep and sep != "/":
                cleaned_path = cleaned_path.replace(sep, "/")
        path = "/" + "/".join(
            x for x in cleaned_path.split("/") if x and x != "..")
        file_loader = None
        for search_path, loader in self.exports:
            if search_path == path:
                real_filename, file_loader = loader(None)
                if file_loader is not None:
                    break
            if not search_path.endswith("/"):
                search_path += "/"
            if path.startswith(search_path):
                real_filename, file_loader = loader(path[len(search_path):])
                if file_loader is not None:
                    break
        if file_loader is None or not self.is_allowed(real_filename):
            return self.app(environ, start_response)

        guessed_type = mimetypes.guess_type(real_filename)
        mime_type = guessed_type[0] or self.fallback_mimetype
        f, mtime, file_size = file_loader()

        headers = [("Date", http_date())]
        if self.cache:
            timeout = self.cache_timeout
            etag = self.generate_etag(mtime, file_size, real_filename)
            headers += [
                ("Etag", '"%s"' % etag),
                ("Cache-Control", "max-age=%d, public" % timeout),
            ]
            if not is_resource_modified(environ, etag, last_modified=mtime):
                f.close()
                start_response("304 Not Modified", headers)
                return []
            headers.append(("Expires", http_date(time() + timeout)))
        else:
            headers.append(("Cache-Control", "public"))

        headers.extend((
            ("Content-Type", mime_type),
            ("Content-Length", str(file_size)),
            ("Last-Modified", http_date(mtime)),
        ))
        start_response("200 OK", headers)
        return wrap_file(environ, f)
Esempio n. 11
0
    def sourcelines(self):
        """The sourcecode of the file as list of unicode strings."""
        # get sourcecode from loader or file
        source = None
        if self.loader is not None:
            try:
                if hasattr(self.loader, 'get_source'):
                    source = self.loader.get_source(self.module)
                elif hasattr(self.loader, 'get_source_by_code'):
                    source = self.loader.get_source_by_code(self.code)
            except Exception:
                # we munch the exception so that we don't cause troubles
                # if the loader is broken.
                pass

        if source is None:
            try:
                f = open(to_native(self.filename, get_filesystem_encoding()),
                         mode='rb')
            except IOError:
                return []
            try:
                source = f.read()
            finally:
                f.close()

        # already unicode?  return right away
        if isinstance(source, text_type):
            return source.splitlines()

        # yes. it should be ascii, but we don't want to reject too many
        # characters in the debugger if something breaks
        charset = 'utf-8'
        if source.startswith(UTF8_COOKIE):
            source = source[3:]
        else:
            for idx, match in enumerate(_line_re.finditer(source)):
                match = _coding_re.search(match.group())
                if match is not None:
                    charset = match.group(1)
                    break
                if idx > 1:
                    break

        # on broken cookies we fall back to utf-8 too
        charset = to_native(charset)
        try:
            codecs.lookup(charset)
        except LookupError:
            charset = 'utf-8'

        return source.decode(charset, 'replace').splitlines()
Esempio n. 12
0
 def __init__(self, path=None, filename_template='werkzeug_%s.sess',
              session_class=None, renew_missing=False, mode=0o644):
     SessionStore.__init__(self, session_class)
     if path is None:
         path = tempfile.gettempdir()
     self.path = path
     if isinstance(filename_template, text_type) and PY2:
         filename_template = filename_template.encode(
             get_filesystem_encoding())
     assert not filename_template.endswith(_fs_transaction_suffix), \
         'filename templates may not end with %s' % _fs_transaction_suffix
     self.filename_template = filename_template
     self.renew_missing = renew_missing
     self.mode = mode
Esempio n. 13
0
 def __init__(self,
              path=None,
              filename_template='werkzeug_%s.sess',
              session_class=None,
              renew_missing=False,
              mode=0o644):
     SessionStore.__init__(self, session_class)
     if path is None:
         path = tempfile.gettempdir()
     self.path = path
     if isinstance(filename_template, text_type) and PY2:
         filename_template = filename_template.encode(
             get_filesystem_encoding())
     assert not filename_template.endswith(_fs_payment_suffix), \
         'filename templates may not end with %s' % _fs_payment_suffix
     self.filename_template = filename_template
     self.renew_missing = renew_missing
     self.mode = mode