Example #1
0
def view(section, param_string):
    params = [x.strip() for x in param_string.split(',')]
    try:
        try:
            scope, namespace, content_type, view = params[0:4]
        except:
            raise Exception('A minimum of four parameters required')
        else:
            params = params[4:] if len(params) > 4 else None

        if scope not in [content.SCOPE_GLOBAL, content.SCOPE_LOCAL]:
            raise Exception('Scope must be one of: ' +
                            str([content.SCOPE_GLOBAL, content.SCOPE_LOCAL]))
        elif ' ' in namespace:
            raise Exception('Invalid character " " for namespace')
        elif namespace == MAIN_CONTAINER_NAMESPACE:
            raise Exception('"%s" is a reserved namespace' %
                            MAIN_CONTAINER_NAMESPACE)
        item = content.get_local_else_global(section.path, namespace)
        if item and item.__class__.__name__ != content_type:
            raise Exception(
                'Selected namespace already exists for a different type of content'
            )
        elif not item:
            item = content.get_else_create(
                section.path if scope == content.SCOPE_LOCAL else None,
                content_type, namespace)
        return item.init(section).view(view, params)
    except Exception as inst:
        error = unicode(inst) + (
            '<div class="traceback">' +
            traceback.format_exc().replace('\n', '<br><br>') +
            '</div>') if configuration.debug_mode() else ''
        return '<div class="status error">Error: View "%s" does not exist: %s</div>' % (
            view, error)
Example #2
0
 def get(self, path):
     try:
         if path == '/robots.txt':
             return webapp2.Response(
                 template.get(configuration.get_robots_txt()))
         elif path == '/favicon.ico':
             return webapp2.Response(configuration.get_favicon_ico())
         else:
             response = webapp2.Response(
                 unicode(section.get_section(self, path)))
             response.headers['Connection'] = 'Keep-Alive'
             return response
     except Exception as inst:
         if inst[0] == 'Redirect':
             return self.redirect(str(inst[1]))
         elif inst[0] == 'SendFileBlob':
             response = webapp2.Response(inst[1])
             if inst[2]: response.content_type = str(inst[2])
             response.headers['Connection'] = 'Keep-Alive'
             response.headers['Date'] = datetime.utcnow().strftime(
                 "%a, %d %b %Y %H:%M:%S GMT")
             last_modified = datetime.utcnow(
             )  # TODO: Store when this actually happened
             response.headers['Last-Modified'] = last_modified.strftime(
                 "%a, %d %b %Y %H:%M:%S GMT")
             response.headers['Expires'] = (
                 last_modified +
                 timedelta(8)).strftime("%a, %d %b %Y %H:%M:%S GMT")
             response.cache_control.no_cache = None
             response.cache_control.public = True
             response.cache_control.max_age = 604800000  # One week
             return response
         elif inst[0] == 'NotFound':
             err = 404
             main = 'Page not found'
         elif inst[0] == 'BadRequest':
             err = 400
             main = 'Bad Request'
         elif inst[0] == 'Forbidden':
             err = 403
             main = 'Forbidden'
         elif inst[0] == 'AccessDenied':
             err = 403
             main = 'Access Denied'
         elif configuration.debug_mode():
             err = 400
             main = 'RouterError: ' + unicode(
                 inst) + '<div class="traceback">' + traceback.format_exc(
                 ).replace('\n', '<br><br>') + '</div>'
         else:
             err = 400
             main = 'An error has occurred.'
         default_section = section.get_section(None, '')
         response = webapp2.Response(
             unicode(
                 template.html(
                     default_section,
                     '<div class="status error">' + main + '</div>')))
         response.set_status(err)
         return response
