Changeset 2555

Show
Ignore:
Timestamp:
03/02/10 16:13:56 (5 months ago)
Author:
JensDiemer
Message:
  • NEW: tools / overwrite template !
  • Bugfix wrong settings.TEMPLATE_DIRS & Bugfix wrong template_path in PyLucidPlugin?
  • merge some code in hightlighter.py
Location:
branches/0.9/pylucid_project
Files:
1 added
6 modified

Legend:

Unmodified
Added
Removed
  • branches/0.9/pylucid_project/apps/pylucid/markup/hightlighter.py

    r2106 r2555  
    2525from pylucid_project.utils.SimpleStringIO import SimpleStringIO 
    2626from pylucid_project.utils.escape import escape, escape_django_tags 
     27from pylucid_project.apps.pylucid.models import EditableHtmlHeadFile 
    2728 
    2829try: 
     
    107108 
    108109 
     110def get_pygments_css(request): 
     111    """ 
     112    Returns the EditableHtmlHeadFile path to pygments.css 
     113    A page_msg would be created, if css not exists. 
     114    """ 
     115    try: 
     116        pygments_css = EditableHtmlHeadFile.on_site.get(filepath="pygments.css") 
     117    except EditableHtmlHeadFile.DoesNotExist: 
     118        request.page_msg("Error: No headfile with filepath 'pygments.css' found.") 
     119    else: 
     120        absolute_url = pygments_css.get_absolute_url(colorscheme=None) 
     121        return absolute_url 
  • branches/0.9/pylucid_project/pylucid_plugins/tools/admin_urls.py

    r2460 r2555  
    2323    url(r'^cleanup_log/$', admin_views.cleanup_log, name='Tools-cleanup_log'), 
    2424    url(r'^cleanup_session/$', admin_views.cleanup_session, name='Tools-cleanup_session'), 
     25    url(r'^overwrite_template/$', admin_views.overwrite_template, name='Tools-overwrite_template'), 
    2526) 
    2627 
  • branches/0.9/pylucid_project/pylucid_plugins/tools/admin_views.py

    r2460 r2555  
    11# coding:utf-8 
    22 
     3import os 
     4import posixpath 
    35from datetime import datetime, timedelta 
     6 
     7 
     8if __name__ == "__main__": 
     9    os.environ['DJANGO_SETTINGS_MODULE'] = "pylucid_project.settings" 
     10    virtualenv_file = "../../../../../bin/activate_this.py" 
     11    execfile(virtualenv_file, dict(__file__=virtualenv_file)) 
    412 
    513from django import http 
    614from django.conf import settings 
    715from django.utils.translation import ugettext as _ 
     16from django.utils.translation import ugettext as _ 
    817from django.contrib.sessions.models import Session 
    9  
    10 from pylucid.models import EditableHtmlHeadFile, LogEntry 
    11 from pylucid.decorators import check_permissions, render_to 
    12  
    13 from pylucid_admin.admin_menu import AdminMenu 
    14  
    15 from pylucid.markup.hightlighter import make_html 
    16  
    17 from pylucid_project.pylucid_plugins.tools.forms import HighlightCodeForm, CleanupLogForm 
     18from django.core.urlresolvers import reverse 
     19from django.contrib.sites.models import Site 
     20 
     21from dbtemplates.models import Template 
     22 
     23from pylucid_project.apps.pylucid.models import LogEntry 
     24from pylucid_project.apps.pylucid.decorators import check_permissions, render_to 
     25from pylucid_project.apps.pylucid.markup.hightlighter import make_html, get_pygments_css 
     26 
     27from pylucid_project.apps.pylucid_admin.admin_menu import AdminMenu 
     28 
     29from pylucid_project.pylucid_plugins.tools.forms import HighlightCodeForm, CleanupLogForm, SelectTemplateForm 
     30 
    1831 
    1932MYSQL_ENCODING_VARS = ( 
     
    4457        url_name="Tools-cleanup_session" 
    4558    ) 
    46  
     59    admin_menu.add_menu_entry( 
     60        parent=menu_section_entry, name="overwrite template", 
     61        title="Overwrite a filesystem template with a new database headfile entry", 
     62        url_name="Tools-overwrite_template" 
     63    ) 
    4764    return "\n".join(output) 
    4865 
     
    5875    } 
    5976 
    60     try: 
    61         pygments_css = EditableHtmlHeadFile.on_site.get(filepath="pygments.css") 
    62     except EditableHtmlHeadFile.DoesNotExist: 
    63         request.page_msg("Error: No headfile with filepath 'pygments.css' found.") 
    64     else: 
    65         absolute_url = pygments_css.get_absolute_url(colorscheme=None) 
    66         context["pygments_css"] = absolute_url 
     77    # get the EditableHtmlHeadFile path to pygments.css (page_msg created, if not exists) 
     78    pygments_css_path = get_pygments_css(request) 
     79    context["pygments_css"] = pygments_css_path 
    6780 
    6881    if request.method == "POST": 
     
    152165    } 
    153166    return context 
     167 
     168 
     169#----------------------------------------------------------------------------------------------------------- 
     170# overwrite template 
     171 
     172 
     173class TemplateFile(object): 
     174    def __init__(self, request, fs_path): 
     175        self.request = request 
     176        self.fs_path = fs_path 
     177 
     178        self.name = fs_path.rsplit("templates", 1)[1].lstrip("/") 
     179 
     180    def _get_fs_content(self): 
     181        try: 
     182            f = file(self.fs_path, "r") 
     183            content = f.read() 
     184            f.close() 
     185        except Exception, err: 
     186            request.page_msg.error("Can't read file: %s" % err) 
     187        else: 
     188            return content 
     189 
     190    def get_or_create_dbtemplate(self): 
     191        """ 
     192        create a dbtemplate entry with the content form filesystem. 
     193        return the dbtemplate instance if success, otherwise: create a page_msg and return None 
     194        """ 
     195        content = self._get_fs_content() 
     196        if not content: 
     197            # Content can't readed. 
     198            return 
     199 
     200        template, created = Template.objects.get_or_create(name=self.name, 
     201            defaults={"content": content} 
     202        ) 
     203        if created: 
     204            template.save() 
     205            current_site = Site.objects.get_current() 
     206            template.sites.add(current_site) 
     207            template.save() 
     208        return template, created 
     209 
     210    def get_content_preview(self): 
     211        content = self._get_fs_content() 
     212        if not content: 
     213            # Can't read the template content, page_msg was created. 
     214            return 
     215 
     216        ext = os.path.splitext(self.fs_path)[1] 
     217        html = make_html(content, ext) 
     218        return html 
     219 
     220 
     221 
     222@check_permissions( 
     223    superuser_only=False, 
     224    permissions=(u'dbtemplates.add_template', u'dbtemplates.change_template') 
     225) 
     226@render_to("tools/overwrite_template.html") 
     227def overwrite_template(request): 
     228    """ 
     229    Overwrite a template: 
     230    1. The user can choose between all existing template in filesystem. 
     231    2. Read the content from filesystem and create a new dbtemplate entry. 
     232    3. redirect to edit the nre dbtemplate entry 
     233    """ 
     234    context = { 
     235        "title": _("overwrite template"), 
     236    } 
     237 
     238    if request.method != "POST": 
     239        form = SelectTemplateForm() 
     240    else: 
     241        form = SelectTemplateForm(request.POST) 
     242        if form.is_valid(): 
     243            fs_path = form.cleaned_data["template"] 
     244            template = TemplateFile(request, fs_path) 
     245 
     246            if "preview" in request.POST: 
     247                # Display only the template content 
     248                preview_html = template.get_content_preview() 
     249                if preview_html: 
     250                    context["template"] = template 
     251 
     252                    # get the EditableHtmlHeadFile path to pygments.css (page_msg created, if not exists) 
     253                    pygments_css_path = get_pygments_css(request) 
     254                    context["pygments_css"] = pygments_css_path 
     255            else: 
     256                # A new dbtemplate should be created 
     257                instance, created = template.get_or_create_dbtemplate() 
     258                if instance: 
     259                    if created: 
     260                        # New dbtemplate instance created -> edit it 
     261                        # if instance == None: e.g.: error reading file -> page_msg was created 
     262                        msg = _("New dbtemplate entry %s created.") % instance 
     263                        LogEntry.objects.log_action( 
     264                            app_label="pylucid_plugin.extrahead", 
     265                            action="overwrite template %s" % template.name, 
     266                            request=request, 
     267                            message=msg 
     268                        ) 
     269                    else: 
     270                        msg = _("dbtemplate entry %s already exists!") % instance 
     271 
     272                    msg += _(" You can edit it now.") 
     273 
     274                    request.page_msg(msg) 
     275 
     276                    # redirect to edit the new dbtemplate entry 
     277                    url = reverse("admin:dbtemplates_template_change", args=(instance.id,)) 
     278                    return http.HttpResponseRedirect(url) 
     279 
     280    context["form"] = form 
     281    return context 
     282 
     283 
     284if __name__ == "__main__": 
     285    templates = [TemplateDir(dir) for dir in settings.TEMPLATE_DIRS] 
  • branches/0.9/pylucid_project/pylucid_plugins/tools/forms.py

    r2431 r2555  
    11# coding: utf-8 
    22 
     3import os 
     4import posixpath 
     5 
     6if __name__ == "__main__": 
     7    os.environ['DJANGO_SETTINGS_MODULE'] = "pylucid_project.settings" 
     8    virtualenv_file = "../../../../../bin/activate_this.py" 
     9    execfile(virtualenv_file, dict(__file__=virtualenv_file)) 
     10 
    311from django import forms 
     12from django.conf import settings 
    413from django.utils.translation import ugettext_lazy as _ 
    514 
     
    2938        help_text=_("Limit the query to the current site?") 
    3039    ) 
     40 
     41 
     42#----------------------------------------------------------------------------------------------------------- 
     43# overwrite template 
     44 
     45 
     46class Template(object): 
     47    """ one template file """ 
     48    def __init__(self, path, filename, abs_path): 
     49        self.path = path 
     50        self.filename = filename 
     51        self.abs_path = abs_path 
     52 
     53    def get_choices(self): 
     54        if "templates" in self.abs_path: 
     55            path = self.abs_path.split("templates", 1)[1] 
     56        else: 
     57            path = self.abs_path 
     58        path = posixpath.normpath(path) 
     59        path = path.lstrip("/") 
     60        return (self.abs_path, path) 
     61 
     62 
     63class TemplateDir(object): 
     64    """ all template in a settings.TEMPLATE_DIRS """ 
     65    def __init__(self, fs_path): 
     66        self.fs_path = fs_path 
     67 
     68        self.short_path = self._build_short_path() 
     69 
     70        if not os.path.isdir(self.fs_path): 
     71            print "Error: %r doesn't exist!!!" % self.fs_path 
     72 
     73        self.templates = [] 
     74        self._get_all_files(self.fs_path) 
     75 
     76    def _build_short_path(self): 
     77        if self.fs_path.startswith(settings.PYLUCID_BASE_PATH): 
     78            short_path = self.fs_path[len(settings.PYLUCID_BASE_PATH):] 
     79        else: 
     80            short_path = self.fs_path 
     81 
     82        short_path = posixpath.normpath(short_path) 
     83        short_path = short_path.strip("/") 
     84        short_path = short_path.rsplit("templates", 1)[0] 
     85        if "/src/" in short_path: 
     86            short_path = short_path.split("/src/")[1] 
     87 
     88        return short_path 
     89 
     90    def _get_all_files(self, path): 
     91        dir_items = os.listdir(path) 
     92        for dir_item in dir_items: 
     93            if dir_item.startswith("."): # Skip hidden items, e.g.: .svn 
     94                continue 
     95 
     96            abs_path = os.path.join(path, dir_item) 
     97            if os.path.isfile(abs_path): 
     98                self.templates.append(Template(path, dir_item, abs_path)) 
     99            elif os.path.isdir(abs_path): 
     100                self._get_all_files(abs_path) # go recusive deeper 
     101            else: 
     102                raise AssertionError("item %r not file or dir" % abs_path) 
     103 
     104 
     105class Templates(object): 
     106    """ all templates """ 
     107    def __init__(self, template_dirs): 
     108        self.template_dirs = template_dirs 
     109        self.templates = {} 
     110        for dir in template_dirs: 
     111            self.templates[dir] = TemplateDir(dir) 
     112 
     113    def get_choices(self): 
     114        choices = [] 
     115        for dir in self.template_dirs: 
     116            templates = self.templates[dir] 
     117            dir_items = [] 
     118            for template in templates.templates: 
     119                dir_items.append(template.get_choices()) 
     120            dir_items.sort() 
     121            choices.append((templates.short_path, dir_items)) 
     122 
     123        choices.sort() 
     124        return choices 
     125 
     126 
     127class ChoiceTemplateField(forms.ChoiceField): 
     128    def __init__(self, *args, **kwargs): 
     129        super(ChoiceTemplateField, self).__init__(*args, **kwargs) 
     130 
     131        templates = Templates(settings.TEMPLATE_DIRS) 
     132        self.choices = [("", "---------")] 
     133        self.choices += templates.get_choices() 
     134 
     135 
     136class SelectTemplateForm(forms.Form): 
     137    template = ChoiceTemplateField( 
     138        initial="", 
     139        help_text=_("Select the template you would like to overwrite in dbtemplate.") 
     140    ) 
     141 
     142 
     143if __name__ == "__main__": 
     144    from pprint import pprint 
     145 
     146    form = SelectTemplateForm() 
     147    pprint(form.fields["template"].choices) 
     148 
  • branches/0.9/pylucid_project/settings.py

    r2548 r2555  
    3131try: 
    3232    #from django_tools.utils import info_print;info_print.redirect_stdout() 
    33  
     33    import django 
     34    import dbpreferences 
    3435    import pylucid_project 
    3536    from pylucid_project.system import pylucid_plugins 
     
    4041 
    4142PYLUCID_PROJECT_ROOT = os.path.abspath(os.path.dirname(pylucid_project.__file__)) 
     43#print "PYLUCID_PROJECT_ROOT:", PYLUCID_PROJECT_ROOT 
    4244#PYLUCID_PLUGINS_ROOT = os.path.abspath(os.path.dirname(pylucid_plugins.__file__)) 
    4345 
     
    134136    os.path.join(PYLUCID_BASE_PATH, "apps/pylucid_update/templates/"), 
    135137 
    136     os.path.join(PYLUCID_BASE_PATH, "apps/dbpreferences/templates/"), 
    137  
    138     os.path.join(PYLUCID_BASE_PATH, "django/contrib/admin/templates"), 
     138    os.path.join(os.path.abspath(os.path.dirname(dbpreferences.__file__)), "templates/"), 
     139    os.path.join(os.path.abspath(os.path.dirname(django.__file__)), "contrib/admin/templates"), 
    139140) 
    140141# Add all templates subdirs from all existing PyLucid plugins 
    141142TEMPLATE_DIRS += pylucid_plugins.PYLUCID_PLUGINS.template_dirs 
    142 #print "settings.TEMPLATE_DIRS:", TEMPLATE_DIRS 
     143#print "settings.TEMPLATE_DIRS:\n", "\n".join(TEMPLATE_DIRS) 
    143144 
    144145TEMPLATE_LOADERS = ( 
  • branches/0.9/pylucid_project/system/pylucid_plugins.py

    r2543 r2555  
    3131        self.pkg_string = ".".join([pkg_prefix, plugin_name]) 
    3232        self.name = plugin_name 
    33  
    34         self._template_path = os.path.join(fs_path, "templates") 
     33        self._template_path = os.path.join(fs_path, plugin_name, "templates") 
    3534 
    3635    def get_template_path(self):