Displaying App Code

I’ve found I am using the same pieces of code in most of my apps, so I thought I would start sharing them here. My current favorite snippet is pretty meta: using the pygments library to enhance my app’s documentation and help pages and to allow new users to browse how the app works without having to go to the code repository. This library allows for python syntax highlighting and can be used to display entire files or specific functions, depending on what code you want to show in your app.

How It Works

This snippet takes the code you want to display in the form of a string, highlights it using python syntax, and then adds the highlighted text to a Wave UI element - I usually use a frame element inside of a form card.

1. Your Code as a String

Use the Entire File

with open('./my_file.py') as f:
   my_code = f.read()

Use a Single Function

import inspect
my_code = inspect.getsource(my_function)

2. Highlight that Syntax

from pygments import highlight
from pygments.formatters.html import HtmlFormatter
from pygments.lexers import get_lexer_by_name

py_lexer = get_lexer_by_name('python')
html_formatter = HtmlFormatter(full=True, style='xcode')
highlighted_code = highlight(my_code, py_lexer, html_formatter)

3. Add to the App

from h2o_wave import ui

q.page.add('my_form_card', ui.form_card(
   box='1 1 -1 -1',
   items=[
      ui.text_xl('Application Code'), 
      ui.frame(content= highlighted_code, height="100%")
   ]
)

In My Apps

Here are a few examples of how I’ve used this in practice:

def render_app_code_view(q: Q):
   """Sets up the application-source-code view """

   with open('./app.py') as f:
      contents = f.read()

   py_lexer = get_lexer_by_name('python')
   html_formatter = HtmlFormatter(full=True, style='xcode')
   code = highlight(contents, py_lexer, html_formatter)

   q.page['content'].items = [
      ui.text_xl('Application Code'), 
      ui.frame(content=code, height="100%")
   ]
# Returns a list of UI objects that can be used in a Form_Card: header and python code of the provided file
# Usage: q.page['code'] = ui.form_card(box='3 4 -1 -1', items=python_code_content("run.py"))
def python_code_content(file_to_display):

   local_dir = os.path.dirname(os.path.realpath(__file__))
   with open(os.path.join(local_dir, file_to_display)) as f:
      contents = f.read()

   py_lexer = get_lexer_by_name('python')
   html_formatter = HtmlFormatter(full=True, style='xcode')
   code = highlight(contents, py_lexer, html_formatter)

   return [
      ui.text_xl(f'Application Code'), 
      ui.frame(content=code, height="100%")
   ]

Let me know if you’re showing your code in your own apps!

6 Likes