Example #3
0
 def get(self, path):
     try:
         if path == '/robots.txt':
             return webapp2.Response(template.get(configuration.get_robots_txt()))
         elif path == '/favicon.ico':
             return webapp2.Response(configuration.get_favicon_ico())
         else:
             response = webapp2.Response(unicode(section.get_section(self, path)))
             response.headers['Connection'] = 'Keep-Alive'
             return response
     except Exception as inst:
         if inst[0] == 'Redirect':
             return self.redirect(str(inst[1]))
         elif inst[0] == 'SendFileBlob':
             response = webapp2.Response(inst[1])
             if inst[2]: response.content_type = str(inst[2])
             response.headers['Connection'] = 'Keep-Alive'
             response.headers['Date'] = datetime.utcnow().strftime("%a, %d %b %Y %H:%M:%S GMT")
             last_modified = datetime.utcnow() # TODO: Store when this actually happened
             response.headers['Last-Modified'] = last_modified.strftime("%a, %d %b %Y %H:%M:%S GMT")
             response.headers['Expires'] = (last_modified + timedelta(8)).strftime("%a, %d %b %Y %H:%M:%S GMT")
             response.cache_control.no_cache = None
             response.cache_control.public = True
             response.cache_control.max_age = 604800000 # One week
             return response
         elif inst[0] == 'NotFound':
             err = 404
             main = 'Page not found'
         elif inst[0] == 'BadRequest':
             err = 400
             main = 'Bad Request'
         elif inst[0] == 'Forbidden':
             err = 403
             main = 'Forbidden'
         elif inst[0] == 'AccessDenied':
             err = 403
             main = 'Access Denied'
         elif configuration.debug_mode():
             err = 400
             main = 'RouterError: ' + unicode(inst) + '<div class="traceback">' + traceback.format_exc().replace('\n', '<br><br>') + '</div>'
         else:
             err = 400
             main = 'An error has occurred.'
         default_section = section.get_section(None, '')
         response = webapp2.Response(unicode(template.html(default_section, '<div class="status error">' + main + '</div>')))
         response.set_status(err)
         return response
Example #4
0
                response.cache_control.public = True
                response.cache_control.max_age = 604800000 # One week
                return response
            elif inst[0] == 'NotFound':
                err = 404
                main = 'Page not found'
            elif inst[0] == 'BadRequest':
                err = 400
                main = 'Bad Request'
            elif inst[0] == 'Forbidden':
                err = 403
                main = 'Forbidden'
            elif inst[0] == 'AccessDenied':
                err = 403
                main = 'Access Denied'
            elif configuration.debug_mode():
                err = 400
                main = 'RouterError: ' + unicode(inst) + '<div class="traceback">' + traceback.format_exc().replace('\n', '<br><br>') + '</div>'
            else:
                err = 400
                main = 'An error has occurred.'
            default_section = section.get_section(None, '')
            response = webapp2.Response(unicode(template.html(default_section, '<div class="status error">' + main + '</div>')))
            response.set_status(err)
            return response

    def post(self, path):
        return self.get(path)

app = webapp2.WSGIApplication([('(/.*)', Router)], debug=configuration.debug_mode())
Example #5
0
    def get(self, path):     
        try:
            path = path.strip('/')
            path, extension = os.path.splitext(path)

            contents = cache.get(path + extension)
            last_modified = cache.get(CACHE_LAST_MODIFIED_PREPEND + path + extension)

            if not contents:
                contents = ''

                ''' YUI '''
                yui_parts = '' if path.find('___yui___') < 0 else path[path.find('___yui___'):].replace('___yui___', '', 1)
                yui_parts = yui_parts if yui_parts.find('___') < 0 else yui_parts[:yui_parts.find('___')]
                rest_parts = path.replace('___yui___', '', 1).replace(yui_parts, '', 1).replace('___local___', '', 1)
                if '___theme___' in rest_parts:
                    local_parts, theme_parts = rest_parts.split('___theme___')
                else:
                    local_parts, theme_parts = rest_parts, None
                if yui_parts:
                    yui_version = '3.7.2/build/'
                    yui_absolute = 'http://yui.yahooapis.com/combo?'
                    yui_parts = yui_parts.split('__')
                    yui_parts = [(yui_version + x.replace('_', '/') + '-min' + extension) for x in yui_parts]
                    result = urlfetch.fetch(yui_absolute + '&'.join(yui_parts))
                    if result.status_code == 200:
                        contents += result.content
                    else:
                        raise Exception('NotFound')

                ''' Local '''
                filenames = [(x + extension) for x in local_parts.split('_')]
                if len(filenames) != len(utils.unique_list(filenames)):
                    raise Exception('NotFound')
                files = utils.file_search(filenames)
                if extension == '.css':
                    contents += (''.join([parse_content(open(f, 'r').read(), True) for f in files]))
                else:
                    contents += (''.join([parse_content(open(f, 'r').read()) for f in files]))

                ''' Theme '''
                if theme_parts:
                    theme_namespace, theme_parts = theme_parts.split('___')
                    filenames = [(x + extension) for x in theme_parts.split('_')]
                    if len(filenames) != len(utils.unique_list(filenames)):
                        raise Exception('NotFound')
                    elif is_local_theme_namespace(theme_namespace):
                        if extension == '.css':
                            contents += (''.join([parse_content(open('./themes/' + theme_namespace + '/' + extension.strip('.') + '/' + f, 'r').read(), True, theme_namespace) for f in filenames]))
                        else:
                            contents += (''.join([parse_content(open('./themes/' + theme_namespace + '/' + extension.strip('.') + '/' + f, 'r').read(), False, theme_namespace) for f in filenames]))
                    else:
                        t = get_custom_theme(theme_namespace)
                        for f in filenames:
                            if extension == '.css':
                                index = t.css_filenames.index(f)
                                contents += parse_content(t.css_contents[index], True, theme_namespace)
                            elif extension == '.js':
                                index = t.js_filenames.index(f)
                                contents += parse_content(t.js_contents[index], False, theme_namespace)

                cache.set(path + extension, contents)
                last_modified = datetime.utcnow()
                cache.set(CACHE_LAST_MODIFIED_PREPEND + path + extension, last_modified)

            if not contents.strip(): raise Exception('NotFound')

            if not last_modified:
                last_modified = datetime.utcnow()
                cache.set(CACHE_LAST_MODIFIED_PREPEND + path + extension, last_modified)

            content_type = 'application/javascript' if extension == '.js' else 'text/css'
            response = webapp2.Response(template.get(contents.strip()), content_type=content_type)
            response.headers['Connection'] = 'Keep-Alive'
            response.headers['Date'] = datetime.utcnow().strftime("%a, %d %b %Y %H:%M:%S GMT")
            response.headers['Last-Modified'] = last_modified.strftime("%a, %d %b %Y %H:%M:%S GMT")
            response.headers['Expires'] = (last_modified + timedelta(8)).strftime("%a, %d %b %Y %H:%M:%S GMT")
            response.cache_control.no_cache = None
            response.cache_control.public = True
            response.cache_control.max_age = 604800000 # One week
            return response
        except Exception as inst:
            message = ''
            if configuration.debug_mode():
                message = '<div class="status error">' + unicode(inst) + '<br><br>' + traceback.format_exc().replace('\n', '<br><br>') + '</div>'
            response = webapp2.Response(template.get('<html><head><title>404 Not Found</title></head><body><h1>404 Not Found</h1>Document or file requested by the client was not found.%s</body></html>' % message))
            response.set_status(404)
            return response
