pyggy the simple pygments server
flak uses pygments to generate the pretty highlighted code blocks. The original approach was to just shell out to the command line tool, but the performance is, ah, suboptimal. Caching mostly saves me, but at 0.1 secs per execution, highlighting five small samples pushes the initial page render up to half a second. Searching the intertubes for a pygments server didn’t reveal much. (The top hit is a random sample of highlighted code, not a highligher itself, and the other hits don’t seem very useful either.)
So here’s pyggy. It’s really simple. It listens on a port. You feed it a language, a length, and some code. It returns a length and some highlighted html. It’s not configurable. Maybe someone will find it useful.
import socket
import pygments
from pygments import formatters,lexers
html = formatters.get_formatter_by_name("html", noclasses=True, nowrap=True)
getlexer = lexers.get_lexer_by_name
highlight = pygments.highlight
serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
serv.bind(('127.0.0.1', 7878))
serv.listen(10)
while True:
con, addr = serv.accept()
try:
fd = con.makefile()
lang = fd.readline().strip()
amt = int(fd.readline())
code = fd.read(amt)
rv = ""
try:
lex = getlexer(lang)
rv = highlight(code, lex, html)
except:
pass
fd.write(str(len(rv)))
fd.write("\n")
fd.write(rv)
fd.close()
except:
pass
con.close()