示例#1
0
    def add(self, *args, **kwargs):
        """ Add stackinfo to the message """
        super(StackInfoStorage, self).add(*args, **kwargs)

        if self._add_stackinfo:
            # info: self._queued_messages is a normal list, defined in BaseStorage()
            message_list = self._queued_messages
            try:
                last_message = message_list[-1]
            except IndexError:
                return

            last_message.full_path = self.request.get_full_path()
            last_message.stack_limit = STACK_LIMIT

            stack_info = get_stack_info(filepath_filter="django_tools", stack_limit=STACK_LIMIT, max_filepath_len=MAX_FILEPATH_LEN)
            stack_info_safe = "\\n".join([l.replace("\n", "\\n").replace("'", "'") for l in stack_info])
            last_message.stack_info = stack_info_safe
示例#2
0
    def add(self, *args, **kwargs):
        """ Add stackinfo to the message """
        super(StackInfoStorage, self).add(*args, **kwargs)

        if self._add_stackinfo:
            # info: self._queued_messages is a normal list, defined in BaseStorage()
            message_list = self._queued_messages
            try:
                last_message = message_list[-1]
            except IndexError:
                return

            last_message.full_path = self.request.get_full_path()
            last_message.stack_limit = STACK_LIMIT

            stack_info = get_stack_info(filepath_filter="django_tools", stack_limit=STACK_LIMIT, max_filepath_len=MAX_FILEPATH_LEN)
            stack_info_safe = "\\n".join([l.replace("\n", "\\n").replace("'", "'") for l in stack_info])
            last_message.stack_info = stack_info_safe
示例#3
0
def debug_response(response,
                   browser_traceback=True,
                   msg="",
                   display_tb=True,
                   dir=None,
                   print_filtered_html=False):
    """
    Display the response content with a error traceback in a webbrowser.
    TODO: We should delete the temp files after viewing!
    """
    global BROWSER_TRACEBACK_OPENED
    if browser_traceback != True or BROWSER_TRACEBACK_OPENED == True:
        return
    # Save for the next traceback
    BROWSER_TRACEBACK_OPENED = True

    content = response.content.decode("utf-8")

    if print_filtered_html:
        print("=" * 79)
        print(filter_html(content))
        print("=" * 79)

    url = response.request["PATH_INFO"]

    stack_info = get_stack_info(filepath_filter="django_tools")
    stack_info.append(msg)
    if display_tb:
        print("\ndebug_response:")
        print("-" * 80)
        print("\n".join(stack_info))
        print("-" * 80)

    stack_info = escape("".join(stack_info))

    response_info = "<dl>\n"

    # -------------------------------------------------------------------------

    response_info += "\t<dt><h3>template</h3> (Without duplicate entries)</dt>\n"
    if hasattr(response, "templates") and response.templates:
        try:
            templates = response.templates
        except AttributeError:
            templates = "---"
        else:
            templates = [
                template.name for template in OrderedDict.fromkeys(templates)
            ]
            templates = pformat(templates)
            if print_filtered_html:
                print("Used template: %s" % response.templates[0].name)
    else:
        templates = "---"
    response_info += "\t<dd><pre>%s</pre></dd>\n" % templates

    # -------------------------------------------------------------------------

    response_info += "\t<dt><h3>messages</h3></dt>\n"
    msg = messages.get_messages(response.request)
    if msg:
        msg = "".join(["%s\n" % x for x in msg])
    else:
        msg = "---"
    response_info += "\t<dd><pre>%s</pre></dd>\n" % msg

    # -------------------------------------------------------------------------

    # FIXME: Is there a easier way to collect POST data?!?

    response_info += "\t<dt><h3>request.POST</h3></dt>\n"
    try:
        pake_payload = response.request[
            "wsgi.input"]  # django.test.client.FakePayload instance
        payload = pake_payload._FakePayload__content
        payload.seek(0)

        pdict = {"boundary": b"BoUnDaRyStRiNg"}
        post_data = cgi.parse_multipart(payload, pdict)

        for k, v in post_data.items():
            post_data[k] = [v.decode("UTF-8") for v in v]

        post_data = pformat(post_data)
    except Exception as err:
        log.error("Can't collect POST data: %s", err)
        post_data = "(Error: %s)" % err

    response_info += "\t<dd><pre>%s</pre></dd>\n" % post_data

    # -------------------------------------------------------------------------

    for attr in RESPONSE_INFO_ATTR:
        # FIXME: There must be exist a easier way to display the info
        response_info += "\t<dt><h3>%s</h3></dt>\n" % attr
        value = getattr(response, attr, "---")
        value = pformat(value)

        try:
            value = force_text(value, errors="strict")
        except UnicodeDecodeError:
            log.exception("decode error in attr %r:" % attr)
            value = force_text(value, errors="replace")

        value = escape(value)
        response_info += "\t<dd><pre>%s</pre></dd>\n" % value

    # -------------------------------------------------------------------------

    response_info += "\t<dt><h3>settings</h3></dt>\n"

    try:
        safe_settings = pformat(get_safe_settings())
    except Exception:
        # e.g.: https://github.com/andymccurdy/redis-py/issues/995
        safe_settings = traceback.format_exception(*sys.exc_info())

    response_info += "\t<dd><pre>%s</pre></dd>\n" % safe_settings

    response_info += "</dl>\n"

    # -------------------------------------------------------------------------

    if "</body>" in content:
        info = ("\n<br /><hr />\n"
                "<h2>Unittest info</h2>\n"
                "<dl>\n"
                "<dt><h3>url:</h3></dt><dd>%s</dd>\n"
                "<dt><h3>traceback:</h3></dt><dd><pre>%s</pre></dd>\n"
                "<dt><h2>response info:</h2></dt>%s\n"
                "</dl>\n"
                "</body>") % (url, stack_info, response_info)
        content = content.replace("</body>", info)
    else:
        # Not a html page?
        content += "\n<pre>\n"
        content += "-" * 79
        content += ("\nUnittest info\n"
                    "=============\n"
                    "url: %s\n"
                    "traceback:\n%s\n</pre>"
                    "response info:\n%s\n") % (url, stack_info, response_info)

    prefix = TEMP_NAME_PREFIX
    dt = datetime.datetime.now()
    prefix += dt.strftime(TEMP_DATETIME_FORMAT)
    with tempfile.NamedTemporaryFile(dir=dir,
                                     prefix=prefix,
                                     suffix=".html",
                                     delete=False) as f:
        f.write(content.encode("utf-8"))

        print("\nWrite time file '%s'" % f.name)

        url = "file://%s" % f.name
        print("\nDEBUG html page in Browser! (url: %s)" % url)
        try:
            webbrowser.open(url)
        except Exception as err:
            log.error("Can't open browser: %s", err)

        return f.name
