def chart(self):
if conf.getboolean('core', 'secure_mode'):
abort(404)
with create_session() as session:
chart_id = request.args.get('chart_id')
embed = request.args.get('embed')
chart = session.query(models.Chart).filter_by(id=chart_id).first()
NVd3ChartClass = chart_mapping.get(chart.chart_type)
if not NVd3ChartClass:
flash(
"Not supported anymore as the license was incompatible, "
"sorry",
"danger")
redirect('/admin/chart/')
sql = ""
if chart.show_sql:
sql = Markup(highlight(
chart.sql,
lexers.SqlLexer(), # Lexer call
HtmlFormatter(noclasses=True))
)
return self.render(
'airflow/nvd3.html',
chart=chart,
title="Airflow - Chart",
sql=sql,
label=chart.label,
embed=embed)
python类HtmlFormatter()的实例源码
def conf(self):
raw = request.args.get('raw') == "true"
title = "Airflow Configuration"
subtitle = conf.AIRFLOW_CONFIG
if conf.getboolean("webserver", "expose_config"):
with open(conf.AIRFLOW_CONFIG, 'r') as f:
config = f.read()
table = [(section, key, value, source)
for section, parameters in conf.as_dict(True, True).items()
for key, (value, source) in parameters.items()]
else:
config = (
"# Your Airflow administrator chose not to expose the "
"configuration, most likely for security reasons.")
table = None
if raw:
return Response(
response=config,
status=200,
mimetype="application/text")
else:
code_html = Markup(highlight(
config,
lexers.IniLexer(), # Lexer call
HtmlFormatter(noclasses=True))
)
return self.render(
'airflow/config.html',
pre_subtitle=settings.HEADER + " v" + airflow.__version__,
code_html=code_html, title=title, subtitle=subtitle,
table=table)
def __init__(self,parent=None,model='',filename='~/.qeval_history'): #'import fandango'):
import fandango.web, fandango.functional
print('%s()'%type(self).__name__)
Qt.QWidget.__init__(self,parent)
try:
self.name = type(self).__name__
self._locals = {'self':self,'load':self.setModel,'printf':self.printf,'Qt':Qt}
self._locals.update([(k,v) for k,v in fandango.functional.__dict__.items() if isCallable(v)])
self._locals['mdir'] = self.dir_module
self._locals['help'] = self.help
self._locals['doc'] = lambda x:x.__doc__
self._locals['run'] = fandango.objects.loadModule
self._locals.update((k,getattr(fandango.web,k)) for k in ('table','bold','color'))
self._modules = {}
self._instances = {}
self.history = []
self.filename = filename.replace('~',os.getenv('HOME')) if filename.startswith('~') else filename
try:#Enabling Syntax Highlighting
from pygments import highlight
from pygments.lexers import PythonLexer
from pygments.formatters import HtmlFormatter
lexer,frmt=PythonLexer(),HtmlFormatter()
self.css=frmt.get_style_defs('.highlight')
self.highlight = lambda t,l=lexer,f=frmt: highlight(t,l,f)
#html='<head><style>%s</style><body>%s</body>'%(css,highlight(code,lexer,frmt))
except:
traceback.print_exc()
self.css = None
self.highlight = lambda t: '<pre>%s</pre>'%t
self.evalQ('import fandango')
self.evalQ('import fandango.qt')
self.evalQ('f=fandango')
self.setup_ui()
self.setEval()
self.setModel(model or '')
except:
traceback.print_exc()
def block_code(self, text, lang):
if not lang:
return '\n<pre><code>%s</code></pre>\n' % text.strip()
lexer = get_lexer_by_name(lang, stripall=True)
formatter = HtmlFormatter()
return highlight(text, lexer, formatter)
def __init__(self, **options):
options['lineseparator'] = '\n<div class="newline"></div>'
formatters.HtmlFormatter.__init__(self, **options)
def test_pygments(pyi_builder):
pyi_builder.test_source(
"""
# This sample code is taken from http://pygments.org/docs/quickstart/.
from pygments import highlight
from pygments.lexers import PythonLexer
from pygments.formatters import HtmlFormatter
code = 'print "Hello World"'
print(highlight(code, PythonLexer(), HtmlFormatter()))
""")
def pretty_json_as_html(data, sort_keys=True):
response = json.dumps(data, sort_keys=sort_keys, indent=2)
# Truncate the data. Alter as needed
response = response[:5000]
# Get the Pygments formatter
formatter = HtmlFormatter(style='colorful')
# Highlight the data
response = highlight(response, JsonLexer(), formatter)
# Get the stylesheet
style = "<style>" + formatter.get_style_defs() + "</style><br>"
# Safe the output
return mark_safe(style + response)
def _format_sql(sql, data, format='html'):
popts = {}
if data.get('remove_comments'):
popts['strip_comments'] = True
if data.get('keyword_case', 'undefined') not in ('undefined', ''):
popts['keyword_case'] = data.get('keyword_case')
if data.get('identifier_case', 'undefined') not in ('undefined', ''):
popts['identifier_case'] = data.get('identifier_case')
if data.get('n_indents', None) is not None:
val = data.get('n_indents')
try:
popts['indent_width'] = max(1, min(1000, int(val)))
popts['reindent'] = True
except (ValueError, TypeError):
pass
if (not 'indent_width' in popts and
data.get('reindent', '').lower() in ('1', 'true', 't')):
popts['indent_width'] = 2
popts['reindent'] = True
if data.get('output_format', None) is not None:
popts['output_format'] = data.get('output_format')
logging.debug('Format: %s, POPTS: %r', format, popts)
logging.debug(sql)
sql = sqlparse.format(sql, **popts)
if format in ('html', 'json'):
if data.get('highlight', False):
if popts['output_format'] == 'python':
lexer = PythonLexer()
elif popts['output_format'] == 'php':
lexer = PhpLexer()
else:
lexer = SqlLexer()
sql = highlight(sql, lexer, HtmlFormatter())
else:
sql = ('<textarea class="resizable" '
'style="height: 350px; margin-top: 1em;">%s</textarea>'
% sql)
return sql
def pygments2xpre(s, language="python"):
"Return markup suitable for XPreformatted"
try:
from pygments import highlight
from pygments.formatters import HtmlFormatter
except ImportError:
return s
from pygments.lexers import get_lexer_by_name
rconv = lambda x: x
if isPy3:
out = getStringIO()
else:
if isUnicode(s):
s = asBytes(s)
rconv = asUnicode
out = getBytesIO()
l = get_lexer_by_name(language)
h = HtmlFormatter()
highlight(s,l,h,out)
styles = [(cls, style.split(';')[0].split(':')[1].strip())
for cls, (style, ttype, level) in h.class2style.items()
if cls and style and style.startswith('color:')]
return rconv(_2xpre(out.getvalue(),styles))
def _wiki_code_callback(matchobj):
m = matchobj.groups()
content = m[1]
content = re.sub(r'^\s*', '', content, re.S)
content = re.sub(r'\s*$', '', content, re.S)
# code_class = m[0]
formatter = HtmlFormatter()
styles = formatter.get_style_defs('.highlight')
code = highlight(content, PythonLexer(), formatter)
return f'<style>{styles}</style>{code}'
def download_release(request, short_name, release_tag):
dataset = get_object_or_404(Dataset, short_name=short_name)
release = get_object_or_404(DatasetRelease, dataset=dataset, release_tag=release_tag)
if release.type is not 'PU' and not dataset.user_is_maintainer(request.user):
raise HttpResponseNotAllowed
script = utils.generate_download_script(dataset)
formatted_script = highlight(script, PythonLexer(), HtmlFormatter())
highlighting_styles = HtmlFormatter().get_style_defs('.highlight')
return render(request, 'datasets/download.html', {'dataset': dataset,
'release': release,
'formatted_script': formatted_script,
'highlighting_styles': highlighting_styles})
def pylight(code):
return highlight(code, PythonLexer(), HtmlFormatter(noclasses=True))
# builtin docstrings to ignore
def block_code(self, text, lang):
if not lang:
return '\n<pre><code>%s</code></pre>\n' % text.strip()
lexer = get_lexer_by_name(lang, stripall=True)
formatter = HtmlFormatter()
return misaka.SmartyPants(highlight(text, lexer, formatter))
def block_code(self, code, lang):
if not lang:
return '\n<pre><code>%s</code></pre>\n' % \
mistune.escape(code)
lexer = get_lexer_by_name(lang, stripall=True)
formatter = HtmlFormatter()
return highlight(code, lexer, formatter)
def block_code(self, code, lang):
if not lang:
return '\n<pre><code>%s</code></pre>\n' % \
mistune.escape(code)
lexer = get_lexer_by_name(lang, stripall=True)
formatter = HtmlFormatter()
return highlight(code, lexer, formatter)
def send_codehilite_style(self, theme='default', dest=None):
"""Send Pygments stylesheet to dest directory"""
if dest == None:
dest = self.staticpath
hl = HtmlFormatter(style=theme).get_style_defs('.codehilite')
fname = path.join(dest, 'codehilite.css')
with open(fname, 'w') as f:
f.write(hl)
def get_prettyjson_html(api_key):
boite = get_object_or_404(Boite, api_key=api_key)
# Example from https://www.pydanny.com/pretty-formatting-json-django-admin.html
response = json.dumps(boite.get_apps_dictionary(), sort_keys=True, indent=2)
response = response[:5000]
formatter = HtmlFormatter(style='friendly')
response = highlight(response, JsonLexer(), formatter)
style = "<style>" + formatter.get_style_defs() + "</style><br>"
return mark_safe(style + response)
def pygment_html_render(s, lexer=lexers.TextLexer):
return highlight(
s,
lexer(),
HtmlFormatter(linenos=True),
)
def chart(self):
session = settings.Session()
chart_id = request.args.get('chart_id')
embed = request.args.get('embed')
chart = session.query(models.Chart).filter_by(id=chart_id).first()
session.expunge_all()
session.commit()
session.close()
NVd3ChartClass = chart_mapping.get(chart.chart_type)
if not NVd3ChartClass:
flash(
"Not supported anymore as the license was incompatible, "
"sorry",
"danger")
redirect('/admin/chart/')
sql = ""
if chart.show_sql:
sql = Markup(highlight(
chart.sql,
lexers.SqlLexer(), # Lexer call
HtmlFormatter(noclasses=True))
)
return self.render(
'airflow/nvd3.html',
chart=chart,
title="Airflow - Chart",
sql=sql,
label=chart.label,
embed=embed)
def sandbox(self):
title = "Sandbox Suggested Configuration"
cfg_loc = conf.AIRFLOW_CONFIG + '.sandbox'
f = open(cfg_loc, 'r')
config = f.read()
f.close()
code_html = Markup(highlight(
config,
lexers.IniLexer(), # Lexer call
HtmlFormatter(noclasses=True))
)
return self.render(
'airflow/code.html',
code_html=code_html, title=title, subtitle=cfg_loc)