Example #1
0
 def url_for(cls, tags=[], entities=[], actions=[], use_env=True):
     import os
     env_tags = []
     if use_env:
         env_tags, _, _ = uri2tea("http://%s/" % os.environ["SERVER_NAME"])
    
     host_tags = []
     path_tags = []
     for tag in tags:
         if tag in env_tags:
             host_tags.append(tag)
         else:
             path_tags.append(tag)
     
     path = ''
     if path_tags:
         path += '/'.join(path_tags)
         path += '/'
     if entities:
         path += entities[0]
     if actions:
         path += "."
         path += ".".join(actions)
     
     from geebaby.tags import geebaby_split_host
     sub, domain = geebaby_split_host(os.environ["SERVER_NAME"])
     
     port = ''
     if os.environ["SERVER_PORT"] != '80':
         port = ':%s' % os.environ["SERVER_PORT"]
     
     #url = "http://%s/%s" % ('.'.join(host_tags + domain) + port, path)
     url = "http://%s.%s/%s%s%s" % (
       tags and tags[0] or 'all',
       domain + port,
       '/'.join(tags[1:]) + (tags[1:] and '/' or ''),
       entities and entities[0] or '',
       actions and '.' + '.'.join(actions) or '',
     )
     
     return url
Example #2
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 #3
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)