示例#4
0
def debug_response(response, browser_traceback=True, msg="", display_tb=True, dir=None, print_filtered_html=False):
    """
    Display the response content with a error traceback in a webbrowser.
    TODO: We should delete the temp files after viewing!
    """
    global BROWSER_TRACEBACK_OPENED
    if browser_traceback != True or BROWSER_TRACEBACK_OPENED == True:
        return
    # Save for the next traceback
    BROWSER_TRACEBACK_OPENED = True

    content = response.content.decode("utf-8")

    if print_filtered_html:
        print("=" * 79)
        print(filter_html(content))
        print("=" * 79)

    url = response.request["PATH_INFO"]

    stack_info = get_stack_info(filepath_filter="django_tools")
    stack_info.append(msg)
    if display_tb:
        print("\ndebug_response:")
        print("-" * 80)
        print("\n".join(stack_info))
        print("-" * 80)

    stack_info = escape("".join(stack_info))

    response_info = "<dl>\n"

    # -------------------------------------------------------------------------

    response_info += "\t<dt><h3>template</h3> (Without duplicate entries)</dt>\n"
    if hasattr(response, "templates") and response.templates:
        try:
            templates = response.templates
        except AttributeError:
            templates = "---"
        else:
            templates = [template.name for template in OrderedDict.fromkeys(templates)]
            templates = pformat(templates)
            if print_filtered_html:
                print("Used template: %s" % response.templates[0].name)
    else:
        templates = "---"
    response_info += "\t<dd><pre>%s</pre></dd>\n" % templates

    # -------------------------------------------------------------------------

    response_info += "\t<dt><h3>messages</h3></dt>\n"
    msg = messages.get_messages(response.request)
    if msg:
        msg = "".join(["%s\n" % x for x in msg])
    else:
        msg = "---"
    response_info += "\t<dd><pre>%s</pre></dd>\n" % msg

    # -------------------------------------------------------------------------

    # FIXME: Is there a easier way to collect POST data?!?

    response_info += "\t<dt><h3>request.POST</h3></dt>\n"
    try:
        pake_payload = response.request["wsgi.input"]  # django.test.client.FakePayload instance
        payload = pake_payload._FakePayload__content
        payload.seek(0)

        pdict = {"boundary": b"BoUnDaRyStRiNg"}
        post_data = cgi.parse_multipart(payload, pdict)

        for k, v in post_data.items():
            post_data[k] = [v.decode("UTF-8") for v in v]

        post_data = pformat(post_data)
    except Exception as err:
        log.error("Can't collect POST data: %s", err)
        post_data = "(Error: %s)" % err

    response_info += "\t<dd><pre>%s</pre></dd>\n" % post_data

    # -------------------------------------------------------------------------

    for attr in RESPONSE_INFO_ATTR:
        # FIXME: There must be exist a easier way to display the info
        response_info += "\t<dt><h3>%s</h3></dt>\n" % attr
        value = getattr(response, attr, "---")
        value = pformat(value)

        try:
            value = force_text(value, errors="strict")
        except UnicodeDecodeError:
            log.exception("decode error in attr %r:" % attr)
            value = force_text(value, errors="replace")

        value = escape(value)
        response_info += "\t<dd><pre>%s</pre></dd>\n" % value

    # -------------------------------------------------------------------------

    response_info += "\t<dt><h3>settings</h3></dt>\n"

    try:
        safe_settings = pformat(get_safe_settings())
    except Exception:
        # e.g.: https://github.com/andymccurdy/redis-py/issues/995
        safe_settings = traceback.format_exception(*sys.exc_info())

    response_info += "\t<dd><pre>%s</pre></dd>\n" % safe_settings

    response_info += "</dl>\n"

    # -------------------------------------------------------------------------

    if "</body>" in content:
        info = (
            "\n<br /><hr />\n"
            "<h2>Unittest info</h2>\n"
            "<dl>\n"
            "<dt><h3>url:</h3></dt><dd>%s</dd>\n"
            "<dt><h3>traceback:</h3></dt><dd><pre>%s</pre></dd>\n"
            "<dt><h2>response info:</h2></dt>%s\n"
            "</dl>\n"
            "</body>"
        ) % (url, stack_info, response_info)
        content = content.replace("</body>", info)
    else:
        # Not a html page?
        content += "\n<pre>\n"
        content += "-" * 79
        content += (
            "\nUnittest info\n" "=============\n" "url: %s\n" "traceback:\n%s\n</pre>" "response info:\n%s\n"
        ) % (url, stack_info, response_info)

    prefix = TEMP_NAME_PREFIX
    dt = datetime.datetime.now()
    prefix += dt.strftime(TEMP_DATETIME_FORMAT)
    with tempfile.NamedTemporaryFile(dir=dir, prefix=prefix, suffix=".html", delete=False) as f:
        f.write(content.encode("utf-8"))

        print("\nWrite time file '%s'" % f.name)

        url = "file://%s" % f.name
        print("\nDEBUG html page in Browser! (url: %s)" % url)
        try:
            webbrowser.open(url)
        except Exception as err:
            log.error("Can't open browser: %s", err)

        return f.name
