PageRenderTime 130ms CodeModel.GetById 33ms RepoModel.GetById 1ms app.codeStats 0ms

/desktop/core/ext-py/Django/django/contrib/admindocs/views.py

https://github.com/jcrobak/hue
Python | 409 lines | 403 code | 3 blank | 3 comment | 4 complexity | 3ae9d2fb1ce441218d01f95e5e64a6f2 MD5 | raw file
  1. from django import template, templatetags
  2. from django.template import RequestContext
  3. from django.conf import settings
  4. from django.contrib.admin.views.decorators import staff_member_required
  5. from django.db import models
  6. from django.shortcuts import render_to_response
  7. from django.core.exceptions import ImproperlyConfigured, ViewDoesNotExist
  8. from django.http import Http404
  9. from django.core import urlresolvers
  10. from django.contrib.admindocs import utils
  11. from django.contrib.sites.models import Site
  12. from django.utils.importlib import import_module
  13. from django.utils.translation import ugettext as _
  14. from django.utils.safestring import mark_safe
  15. import inspect, os, re
  16. # Exclude methods starting with these strings from documentation
  17. MODEL_METHODS_EXCLUDE = ('_', 'add_', 'delete', 'save', 'set_')
  18. class GenericSite(object):
  19. domain = 'example.com'
  20. name = 'my site'
  21. def get_root_path():
  22. try:
  23. return urlresolvers.reverse('admin:index')
  24. except urlresolvers.NoReverseMatch:
  25. from django.contrib import admin
  26. try:
  27. return urlresolvers.reverse(admin.site.root, args=[''])
  28. except urlresolvers.NoReverseMatch:
  29. return getattr(settings, "ADMIN_SITE_ROOT_URL", "/admin/")
  30. def doc_index(request):
  31. if not utils.docutils_is_available:
  32. return missing_docutils_page(request)
  33. return render_to_response('admin_doc/index.html', {
  34. 'root_path': get_root_path(),
  35. }, context_instance=RequestContext(request))
  36. doc_index = staff_member_required(doc_index)
  37. def bookmarklets(request):
  38. admin_root = get_root_path()
  39. return render_to_response('admin_doc/bookmarklets.html', {
  40. 'root_path': admin_root,
  41. 'admin_url': mark_safe("%s://%s%s" % (request.is_secure() and 'https' or 'http', request.get_host(), admin_root)),
  42. }, context_instance=RequestContext(request))
  43. bookmarklets = staff_member_required(bookmarklets)
  44. def template_tag_index(request):
  45. if not utils.docutils_is_available:
  46. return missing_docutils_page(request)
  47. load_all_installed_template_libraries()
  48. tags = []
  49. for module_name, library in template.libraries.items():
  50. for tag_name, tag_func in library.tags.items():
  51. title, body, metadata = utils.parse_docstring(tag_func.__doc__)
  52. if title:
  53. title = utils.parse_rst(title, 'tag', _('tag:') + tag_name)
  54. if body:
  55. body = utils.parse_rst(body, 'tag', _('tag:') + tag_name)
  56. for key in metadata:
  57. metadata[key] = utils.parse_rst(metadata[key], 'tag', _('tag:') + tag_name)
  58. if library in template.builtins:
  59. tag_library = None
  60. else:
  61. tag_library = module_name.split('.')[-1]
  62. tags.append({
  63. 'name': tag_name,
  64. 'title': title,
  65. 'body': body,
  66. 'meta': metadata,
  67. 'library': tag_library,
  68. })
  69. return render_to_response('admin_doc/template_tag_index.html', {
  70. 'root_path': get_root_path(),
  71. 'tags': tags
  72. }, context_instance=RequestContext(request))
  73. template_tag_index = staff_member_required(template_tag_index)
  74. def template_filter_index(request):
  75. if not utils.docutils_is_available:
  76. return missing_docutils_page(request)
  77. load_all_installed_template_libraries()
  78. filters = []
  79. for module_name, library in template.libraries.items():
  80. for filter_name, filter_func in library.filters.items():
  81. title, body, metadata = utils.parse_docstring(filter_func.__doc__)
  82. if title:
  83. title = utils.parse_rst(title, 'filter', _('filter:') + filter_name)
  84. if body:
  85. body = utils.parse_rst(body, 'filter', _('filter:') + filter_name)
  86. for key in metadata:
  87. metadata[key] = utils.parse_rst(metadata[key], 'filter', _('filter:') + filter_name)
  88. if library in template.builtins:
  89. tag_library = None
  90. else:
  91. tag_library = module_name.split('.')[-1]
  92. filters.append({
  93. 'name': filter_name,
  94. 'title': title,
  95. 'body': body,
  96. 'meta': metadata,
  97. 'library': tag_library,
  98. })
  99. return render_to_response('admin_doc/template_filter_index.html', {
  100. 'root_path': get_root_path(),
  101. 'filters': filters
  102. }, context_instance=RequestContext(request))
  103. template_filter_index = staff_member_required(template_filter_index)
  104. def view_index(request):
  105. if not utils.docutils_is_available:
  106. return missing_docutils_page(request)
  107. if settings.ADMIN_FOR:
  108. settings_modules = [import_module(m) for m in settings.ADMIN_FOR]
  109. else:
  110. settings_modules = [settings]
  111. views = []
  112. for settings_mod in settings_modules:
  113. urlconf = import_module(settings_mod.ROOT_URLCONF)
  114. view_functions = extract_views_from_urlpatterns(urlconf.urlpatterns)
  115. if Site._meta.installed:
  116. site_obj = Site.objects.get(pk=settings_mod.SITE_ID)
  117. else:
  118. site_obj = GenericSite()
  119. for (func, regex) in view_functions:
  120. views.append({
  121. 'name': getattr(func, '__name__', func.__class__.__name__),
  122. 'module': func.__module__,
  123. 'site_id': settings_mod.SITE_ID,
  124. 'site': site_obj,
  125. 'url': simplify_regex(regex),
  126. })
  127. return render_to_response('admin_doc/view_index.html', {
  128. 'root_path': get_root_path(),
  129. 'views': views
  130. }, context_instance=RequestContext(request))
  131. view_index = staff_member_required(view_index)
  132. def view_detail(request, view):
  133. if not utils.docutils_is_available:
  134. return missing_docutils_page(request)
  135. mod, func = urlresolvers.get_mod_func(view)
  136. try:
  137. view_func = getattr(import_module(mod), func)
  138. except (ImportError, AttributeError):
  139. raise Http404
  140. title, body, metadata = utils.parse_docstring(view_func.__doc__)
  141. if title:
  142. title = utils.parse_rst(title, 'view', _('view:') + view)
  143. if body:
  144. body = utils.parse_rst(body, 'view', _('view:') + view)
  145. for key in metadata:
  146. metadata[key] = utils.parse_rst(metadata[key], 'model', _('view:') + view)
  147. return render_to_response('admin_doc/view_detail.html', {
  148. 'root_path': get_root_path(),
  149. 'name': view,
  150. 'summary': title,
  151. 'body': body,
  152. 'meta': metadata,
  153. }, context_instance=RequestContext(request))
  154. view_detail = staff_member_required(view_detail)
  155. def model_index(request):
  156. if not utils.docutils_is_available:
  157. return missing_docutils_page(request)
  158. m_list = [m._meta for m in models.get_models()]
  159. return render_to_response('admin_doc/model_index.html', {
  160. 'root_path': get_root_path(),
  161. 'models': m_list
  162. }, context_instance=RequestContext(request))
  163. model_index = staff_member_required(model_index)
  164. def model_detail(request, app_label, model_name):
  165. if not utils.docutils_is_available:
  166. return missing_docutils_page(request)
  167. # Get the model class.
  168. try:
  169. app_mod = models.get_app(app_label)
  170. except ImproperlyConfigured:
  171. raise Http404, _("App %r not found") % app_label
  172. model = None
  173. for m in models.get_models(app_mod):
  174. if m._meta.object_name.lower() == model_name:
  175. model = m
  176. break
  177. if model is None:
  178. raise Http404, _("Model %(model_name)r not found in app %(app_label)r") % {'model_name': model_name, 'app_label': app_label}
  179. opts = model._meta
  180. # Gather fields/field descriptions.
  181. fields = []
  182. for field in opts.fields:
  183. # ForeignKey is a special case since the field will actually be a
  184. # descriptor that returns the other object
  185. if isinstance(field, models.ForeignKey):
  186. data_type = related_object_name = field.rel.to.__name__
  187. app_label = field.rel.to._meta.app_label
  188. verbose = utils.parse_rst((_("the related `%(app_label)s.%(data_type)s` object") % {'app_label': app_label, 'data_type': data_type}), 'model', _('model:') + data_type)
  189. else:
  190. data_type = get_readable_field_data_type(field)
  191. verbose = field.verbose_name
  192. fields.append({
  193. 'name': field.name,
  194. 'data_type': data_type,
  195. 'verbose': verbose,
  196. 'help_text': field.help_text,
  197. })
  198. # Gather many-to-many fields.
  199. for field in opts.many_to_many:
  200. data_type = related_object_name = field.rel.to.__name__
  201. app_label = field.rel.to._meta.app_label
  202. verbose = _("related `%(app_label)s.%(object_name)s` objects") % {'app_label': app_label, 'object_name': data_type}
  203. fields.append({
  204. 'name': "%s.all" % field.name,
  205. "data_type": 'List',
  206. 'verbose': utils.parse_rst(_("all %s") % verbose , 'model', _('model:') + opts.module_name),
  207. })
  208. fields.append({
  209. 'name' : "%s.count" % field.name,
  210. 'data_type' : 'Integer',
  211. 'verbose' : utils.parse_rst(_("number of %s") % verbose , 'model', _('model:') + opts.module_name),
  212. })
  213. # Gather model methods.
  214. for func_name, func in model.__dict__.items():
  215. if (inspect.isfunction(func) and len(inspect.getargspec(func)[0]) == 1):
  216. try:
  217. for exclude in MODEL_METHODS_EXCLUDE:
  218. if func_name.startswith(exclude):
  219. raise StopIteration
  220. except StopIteration:
  221. continue
  222. verbose = func.__doc__
  223. if verbose:
  224. verbose = utils.parse_rst(utils.trim_docstring(verbose), 'model', _('model:') + opts.module_name)
  225. fields.append({
  226. 'name': func_name,
  227. 'data_type': get_return_data_type(func_name),
  228. 'verbose': verbose,
  229. })
  230. # Gather related objects
  231. for rel in opts.get_all_related_objects() + opts.get_all_related_many_to_many_objects():
  232. verbose = _("related `%(app_label)s.%(object_name)s` objects") % {'app_label': rel.opts.app_label, 'object_name': rel.opts.object_name}
  233. accessor = rel.get_accessor_name()
  234. fields.append({
  235. 'name' : "%s.all" % accessor,
  236. 'data_type' : 'List',
  237. 'verbose' : utils.parse_rst(_("all %s") % verbose , 'model', _('model:') + opts.module_name),
  238. })
  239. fields.append({
  240. 'name' : "%s.count" % accessor,
  241. 'data_type' : 'Integer',
  242. 'verbose' : utils.parse_rst(_("number of %s") % verbose , 'model', _('model:') + opts.module_name),
  243. })
  244. return render_to_response('admin_doc/model_detail.html', {
  245. 'root_path': get_root_path(),
  246. 'name': '%s.%s' % (opts.app_label, opts.object_name),
  247. 'summary': _("Fields on %s objects") % opts.object_name,
  248. 'description': model.__doc__,
  249. 'fields': fields,
  250. }, context_instance=RequestContext(request))
  251. model_detail = staff_member_required(model_detail)
  252. def template_detail(request, template):
  253. templates = []
  254. for site_settings_module in settings.ADMIN_FOR:
  255. settings_mod = import_module(site_settings_module)
  256. if Site._meta.installed:
  257. site_obj = Site.objects.get(pk=settings_mod.SITE_ID)
  258. else:
  259. site_obj = GenericSite()
  260. for dir in settings_mod.TEMPLATE_DIRS:
  261. template_file = os.path.join(dir, template)
  262. templates.append({
  263. 'file': template_file,
  264. 'exists': os.path.exists(template_file),
  265. 'contents': lambda: os.path.exists(template_file) and open(template_file).read() or '',
  266. 'site_id': settings_mod.SITE_ID,
  267. 'site': site_obj,
  268. 'order': list(settings_mod.TEMPLATE_DIRS).index(dir),
  269. })
  270. return render_to_response('admin_doc/template_detail.html', {
  271. 'root_path': get_root_path(),
  272. 'name': template,
  273. 'templates': templates,
  274. }, context_instance=RequestContext(request))
  275. template_detail = staff_member_required(template_detail)
  276. ####################
  277. # Helper functions #
  278. ####################
  279. def missing_docutils_page(request):
  280. """Display an error message for people without docutils"""
  281. return render_to_response('admin_doc/missing_docutils.html')
  282. def load_all_installed_template_libraries():
  283. # Load/register all template tag libraries from installed apps.
  284. for e in templatetags.__path__:
  285. libraries = [os.path.splitext(p)[0] for p in os.listdir(e) if p.endswith('.py') and p[0].isalpha()]
  286. for library_name in libraries:
  287. try:
  288. lib = template.get_library("django.templatetags.%s" % library_name.split('.')[-1])
  289. except template.InvalidTemplateLibrary:
  290. pass
  291. def get_return_data_type(func_name):
  292. """Return a somewhat-helpful data type given a function name"""
  293. if func_name.startswith('get_'):
  294. if func_name.endswith('_list'):
  295. return 'List'
  296. elif func_name.endswith('_count'):
  297. return 'Integer'
  298. return ''
  299. # Maps Field objects to their human-readable data types, as strings.
  300. # Column-type strings can contain format strings; they'll be interpolated
  301. # against the values of Field.__dict__ before being output.
  302. # If a column type is set to None, it won't be included in the output.
  303. DATA_TYPE_MAPPING = {
  304. 'AutoField' : _('Integer'),
  305. 'BooleanField' : _('Boolean (Either True or False)'),
  306. 'CharField' : _('String (up to %(max_length)s)'),
  307. 'CommaSeparatedIntegerField': _('Comma-separated integers'),
  308. 'DateField' : _('Date (without time)'),
  309. 'DateTimeField' : _('Date (with time)'),
  310. 'DecimalField' : _('Decimal number'),
  311. 'EmailField' : _('E-mail address'),
  312. 'FileField' : _('File path'),
  313. 'FilePathField' : _('File path'),
  314. 'FloatField' : _('Floating point number'),
  315. 'ForeignKey' : _('Integer'),
  316. 'ImageField' : _('File path'),
  317. 'IntegerField' : _('Integer'),
  318. 'IPAddressField' : _('IP address'),
  319. 'ManyToManyField' : '',
  320. 'NullBooleanField' : _('Boolean (Either True, False or None)'),
  321. 'OneToOneField' : _('Relation to parent model'),
  322. 'PhoneNumberField' : _('Phone number'),
  323. 'PositiveIntegerField' : _('Integer'),
  324. 'PositiveSmallIntegerField' : _('Integer'),
  325. 'SlugField' : _('String (up to %(max_length)s)'),
  326. 'SmallIntegerField' : _('Integer'),
  327. 'TextField' : _('Text'),
  328. 'TimeField' : _('Time'),
  329. 'URLField' : _('URL'),
  330. 'USStateField' : _('U.S. state (two uppercase letters)'),
  331. 'XMLField' : _('XML text'),
  332. }
  333. def get_readable_field_data_type(field):
  334. return DATA_TYPE_MAPPING[field.get_internal_type()] % field.__dict__
  335. def extract_views_from_urlpatterns(urlpatterns, base=''):
  336. """
  337. Return a list of views from a list of urlpatterns.
  338. Each object in the returned list is a two-tuple: (view_func, regex)
  339. """
  340. views = []
  341. for p in urlpatterns:
  342. if hasattr(p, '_get_callback'):
  343. try:
  344. views.append((p._get_callback(), base + p.regex.pattern))
  345. except ViewDoesNotExist:
  346. continue
  347. elif hasattr(p, '_get_url_patterns'):
  348. try:
  349. patterns = p.url_patterns
  350. except ImportError:
  351. continue
  352. views.extend(extract_views_from_urlpatterns(patterns, base + p.regex.pattern))
  353. else:
  354. raise TypeError, _("%s does not appear to be a urlpattern object") % p
  355. return views
  356. named_group_matcher = re.compile(r'\(\?P(<\w+>).+?\)')
  357. non_named_group_matcher = re.compile(r'\(.*?\)')
  358. def simplify_regex(pattern):
  359. """
  360. Clean up urlpattern regexes into something somewhat readable by Mere Humans:
  361. turns something like "^(?P<sport_slug>\w+)/athletes/(?P<athlete_slug>\w+)/$"
  362. into "<sport_slug>/athletes/<athlete_slug>/"
  363. """
  364. # handle named groups first
  365. pattern = named_group_matcher.sub(lambda m: m.group(1), pattern)
  366. # handle non-named groups
  367. pattern = non_named_group_matcher.sub("<var>", pattern)
  368. # clean up any outstanding regex-y characters.
  369. pattern = pattern.replace('^', '').replace('$', '').replace('?', '').replace('//', '/').replace('\\', '')
  370. if not pattern.startswith('/'):
  371. pattern = '/' + pattern
  372. return pattern