Example #1
0
def load_template(name, namespace=geebaby_templates_namespace):
    if ':' in name:
        namespace, name = name.split(":", 1)
    
    parts = [x for x in name.split("/") if x]

    entity = parts.pop()
    entity = entity.split(".")[0]
    
    tags = ['templates'] + parts
    
    gb = Geebaby.get_objects_in_namespace(namespace, tags, [entity], fetch=1)
    
    if gb:
        def uptodate():
            return not Geebaby.is_modified(tags, entity)
        return getattr(gb[0], 'text', ''), name, uptodate
    else:
        if tags == ['templates'] and entity == 'default':
            if namespace != 'templates':
                # Load the global default template.
                return load_template('default.html', namespace='templates')
            else:
                # Even global template was not found,
                # return the hardcoded welcome template. 
                return WELCOME_TEMPLATE.render(), "<welcome>", lambda: False    
        return PLACEHOLDER_TEMPLATE.render(name=name), "<placeholder>", lambda: False
Example #2
0
    def setup_templates(self):
        from geebaby.templates import bootstrap

        for obj in bootstrap.TEMPLATES:
            gb = Geebaby(**obj)
            stored = gb.similar_objects().get()
            if not stored:
                gb.put()
                self.response.out.write("Created %s.\n" % gb)
            elif self.request.get("reset"):
                gb = Geebaby(key=stored.key(), **obj)
                gb.put()
                self.response.out.write("Overwrited %s.\n" % gb)
            else:
                self.response.out.write("Already exists: %s. Use ?reset=1 to overwrite.\n" % gb)
Example #3
0
def get_template(tags=[], entities=[], actions=[]):
    namespace = namespace_manager.get_namespace()
    
    tags = tags[:]
    cache_key = tuple(tags)
    while tags:
        name = tags.pop()
        fullname = '%s:%s/%s.html' % (namespace, '/'.join(tags), name)        
        t = CACHE.get(cache_key)
        if Geebaby.is_modified(['templates'] + tags, [name]):
            t = None
        if not t:
            try:
                t = CACHE[cache_key] = jinjaenv.get_template(fullname)
            except TemplateNotFound:
                pass
        if t and not t.filename == "<placeholder>":
            return t
    
    fullname = '%s:default.html' % namespace
    t = CACHE[cache_key] = jinjaenv.get_template(fullname)
    return t
Example #4
0
 def uptodate():
     return not Geebaby.is_modified(tags, entity)
Example #5
0
    def Get(self):
        write = self.response.out.write
        uri = "http://%s%s?%s" % (os.environ["SERVER_NAME"], os.environ["PATH_INFO"], os.environ["QUERY_STRING"])
        tags, entities, actions = uri2tea(uri)

        self.request.tags = tags
        self.request.entities = entities
        self.request.actions = actions
        
        if not "edit" in actions and ("py" in actions or "css" in actions):
            # handle with care
            
            gb = Geebaby.get_objects(tags, entities).fetch(1)
            if gb:
                typ = "text/plain"
                if "css" in actions:
                    typ = "text/css"
                self.response.headers["Content-Type"] = "text/css"
                write(getattr(gb[0], 'text', ''))
            else:
                self.error(404)
        
        elif "xml" in actions:
            from geebaby.handlers import feeds
            objects = Geebaby.get_objects(tags, entities)
            xml = feeds.render_template(tags=tags, actions=actions, entities=entities, objects=objects, request=self.request)
            write(xml)
            
        elif "app" in actions or ("json" in actions and "apps" in tags):
            name = None
            try:
                if "apps" not in tags:
                    # import global app
                    name = "apps.global.%s" % entities[0]
                    mod = __import__(name, globals=globals(), fromlist=[None])
                else:
                    # import app based on tags
                    name = '.'.join(tags + entities)
                    mod = __import__(name, globals=globals(), fromlist=[None])
                    
                if 'refresh' in self.request.params:
                    reload(mod)
                
                mod.request = self.request
                mod.response = self.response
                if 'json' in actions:
                    mod.write = lambda x: logging.debug("%s:%s" % (mod.__file__, x))
                else:
                    mod.write = write
                
                result = mod.main()
                if 'json' in actions:
                    from django.utils import simplejson
                    json = simplejson.dumps(result)
                    self.response.headers["Content-Type"] = "text/plain"
                    
                    if "callback" in self.request.params:
                        write("%s(%s)" % (self.request.params["callback"], json))
                    else:
                        write(json)
            except:
                import traceback
                text = traceback.format_exc()
                write(render_string(
                  "<h2>[Error] {{ name }}</h2><pre>{{text|e}}</pre>",
                  name=name, text=text))
        else:
            objects = Geebaby.get_objects(tags, entities)
            html = render_template(tags, entities, actions, objects=objects, request=self.request)
            write(html)            
Example #6
0
    def Post(self):
        text = self.request.params['geebaby_text']
            
        #log.debug(repr(text))
        #log.debug(str(text))
        
        uri = "http://%s%s?%s" % (os.environ["SERVER_NAME"], os.environ["PATH_INFO"], os.environ["QUERY_STRING"])
        tags, entities, actions = uri2tea(uri)
        
        soup = soupmagic.BeautifulSoup(text.replace(u"\xa0", " "))
        objects = soup.findAll(attrs={'class': lambda x: x and 'geebaby' in x.split()})
        
        if len(objects) == 1 and not objects[0].get("id"):
            # new object
            gb_list = [Geebaby()]
        else:
            # existing objects
            gb_list = db.get(obj.get("id") for obj in objects[:1]) 
        
        for i, gb in enumerate(gb_list):
            if not gb:
                gb = Geebaby()

            obj = objects[i]
            #log.debug("obj:%s gb:%s" % (obj.get("id"), gb.key()))
            
            attributes = {}
            if actions:
                attributes['text__type'] = actions[0]
            for x in obj.findAll(attrs={'class': lambda x: x and x.split()[0] == 'x'}):
                value = x.renderContents(encoding=None)
                parts = x["class"].split()
                key = parts[1].replace('-x', '')
                escaped = 'escaped' in parts[2:] 
                if escaped:
                    from HTMLParser import HTMLParser
                    value = soupmagic.BeautifulSoup(value)
                    #value = soupmagic.replace_tags(value, "br", "\n")
                    value = soupmagic.flatten(value)
                    value = HTMLParser().unescape(value)
                if x.name in ('ol', 'ul'):
                    value = filter(None, [soupmagic.flatten(t).strip() for t in x('li')])
                    
                
                if key not in attributes:
                    attributes[key] = value
                else:
                    attributes[key] += value
            
            if not attributes.get('name'):
                attributes['name'] = entities and entities[0]
            if not attributes.get('name'):
                from geebaby.utils.slugify import slugify_name
                attributes['name'] = slugify_name(attributes.get('title'))
            if not attributes.get('name'):
                from md5 import md5
                attributes['name'] = md5().hexdigest()
                        
            for key, value in attributes.items():
                if value != getattr(gb, key, None):
                    try:
                        setattr(gb, key, value)
                    except:
                        log.exception(key)
                        log.debug(repr(value))
                        raise
                    gb._changed = True
                
            if not gb.is_saved() or getattr(gb, '_changed', None):
                gb.put()
            else:
                log.debug("Not modified: %s" % gb)