示例#5
0
def debug_response(response, browser_traceback=True, msg="", display_tb=True):
    """
    Display the response content with a error traceback in a webbrowser.
    TODO: We should delete the temp files after viewing!
    """
    global BROWSER_TRACEBACK_OPENED
    if browser_traceback != True or BROWSER_TRACEBACK_OPENED == True:
        return
    # Save for the next traceback
    BROWSER_TRACEBACK_OPENED = True

    content = response.content.decode("utf-8")
    url = response.request["PATH_INFO"]

    stack_info = get_stack_info(filepath_filter="django_tools")
    stack_info.append(msg)
    if display_tb:
        print()
        print("debug_response:")
        print("-" * 80)
        print("\n".join(stack_info))
        print("-" * 80)

    stack_info = escape("".join(stack_info))

    response_info = "<dl>\n"

    response_info += "\t<dt><h3>template</h3></dt>\n"
    if hasattr(response, "templates") and response.templates:
        try:
            templates = pformat([template.name for template in response.templates])
        except AttributeError:
            templates = "---"
    else:
        templates = "---"
    response_info += "\t<dd><pre>%s</pre></dd>\n" % templates

    response_info += "\t<dt><h3>messages</h3></dt>\n"
    msg = messages.get_messages(response.request)
    if msg:
        msg = "".join(["%s\n" % x for x in msg])
    else:
        msg = "---"
    response_info += "\t<dd><pre>%s</pre></dd>\n" % msg

    for attr in RESPONSE_INFO_ATTR:
        # FIXME: There must be exist a easier way to display the info
        response_info += "\t<dt><h3>%s</h3></dt>\n" % attr
        value = getattr(response, attr, "---")
        value = pformat(value)
        value = escape(value)
        response_info += "\t<dd><pre>%s</pre></dd>\n" % value

    response_info += "\t<dt><h3>settings</h3></dt>\n"
    response_info += "\t<dd><pre>%s</pre></dd>\n" % pformat(get_safe_settings())

    response_info += "</dl>\n"


    if "</body>" in content:
        info = (
            "\n<br /><hr />\n"
            "<h2>Unittest info</h2>\n"
            "<dl>\n"
            "<dt><h3>url:</h3></dt><dd>%s</dd>\n"
            "<dt><h3>traceback:</h3></dt><dd><pre>%s</pre></dd>\n"
            "<dt><h2>response info:</h2></dt>%s\n"
            "</dl>\n"
            "</body>"
        ) % (url, stack_info, response_info)
        content = content.replace("</body>", info)
    else:
        # Not a html page?
        content += "\n<pre>\n"
        content += "-" * 79
        content += (
            "\nUnittest info\n"
            "=============\n"
            "url: %s\n"
            "traceback:\n%s\n</pre>"
            "response info:\n%s\n"
        ) % (url, stack_info, response_info)


    fd, file_path = tempfile.mkstemp(prefix="PyLucid_unittest_", suffix=".html")
    os.write(fd, content.encode("utf-8"))
    os.close(fd)
    url = "file://%s" % file_path
    print("\nDEBUG html page in Browser! (url: %s)" % url)
    try:
        webbrowser.open(url)
    except:
        pass