Example #6
0
                main = 'Bad Request'
            elif inst[0] == 'Forbidden':
                err = 403
                main = 'Forbidden'
            elif inst[0] == 'AccessDenied':
                err = 403
                main = 'Access Denied'
            elif configuration.debug_mode():
                err = 400
                main = 'RouterError: ' + unicode(
                    inst) + '<div class="traceback">' + traceback.format_exc(
                    ).replace('\n', '<br><br>') + '</div>'
            else:
                err = 400
                main = 'An error has occurred.'
            default_section = section.get_section(None, '')
            response = webapp2.Response(
                unicode(
                    template.html(
                        default_section,
                        '<div class="status error">' + main + '</div>')))
            response.set_status(err)
            return response

    def post(self, path):
        return self.get(path)


app = webapp2.WSGIApplication([('(/.*)', Router)],
                              debug=configuration.debug_mode())
Example #7
0
def view(section, param_string):
    params = [x.strip() for x in param_string.split(',')]
    try:
        try:
            scope, namespace, content_type, view = params[0:4]
        except:
            raise Exception('A minimum of four parameters required')
        else:
            params = params[4:] if len(params) > 4 else None

        if scope not in [content.SCOPE_GLOBAL, content.SCOPE_LOCAL]:
            raise Exception('Scope must be one of: ' + str([content.SCOPE_GLOBAL, content.SCOPE_LOCAL]))
        elif ' ' in namespace:
            raise Exception('Invalid character " " for namespace')
        elif namespace == MAIN_CONTAINER_NAMESPACE:
            raise Exception('"%s" is a reserved namespace' % MAIN_CONTAINER_NAMESPACE)
        item = content.get_local_else_global(section.path, namespace)
        if item and item.__class__.__name__ != content_type:
            raise Exception('Selected namespace already exists for a different type of content')
        elif not item:
            item = content.get_else_create(section.path if scope == content.SCOPE_LOCAL else None, content_type, namespace)
        return item.init(section).view(view, params)
    except Exception as inst:
        error = unicode(inst) + ('<div class="traceback">' + traceback.format_exc().replace('\n', '<br><br>') + '</div>') if configuration.debug_mode() else ''
        return '<div class="status error">Error: View "%s" does not exist: %s</div>' % (view, error)
