def rst2html(input):
def convertion_attempt(rst):
writer = Writer()
# store full html output to html variable
html = publish_string(source=rst,
writer=writer,
writer_name='html',
settings_overrides={'math-output': 'html',
'link': 'link',
'top': 'top'})
# disable system message in html, no in stderr
parts = publish_parts(source=rst,
writer=writer,
writer_name='html',
settings_overrides={'no_system_messages': True})
# store only html body
body = parts['html_title'] + parts['body'] + parts['html_line'] + \
parts['html_footnotes'] + parts['html_citations'] + \
parts['html_hyperlinks']
return body
try:
return convertion_attempt(input)
except:
return ('<b>' + _('Error in compiling comment') + '</b><br />'
+ input.replace("\n","<br />\n"))
python类publish_parts()的实例源码
def html_doc(self):
"""Methods docstring, as HTML"""
if not self.raw_docstring:
result = ''
elif settings.MODERNRPC_DOC_FORMAT.lower() in ('rst', 'restructred', 'restructuredtext'):
from docutils.core import publish_parts
result = publish_parts(self.raw_docstring, writer_name='html')['body']
elif settings.MODERNRPC_DOC_FORMAT.lower() in ('md', 'markdown'):
import markdown
result = markdown.markdown(self.raw_docstring)
else:
result = "<p>{}</p>".format(self.raw_docstring.replace('\n\n', '</p><p>').replace('\n', ' '))
return mark_safe(urlize(result))
def view_page(request):
page = request.context.page
def add_link(match):
word = match.group(1)
exists = request.dbsession.query(Page).filter_by(name=word).all()
if exists:
view_url = request.route_url('view_page', pagename=word)
return '<a href="%s">%s</a>' % (view_url, escape(word))
else:
add_url = request.route_url('add_page', pagename=word)
return '<a href="%s">%s</a>' % (add_url, escape(word))
content = publish_parts(page.data, writer_name='html')['html_body']
content = wikiwords.sub(add_link, content)
edit_url = request.route_url('edit_page', pagename=page.name)
return dict(page=page, content=content, edit_url=edit_url)
def setup(app):
#app.add_autodocumenter(RuleDocumenter)
app.add_directive('snakemakerule', snakemake_rule_directive, True, (0,0,0))
# Add visit/depart methods to HTML-Translator:
def visit_perform(self, node):
# Ideally, we should use sphinx but this is a simple temporary solution
from docutils import core
from docutils.writers.html4css1 import Writer
w = Writer()
try:
res = core.publish_parts(node.rule_docstring, writer=w)['html_body']
self.body.append('<div class="snakemake">' + res + '</div>' )
node.children = []
except Exception as err:
print(err)
self.body.append('<div class="snakemake"> no docstring </div>' )
def depart_perform(self, node):
node.children = []
def visit_ignore(self, node):
node.children = []
def depart_ignore(self, node):
node.children = []
app.add_node(snakemake_rule,
html=(visit_perform, depart_perform),
latex=(visit_ignore, depart_ignore))
def html_parts(input_string, source_path=None, destination_path=None,
input_encoding='unicode', doctitle=True,
initial_header_level=1):
"""
Given an input string, returns a dictionary of HTML document parts.
Dictionary keys are the names of parts, and values are Unicode strings;
encoding is up to the client.
Parameters:
- `input_string`: A multi-line text string; required.
- `source_path`: Path to the source file or object. Optional, but useful
for diagnostic output (system messages).
- `destination_path`: Path to the file or object which will receive the
output; optional. Used for determining relative paths (stylesheets,
source links, etc.).
- `input_encoding`: The encoding of `input_string`. If it is an encoded
8-bit string, provide the correct encoding. If it is a Unicode string,
use "unicode", the default.
- `doctitle`: Disable the promotion of a lone top-level section title to
document title (and subsequent section title to document subtitle
promotion); enabled by default.
- `initial_header_level`: The initial level for header elements (e.g. 1
for "<h1>").
"""
overrides = {'input_encoding': input_encoding,
'doctitle_xform': doctitle,
'initial_header_level': initial_header_level}
parts = core.publish_parts(
source=input_string, source_path=source_path,
destination_path=destination_path,
writer_name='html', settings_overrides=overrides)
return parts
def html_parts(input_string, source_path=None, destination_path=None,
input_encoding='unicode', doctitle=True,
initial_header_level=1):
"""
Given an input string, returns a dictionary of HTML document parts.
Dictionary keys are the names of parts, and values are Unicode strings;
encoding is up to the client.
Parameters:
- `input_string`: A multi-line text string; required.
- `source_path`: Path to the source file or object. Optional, but useful
for diagnostic output (system messages).
- `destination_path`: Path to the file or object which will receive the
output; optional. Used for determining relative paths (stylesheets,
source links, etc.).
- `input_encoding`: The encoding of `input_string`. If it is an encoded
8-bit string, provide the correct encoding. If it is a Unicode string,
use "unicode", the default.
- `doctitle`: Disable the promotion of a lone top-level section title to
document title (and subsequent section title to document subtitle
promotion); enabled by default.
- `initial_header_level`: The initial level for header elements (e.g. 1
for "<h1>").
"""
overrides = {'input_encoding': input_encoding,
'doctitle_xform': doctitle,
'initial_header_level': initial_header_level}
parts = core.publish_parts(
source=input_string, source_path=source_path,
destination_path=destination_path,
writer_name='html', settings_overrides=overrides)
return parts
def rst2html(rst, theme=None, opts=None, body_only=False):
rst_opts = default_rst_opts.copy()
rst_opts['warning_stream'] = StringIO()
if body_only:
out = publish_parts(rst, writer_name='html',
settings_overrides=rst_opts)['html_body']
rst_opts['warning_stream'].seek(0)
warnings = rst_opts['warning_stream'].read()
return out, warnings
if opts:
rst_opts.update(opts)
rst_opts['template'] = os.path.join(THEMES, 'template.txt')
stylesheets = ['basic.css']
if theme:
stylesheets.append('%s/%s.css' % (theme, theme))
rst_opts['stylesheet'] = ','.join([J(THEMES, p) for p in stylesheets])
out = publish_string(rst, writer_name='html', settings_overrides=rst_opts)
rst_opts['warning_stream'].seek(0)
warnings = rst_opts['warning_stream'].read()
return out, warnings
def html_parts(input_string, source_path=None, destination_path=None,
input_encoding='unicode', doctitle=True,
initial_header_level=1):
"""
Given an input string, returns a dictionary of HTML document parts.
Dictionary keys are the names of parts, and values are Unicode strings;
encoding is up to the client.
Parameters:
- `input_string`: A multi-line text string; required.
- `source_path`: Path to the source file or object. Optional, but useful
for diagnostic output (system messages).
- `destination_path`: Path to the file or object which will receive the
output; optional. Used for determining relative paths (stylesheets,
source links, etc.).
- `input_encoding`: The encoding of `input_string`. If it is an encoded
8-bit string, provide the correct encoding. If it is a Unicode string,
use "unicode", the default.
- `doctitle`: Disable the promotion of a lone top-level section title to
document title (and subsequent section title to document subtitle
promotion); enabled by default.
- `initial_header_level`: The initial level for header elements (e.g. 1
for "<h1>").
"""
overrides = {'input_encoding': input_encoding,
'doctitle_xform': doctitle,
'initial_header_level': initial_header_level}
parts = core.publish_parts(
source=input_string, source_path=source_path,
destination_path=destination_path,
writer_name='html', settings_overrides=overrides)
return parts
def _parse_comment_text(self, text):
settings = {'file_insertion_enabled': False,
'raw_enabled': False,
'output_encoding': 'unicode'}
try:
ret = publish_parts(text, writer_name='html',
settings_overrides=settings)['fragment']
except Exception:
ret = htmlescape(text)
return ret
def _parse_comment_text(self, text):
settings = {'file_insertion_enabled': False,
'raw_enabled': False,
'output_encoding': 'unicode'}
try:
ret = publish_parts(text, writer_name='html',
settings_overrides=settings)['fragment']
except Exception:
ret = htmlescape(text)
return ret
def rstvalidator(path):
if not path:
raise ValueError("path '' EMPTY")
if not os.path.exists(path):
raise OSError("%s NOT EXISTS" % path)
reports = []
def system_message(self, level, message, *children, **kwargs):
args = [self, level, message] + list(children)
result = orignal_system_message(*args, **kwargs)
if level >= self.WARNING_LEVEL:
# All reST failures preventing doc publishing go to reports
# and thus will result to failed checkdocs run
reports.append(message)
return result
def rst2html(value):
""" Run rst2html translation """
parts = publish_parts(source=value, writer_name="html4css1")
return parts['whole']
text = open(path).read()
# Monkeypatch docutils for simple error/warning output support
orignal_system_message = utils.Reporter.system_message
utils.Reporter.system_message = system_message
old_stderr = sys.stderr
sys.stderr = open(os.devnull, "w")
try:
rst2html(text)
utils.Reporter.system_message = orignal_system_message
return reports
finally:
sys.stderr.close()
sys.stderr = old_stderr
def html_parts(input_string, source_path=None, destination_path=None,
input_encoding='unicode', doctitle=True,
initial_header_level=1):
"""
Given an input string, returns a dictionary of HTML document parts.
Dictionary keys are the names of parts, and values are Unicode strings;
encoding is up to the client.
Parameters:
- `input_string`: A multi-line text string; required.
- `source_path`: Path to the source file or object. Optional, but useful
for diagnostic output (system messages).
- `destination_path`: Path to the file or object which will receive the
output; optional. Used for determining relative paths (stylesheets,
source links, etc.).
- `input_encoding`: The encoding of `input_string`. If it is an encoded
8-bit string, provide the correct encoding. If it is a Unicode string,
use "unicode", the default.
- `doctitle`: Disable the promotion of a lone top-level section title to
document title (and subsequent section title to document subtitle
promotion); enabled by default.
- `initial_header_level`: The initial level for header elements (e.g. 1
for "<h1>").
"""
overrides = {'input_encoding': input_encoding,
'doctitle_xform': doctitle,
'initial_header_level': initial_header_level}
parts = core.publish_parts(
source=input_string, source_path=source_path,
destination_path=destination_path,
writer_name='html', settings_overrides=overrides)
return parts
def html_parts(input_string, source_path=None, destination_path=None,
input_encoding='unicode', doctitle=True,
initial_header_level=1):
"""
Given an input string, returns a dictionary of HTML document parts.
Dictionary keys are the names of parts, and values are Unicode strings;
encoding is up to the client.
Parameters:
- `input_string`: A multi-line text string; required.
- `source_path`: Path to the source file or object. Optional, but useful
for diagnostic output (system messages).
- `destination_path`: Path to the file or object which will receive the
output; optional. Used for determining relative paths (stylesheets,
source links, etc.).
- `input_encoding`: The encoding of `input_string`. If it is an encoded
8-bit string, provide the correct encoding. If it is a Unicode string,
use "unicode", the default.
- `doctitle`: Disable the promotion of a lone top-level section title to
document title (and subsequent section title to document subtitle
promotion); enabled by default.
- `initial_header_level`: The initial level for header elements (e.g. 1
for "<h1>").
"""
overrides = {'input_encoding': input_encoding,
'doctitle_xform': doctitle,
'initial_header_level': initial_header_level}
parts = core.publish_parts(
source=input_string, source_path=source_path,
destination_path=destination_path,
writer_name='html', settings_overrides=overrides)
return parts
def main(argv=None):
# Some sanity checks on if the path exists.
filepath = argv[1] if argv is not None else sys.argv[1]
filepath = os.path.abspath(filepath)
if not os.path.exists(filepath):
return 'File Not Found'
# open in binary, decode utf-8, and live in unicode
with codecs.open(filepath, 'r', 'utf8') as f:
page_string = f.read()
overrides = {
'initial_header_level': 1,
'halt_level': 5,
}
parts = core.publish_parts(
source=page_string,
source_path=filepath,
writer_name='html',
settings_overrides=overrides,
)
html_document = parts['html_body']
html_document = html_document.replace('\ufeff', '')
# the REAL print function in python 2, now... see top of file
print(html_document)
def reST_to_html_fragment(a_str):
parts = core.publish_parts(source=a_str, writer_name='html')
return parts['body_pre_docinfo'] + parts['fragment']
def restructuredtext(value, short=False):
try:
from docutils.core import publish_parts
except ImportError:
if settings.DEBUG:
raise template.TemplateSyntaxError(
"Error in 'restructuredtext' filter: "
"The Python docutils library isn't installed."
)
return force_text(value)
else:
docutils_settings = {
'raw_enabled': False,
'file_insertion_enabled': False,
}
docutils_settings.update(getattr(settings, 'RESTRUCTUREDTEXT_FILTER_SETTINGS', {}))
parts = publish_parts(source=force_bytes(value), writer_name="html4css1",
settings_overrides=docutils_settings)
out = force_text(parts["html_body"])
try:
if short:
out = out.split("\n")[0]
except IndexError:
pass
finally:
return mark_safe(out)
examples.py 文件源码
项目:tf_aws_ecs_instance_draining_on_scale_in
作者: terraform-community-modules
项目源码
文件源码
阅读 26
收藏 0
点赞 0
评论 0
def html_parts(input_string, source_path=None, destination_path=None,
input_encoding='unicode', doctitle=True,
initial_header_level=1):
"""
Given an input string, returns a dictionary of HTML document parts.
Dictionary keys are the names of parts, and values are Unicode strings;
encoding is up to the client.
Parameters:
- `input_string`: A multi-line text string; required.
- `source_path`: Path to the source file or object. Optional, but useful
for diagnostic output (system messages).
- `destination_path`: Path to the file or object which will receive the
output; optional. Used for determining relative paths (stylesheets,
source links, etc.).
- `input_encoding`: The encoding of `input_string`. If it is an encoded
8-bit string, provide the correct encoding. If it is a Unicode string,
use "unicode", the default.
- `doctitle`: Disable the promotion of a lone top-level section title to
document title (and subsequent section title to document subtitle
promotion); enabled by default.
- `initial_header_level`: The initial level for header elements (e.g. 1
for "<h1>").
"""
overrides = {'input_encoding': input_encoding,
'doctitle_xform': doctitle,
'initial_header_level': initial_header_level}
parts = core.publish_parts(
source=input_string, source_path=source_path,
destination_path=destination_path,
writer_name='html', settings_overrides=overrides)
return parts
def run(self):
import django
import codecs
from pootle.apps.pootle_misc.checks import (check_names,
excluded_filters)
from translate.filters.checks import (TeeChecker, StandardChecker,
StandardUnitChecker)
try:
from docutils.core import publish_parts
except ImportError:
from distutils.errors import DistutilsModuleError
raise DistutilsModuleError("Please install the docutils library.")
from pootle import syspath_override # noqa
django.setup()
def get_check_description(name, filterfunc):
"""Get a HTML snippet for a specific quality check description.
The quality check description is extracted from the check function
docstring (which uses reStructuredText) and rendered using docutils
to get the HTML snippet.
"""
# Provide a header with an anchor to refer to.
description = ('\n<h3 id="%s">%s</h3>\n\n' %
(name, unicode(check_names[name])))
# Clean the leading whitespace on each docstring line so it gets
# properly rendered.
docstring = "\n".join(line.strip()
for line in filterfunc.__doc__.split("\n"))
# Render the reStructuredText in the docstring into HTML.
description += publish_parts(docstring, writer_name="html")["body"]
return description
print("Regenerating Translate Toolkit quality checks descriptions")
# Get a checker with the Translate Toolkit checks. Note that filters
# that are not used in Pootle are excluded.
fd = TeeChecker(
checkerclasses=[StandardChecker, StandardUnitChecker]
).getfilters(excludefilters=excluded_filters)
docs = sorted(
get_check_description(name, f) for name, f in fd.items()
)
# Output the quality checks descriptions to the HTML file.
templates_dir = os.path.join(
os.path.abspath(os.path.dirname(__file__)), "pootle", "templates"
)
filename = os.path.join(templates_dir, "help/_ttk_quality_checks.html")
with codecs.open(filename, "w", "utf-8") as f:
f.write(u"\n".join(docs))
print("Checks templates written to %r" % (filename))
def find_description(docs):
"""
Determine the package description from DESCRIPTION
:Parameters:
`docs` : ``dict``
Docs config section
:Return: Tuple of summary, description and license
(``('summary', 'description', 'license')``)
(all may be ``None``)
:Rtype: ``tuple``
"""
summary = None
filename = docs.get('meta.summary', 'SUMMARY').strip()
if filename and _os.path.isfile(filename):
fp = open(filename)
try:
try:
summary = fp.read().strip().splitlines()[0].rstrip()
except IndexError:
summary = ''
finally:
fp.close()
description = None
filename = docs.get('meta.description', 'DESCRIPTION').strip()
if filename and _os.path.isfile(filename):
fp = open(filename)
try:
description = fp.read().rstrip()
finally:
fp.close()
if summary is None and description:
from docutils import core
summary = core.publish_parts(
source=description,
source_path=filename,
writer_name='html',
)['title'].encode('utf-8')
return summary, description
def find_description(docs):
"""
Determine the package description from DESCRIPTION
:Parameters:
`docs` : ``dict``
Docs config section
:Return: Tuple of summary, description and license
(``('summary', 'description', 'license')``)
(all may be ``None``)
:Rtype: ``tuple``
"""
summary = None
filename = docs.get('meta.summary', 'SUMMARY').strip()
if filename and _os.path.isfile(filename):
fp = open(filename, encoding='utf-8')
try:
try:
summary = fp.read().strip().splitlines()[0].rstrip()
except IndexError:
summary = ''
finally:
fp.close()
description = None
filename = docs.get('meta.description', 'DESCRIPTION').strip()
if filename and _os.path.isfile(filename):
fp = open(filename, encoding='utf-8')
try:
description = fp.read().rstrip()
finally:
fp.close()
if summary is None and description:
from docutils import core
summary = core.publish_parts(
source=description,
source_path=filename,
writer_name='html',
)['title'].encode('utf-8')
return summary, description
def find_description(docs):
"""
Determine the package description from DESCRIPTION
:Parameters:
`docs` : ``dict``
Docs config section
:Return: Tuple of summary, description and license
(``('summary', 'description', 'license')``)
(all may be ``None``)
:Rtype: ``tuple``
"""
summary = None
filename = docs.get('meta.summary', 'SUMMARY').strip()
if filename and _os.path.isfile(filename):
fp = open(filename)
try:
try:
summary = fp.read().strip().splitlines()[0].rstrip()
except IndexError:
summary = ''
finally:
fp.close()
description = None
filename = docs.get('meta.description', 'DESCRIPTION').strip()
if filename and _os.path.isfile(filename):
fp = open(filename)
try:
description = fp.read().rstrip()
finally:
fp.close()
if summary is None and description:
from docutils import core
summary = core.publish_parts(
source=description,
source_path=filename,
writer_name='html',
)['title'].encode('utf-8')
return summary, description
def find_description(docs):
"""
Determine the package description from DESCRIPTION
:Parameters:
`docs` : ``dict``
Docs config section
:Return: Tuple of summary, description and license
(``('summary', 'description', 'license')``)
(all may be ``None``)
:Rtype: ``tuple``
"""
summary = None
filename = docs.get('meta.summary', 'SUMMARY').strip()
if filename and _os.path.isfile(filename):
fp = open(filename, encoding='utf-8')
try:
try:
summary = fp.read().strip().splitlines()[0].rstrip()
except IndexError:
summary = ''
finally:
fp.close()
description = None
filename = docs.get('meta.description', 'DESCRIPTION').strip()
if filename and _os.path.isfile(filename):
fp = open(filename, encoding='utf-8')
try:
description = fp.read().rstrip()
finally:
fp.close()
if summary is None and description:
from docutils import core
summary = core.publish_parts(
source=description,
source_path=filename,
writer_name='html',
)['title'].encode('utf-8')
return summary, description