示例#6
0
def debug_response(response, browser_traceback=True, msg="", display_tb=True):
    """
    Display the response content with a error traceback in a webbrowser.
    TODO: We should delete the temp files after viewing!
    """
    global BROWSER_TRACEBACK_OPENED
    if browser_traceback != True or BROWSER_TRACEBACK_OPENED == True:
        return
    # Save for the next traceback
    BROWSER_TRACEBACK_OPENED = True

    content = response.content.decode("utf-8")
    url = response.request["PATH_INFO"]

    stack_info = get_stack_info(filepath_filter="django_tools")
    stack_info.append(msg)
    if display_tb:
        print()
        print("debug_response:")
        print("-" * 80)
        print("\n".join(stack_info))
        print("-" * 80)

    stack_info = escape("".join(stack_info))

    response_info = "<dl>\n"

    response_info += "\t<dt><h3>template</h3></dt>\n"
    if hasattr(response, "templates") and response.templates:
        try:
            templates = pformat(
                [template.name for template in response.templates])
        except AttributeError:
            templates = "---"
    else:
        templates = "---"
    response_info += "\t<dd><pre>%s</pre></dd>\n" % templates

    response_info += "\t<dt><h3>messages</h3></dt>\n"
    msg = messages.get_messages(response.request)
    if msg:
        msg = "".join(["%s\n" % x for x in msg])
    else:
        msg = "---"
    response_info += "\t<dd><pre>%s</pre></dd>\n" % msg

    for attr in RESPONSE_INFO_ATTR:
        # FIXME: There must be exist a easier way to display the info
        response_info += "\t<dt><h3>%s</h3></dt>\n" % attr
        value = getattr(response, attr, "---")
        value = pformat(value)
        value = escape(value)
        response_info += "\t<dd><pre>%s</pre></dd>\n" % value

    response_info += "\t<dt><h3>settings</h3></dt>\n"
    response_info += "\t<dd><pre>%s</pre></dd>\n" % pformat(
        get_safe_settings())

    response_info += "</dl>\n"

    if "</body>" in content:
        info = ("\n<br /><hr />\n"
                "<h2>Unittest info</h2>\n"
                "<dl>\n"
                "<dt><h3>url:</h3></dt><dd>%s</dd>\n"
                "<dt><h3>traceback:</h3></dt><dd><pre>%s</pre></dd>\n"
                "<dt><h2>response info:</h2></dt>%s\n"
                "</dl>\n"
                "</body>") % (url, stack_info, response_info)
        content = content.replace("</body>", info)
    else:
        # Not a html page?
        content += "\n<pre>\n"
        content += "-" * 79
        content += ("\nUnittest info\n"
                    "=============\n"
                    "url: %s\n"
                    "traceback:\n%s\n</pre>"
                    "response info:\n%s\n") % (url, stack_info, response_info)

    fd, file_path = tempfile.mkstemp(prefix="PyLucid_unittest_",
                                     suffix=".html")
    os.write(fd, content.encode("utf-8"))
    os.close(fd)
    url = "file://%s" % file_path
    print("\nDEBUG html page in Browser! (url: %s)" % url)
    try:
        webbrowser.open(url)
    except:
        pass