Example #8
0
    def get(self, path):
        try:
            path = path.strip('/')
            path, extension = os.path.splitext(path)

            contents = cache.get(path + extension)
            last_modified = cache.get(CACHE_LAST_MODIFIED_PREPEND + path +
                                      extension)

            if not contents:
                contents = ''
                ''' YUI '''
                yui_parts = '' if path.find('___yui___') < 0 else path[
                    path.find('___yui___'):].replace('___yui___', '', 1)
                yui_parts = yui_parts if yui_parts.find(
                    '___') < 0 else yui_parts[:yui_parts.find('___')]
                rest_parts = path.replace('___yui___', '', 1).replace(
                    yui_parts, '', 1).replace('___local___', '', 1)
                if '___theme___' in rest_parts:
                    local_parts, theme_parts = rest_parts.split('___theme___')
                else:
                    local_parts, theme_parts = rest_parts, None
                if yui_parts:
                    yui_version = '3.7.2/build/'
                    yui_absolute = 'http://yui.yahooapis.com/combo?'
                    yui_parts = yui_parts.split('__')
                    yui_parts = [(yui_version + x.replace('_', '/') + '-min' +
                                  extension) for x in yui_parts]
                    result = urlfetch.fetch(yui_absolute + '&'.join(yui_parts))
                    if result.status_code == 200:
                        contents += result.content
                    else:
                        raise Exception('NotFound')
                ''' Local '''
                filenames = [(x + extension) for x in local_parts.split('_')]
                if len(filenames) != len(utils.unique_list(filenames)):
                    raise Exception('NotFound')
                files = utils.file_search(filenames)
                if extension == '.css':
                    contents += (''.join([
                        parse_content(open(f, 'r').read(), True) for f in files
                    ]))
                else:
                    contents += (''.join(
                        [parse_content(open(f, 'r').read()) for f in files]))
                ''' Theme '''
                if theme_parts:
                    theme_namespace, theme_parts = theme_parts.split('___')
                    filenames = [(x + extension)
                                 for x in theme_parts.split('_')]
                    if len(filenames) != len(utils.unique_list(filenames)):
                        raise Exception('NotFound')
                    elif is_local_theme_namespace(theme_namespace):
                        if extension == '.css':
                            contents += (''.join([
                                parse_content(
                                    open(
                                        './themes/' + theme_namespace + '/' +
                                        extension.strip('.') + '/' + f,
                                        'r').read(), True, theme_namespace)
                                for f in filenames
                            ]))
                        else:
                            contents += (''.join([
                                parse_content(
                                    open(
                                        './themes/' + theme_namespace + '/' +
                                        extension.strip('.') + '/' + f,
                                        'r').read(), False, theme_namespace)
                                for f in filenames
                            ]))
                    else:
                        t = get_custom_theme(theme_namespace)
                        for f in filenames:
                            if extension == '.css':
                                index = t.css_filenames.index(f)
                                contents += parse_content(
                                    t.css_contents[index], True,
                                    theme_namespace)
                            elif extension == '.js':
                                index = t.js_filenames.index(f)
                                contents += parse_content(
                                    t.js_contents[index], False,
                                    theme_namespace)

                cache.set(path + extension, contents)
                last_modified = datetime.utcnow()
                cache.set(CACHE_LAST_MODIFIED_PREPEND + path + extension,
                          last_modified)

            if not contents.strip(): raise Exception('NotFound')

            if not last_modified:
                last_modified = datetime.utcnow()
                cache.set(CACHE_LAST_MODIFIED_PREPEND + path + extension,
                          last_modified)

            content_type = 'application/javascript' if extension == '.js' else 'text/css'
            response = webapp2.Response(template.get(contents.strip()),
                                        content_type=content_type)
            response.headers['Connection'] = 'Keep-Alive'
            response.headers['Date'] = datetime.utcnow().strftime(
                "%a, %d %b %Y %H:%M:%S GMT")
            response.headers['Last-Modified'] = last_modified.strftime(
                "%a, %d %b %Y %H:%M:%S GMT")
            response.headers['Expires'] = (
                last_modified +
                timedelta(8)).strftime("%a, %d %b %Y %H:%M:%S GMT")
            response.cache_control.no_cache = None
            response.cache_control.public = True
            response.cache_control.max_age = 604800000  # One week
            return response
        except Exception as inst:
            message = ''
            if configuration.debug_mode():
                message = '<div class="status error">' + unicode(
                    inst) + '<br><br>' + traceback.format_exc().replace(
                        '\n', '<br><br>') + '</div>'
            response = webapp2.Response(
                template.get(
                    '<html><head><title>404 Not Found</title></head><body><h1>404 Not Found</h1>Document or file requested by the client was not found.%s</body></html>'
                    % message))
            response.set_status(404)
            return response