Skip to content

Instantly share code, notes, and snippets.

@mpyrev
Created November 16, 2017 09:51
Show Gist options
  • Save mpyrev/f6e68fc708e878009a6d619635d352b0 to your computer and use it in GitHub Desktop.
Save mpyrev/f6e68fc708e878009a6d619635d352b0 to your computer and use it in GitHub Desktop.
get_view_description function with markdown support
import markdown
from django.utils.encoding import smart_text
from django.utils.safestring import mark_safe
from rest_framework.utils import formatting
__all__ = ['get_view_description']
if markdown.version <= '2.2':
HEADERID_EXT_PATH = 'headerid'
LEVEL_PARAM = 'level'
elif markdown.version < '2.6':
HEADERID_EXT_PATH = 'markdown.extensions.headerid'
LEVEL_PARAM = 'level'
else:
HEADERID_EXT_PATH = 'markdown.extensions.toc'
LEVEL_PARAM = 'baselevel'
def apply_markdown(text):
"""
Simple wrapper around :func:`markdown.markdown` to set the base level
of '#' style headers to <h2>.
"""
extensions = [
HEADERID_EXT_PATH,
'markdown.extensions.codehilite',
'markdown.extensions.tables',
]
extension_configs = {
HEADERID_EXT_PATH: {
LEVEL_PARAM: '2'
}
}
md = markdown.Markdown(
extensions=extensions, extension_configs=extension_configs
)
return md.convert(text)
def get_view_description(view_cls, html=False):
"""
Given a view class, return a textual description to represent the view.
This name is used in the browsable API, and in OPTIONS responses.
This function is the default for the `VIEW_DESCRIPTION_FUNCTION` setting.
"""
description = view_cls.__doc__ or ''
description = formatting.dedent(smart_text(description))
if html:
return mark_safe(apply_markdown(description))
return description
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment