Skip to content

armgit / zulip

Public Imported from GitHub
0

Zulip server and web application. Open-source team chat that helps teams stay productive and focused.

python: Serialize lxml elements directly to str.

Anders Kaseorg9281dccae4b0
diff --git a/zerver/lib/email_notifications.py b/zerver/lib/email_notifications.py
index acc29ba0f28..001d92381b8 100644
--- a/zerver/lib/email_notifications.py
+++ b/zerver/lib/email_notifications.py
@@ -82,7 +82,7 @@ def relative_to_full_url(base_url: str, content: str) -> str:
fragment = lxml.html.fromstring(new_content)
fragment.make_links_absolute(base_url)
- content = lxml.html.tostring(fragment).decode("utf-8")
+ content = lxml.html.tostring(fragment, encoding="unicode")
return content
@@ -115,7 +115,7 @@ def fix_emojis(content: str, base_url: str, emojiset: str) -> str:
del realm_emoji.attrib['class']
realm_emoji.set('style', 'height: 20px;')
- content = lxml.html.tostring(fragment).decode('utf-8')
+ content = lxml.html.tostring(fragment, encoding="unicode")
return content
def fix_spoilers_in_html(content: str, language: str) -> str:
@@ -141,7 +141,7 @@ def fix_spoilers_in_html(content: str, language: str) -> str:
header_content.append(span_elem)
header.drop_tag()
spoiler_content.drop_tree()
- content = lxml.html.tostring(fragment).decode("utf-8")
+ content = lxml.html.tostring(fragment, encoding="unicode")
return content
def fix_spoilers_in_text(content: str, language: str) -> str:
diff --git a/zerver/lib/markdown/fenced_code.py b/zerver/lib/markdown/fenced_code.py
index 7398377482d..c992b1ba283 100644
--- a/zerver/lib/markdown/fenced_code.py
+++ b/zerver/lib/markdown/fenced_code.py
@@ -78,9 +78,9 @@ Dependencies:
import re
from typing import Any, Dict, Iterable, List, Mapping, MutableSequence, Optional
+import lxml.html
import markdown
from django.utils.html import escape
-from lxml import etree
from markdown.extensions.codehilite import CodeHilite, CodeHiliteExtension
from pygments.lexers import get_lexer_by_name
from pygments.util import ClassNotFound
@@ -402,8 +402,7 @@ class FencedBlockPreprocessor(markdown.preprocessors.Preprocessor):
# Unfortunately, the pygments API doesn't offer a way to add
# this, so we need to do it in a post-processing step.
if lang:
- parsed_code = etree.HTML(code)
- div_tag = parsed_code[0][0]
+ div_tag = lxml.html.fromstring(code)
# For the value of our data element, we get the lexer
# subclass name instead of directly using the language,
@@ -424,9 +423,7 @@ class FencedBlockPreprocessor(markdown.preprocessors.Preprocessor):
code_language = self._escape(lang)
div_tag.attrib['data-code-language'] = code_language
- # lxml implicitly converts tags like <span></span> into <span/>.
- # Specifying method="c14n" when converting to string prevents that.
- code = etree.tostring(div_tag, method="c14n").decode()
+ code = lxml.html.tostring(div_tag, encoding="unicode")
return code
def format_quote(self, text: str) -> str: