Ejemplo n.º 1
0
    def load_current_model(self):
        model = self.get_model_name()
        current_model = {}
        current_model['name'] = get_package_name()
        current_model['models'] = {}
        current_model['ordered_models'] = []

        for m in dir(model):
            if m in ('SQLObject', 'InheritableSQLObject'):
                continue
            model_object = getattr(model, m)
            if isinstance(model_object, type) and issubclass(
                    model_object, sqlobject.SQLObject):
                parent_class = 'SQLObject'
                if model_object._inheritable:
                    parent_class = model_object._parentClass.__name__
                columns = self.load_columns(model_object)
                current_model['ordered_models'].append(m)
                current_model['models'][m] = {
                    'name': m,
                    'parent_class': parent_class,
                    'table_name': model_object.sqlmeta.table,
                    'id_name': model_object.sqlmeta.idName,
                    'columns': columns,
                    'relations': {}}
        return dict(model=current_model)
Ejemplo n.º 2
0
    def load_current_model(self):
        model = self.get_model_name()
        current_model = {}
        current_model['name'] = get_package_name()
        current_model['models'] = {}
        current_model['ordered_models'] = []

        for m in dir(model):
            if m in ('SQLObject', 'InheritableSQLObject'):
                continue
            model_object = getattr(model, m)
            if isinstance(model_object, type) and issubclass(
                    model_object, sqlobject.SQLObject):
                parent_class = 'SQLObject'
                if model_object._inheritable:
                    parent_class = model_object._parentClass.__name__
                columns = self.load_columns(model_object)
                current_model['ordered_models'].append(m)
                current_model['models'][m] = {
                    'name': m,
                    'parent_class': parent_class,
                    'table_name': model_object.sqlmeta.table,
                    'id_name': model_object.sqlmeta.idName,
                    'columns': columns,
                    'relations': {}
                }
        return dict(model=current_model)
Ejemplo n.º 3
0
 def __call__(self, locale):
     if not self._initialized:
         # the leading underscore is to prevent shadowing of the
         # register_package_provider-arguments
         if package is None:
             _package = get_package_name()
         else:
             _package = package
         if directory is None:
             _directory = "static/javascript"
         else:
             _directory = directory
         if domain is None:
             _domain = config.get('i18n.domain', 'messages')
         else:
             _domain = domain
         js_dir = pkg_resources.resource_filename(_package, _directory)
         register_static_directory(_package, js_dir)
         self._package_name = _package
         self._domain = _domain
         self._initialized = True
     js = []
     for l in locale, locale[:2]:
         link = JSLink(self._package_name, "%s-%s.js" % (self._domain, l))
         if parent.linked_file_exists(link):
             js.append(link)
             break
     return js
Ejemplo n.º 4
0
def get_locale_dir():
    localedir = config.get("i18n.locale_dir")
    if not localedir:
        package = get_package_name()
        if package:
            localedir = os.path.join(os.path.dirname(sys.modules[package].__path__[0]), "locales")
    return localedir
Ejemplo n.º 5
0
 def __call__(self, locale):
     if not self._initialized:
         # the leading underscore is to prevent shadowing of the
         # register_package_provider-arguments
         if package is None:
             _package = get_package_name()
         else:
             _package = package
         if directory is None:
             _directory = "static/javascript"
         else:
             _directory = directory
         if domain is None:
             _domain = config.get('i18n.domain', 'messages')
         else:
             _domain = domain
         js_dir = pkg_resources.resource_filename(
             _package, _directory)
         register_static_directory(_package, js_dir)
         self._package_name = _package
         self._domain = _domain
         self._initialized = True
     js = []
     for l in locale, locale[:2]:
         link = JSLink(self._package_name,
                       "%s-%s.js" % (self._domain, l))
         if parent.linked_file_exists(link):
             js.append(link)
             break
     return js
Ejemplo n.º 6
0
 def run(self):
     # auto detect package name
     from turbogears.util import get_package_name
     self.package_name = get_package_name()
     # the main script
     p = Packager()
     p.make_package(self.package_name)         
Ejemplo n.º 7
0
def get_locale_dir():
    localedir = config.get("i18n.locale_dir")
    if not localedir:
        package = get_package_name()
        if package:
            localedir = os.path.join(
                os.path.dirname(sys.modules[package].__path__[0]), "locales")
    return localedir
Ejemplo n.º 8
0
    def scan_source_files(self):
        source_files = []
        kid_files = []
        genshi_files = []
        js_files = []
        srcdir = self.options.source_dir or get_package_name().split(".", 1)[0]
        print "Scanning source directory", srcdir
        for root, dirs, files in os.walk(srcdir):
            if os.path.basename(root).lower() in ("cvs", ".svn"):
                continue
            for fname in files:
                name, ext = os.path.splitext(fname)
                srcfile = os.path.join(root, fname)
                if ext == ".py":
                    source_files.append(srcfile)
                elif ext == ".kid":
                    kid_files.append(srcfile)
                elif ext == ".html":
                    genshi_files.append(srcfile)
                elif ext == ".js":
                    js_files.append(srcfile)
                else:
                    pass  # do nothing
        tmp_handle, tmp_potfile = tempfile.mkstemp(".pot", "tmp", self.locale_dir)
        os.close(tmp_handle)
        potbasename = os.path.basename(tmp_potfile)[:-4]
        pygettext_options = ["-v", "-d", potbasename, "-p", os.path.dirname(tmp_potfile)]
        if self.options.ascii_output:
            pygettext_options.insert(0, "-E")
        pygettext.sys.argv = [""] + pygettext_options + source_files
        pygettext.main()
        if not os.path.exists(tmp_potfile):
            raise ProgramError("pygettext failed")
        atexit.register(silent_os_remove, tmp_potfile)

        if kid_files and self.options.kid_support:
            if not kid:
                print "Kid not installed, no support for Kid templates."
            else:
                self.scan_kid_files(tmp_potfile, kid_files)

        if genshi_files and self.options.genshi_support:
            try:
                self.scan_genshi_files(tmp_potfile, genshi_files)
            except ImportError:
                print "Genshi not installed, no support for Genshi templates."

        if js_files and self.options.js_support:
            self.scan_js_files(tmp_potfile, js_files)

        potfile = self.get_potfile_path()
        if os.path.isfile(potfile):
            bakfile = potfile.replace(".pot", ".bak")
            silent_os_remove(bakfile)
            os.rename(potfile, bakfile)
            print "Backup existing file to", bakfile
        os.rename(tmp_potfile, potfile)
        print "Message templates written to", potfile
Ejemplo n.º 9
0
 def save_model(self, code):
     project_name = get_package_name()
     model_text = model_template % (project_name, code)
     model_path = self.model_path()
     if os.path.exists(model_path):
         version_file(model_path)
         f = open(model_path,'w')
         f.write(model_text)
         f.close()
         return True, 'Saved %s' % model_path
     else:
         return False, 'Failed to save %s' % model_path
Ejemplo n.º 10
0
 def save_model(self, code):
     project_name = get_package_name()
     model_text = model_template % (project_name, code)
     model_path = self.model_path()
     if os.path.exists(model_path):
         version_file(model_path)
         f = open(model_path, 'w')
         f.write(model_text)
         f.close()
         return True, 'Saved %s' % model_path
     else:
         return False, 'Failed to save %s' % model_path
Ejemplo n.º 11
0
 def save_and_create_(self, code, order):
     model_path = os.path.join(get_project_name(), 'tmp2_model.py')
     model_path = os.path.abspath(model_path)
     open(model_path, 'w').write(str)
     package = __import__(get_package_name(), {}, {}, ["tmp2_model"])
     package.tmp2_model.Persona.createTable(ifNotExists=True)
     model = self.get_model_name()
     model.Persona = package.tmp2_model.Persona
     # pk = package.model
     # import tmp_model as pk
     # pk.Persona.createTable(ifNotExists=True)
     return dict(status='Tables ok')
Ejemplo n.º 12
0
 def save_and_create_(self, code, order):
     model_path = os.path.join(get_project_name(), 'tmp2_model.py')
     model_path = os.path.abspath(model_path)
     open(model_path, 'w').write(str)
     package = __import__(get_package_name(), {}, {}, ['tmp2_model'])
     package.tmp2_model.Persona.createTable(ifNotExists=True)
     model = self.get_model_name()
     model.Persona = package.tmp2_model.Persona
     # pk = package.model
     # import tmp_model as pk
     # pk.Persona.createTable(ifNotExists=True)
     return dict(status='Tables ok')
Ejemplo n.º 13
0
    def run(self):
        from turbogears.toolbox.catwalk import CatWalk
        import cherrypy
        from turbogears import toolbox

        try:
            if get_package_name():
                conf = turbogears.config.config_obj( configfile = self.config,
                        modulename="%s.config" % get_package_name() )
            else:
                conf = turbogears.config.config_obj( configfile = self.config )
            
            new_conf = {}
            for key in ( "sqlobject.dburi", "sqlalchemy.dburi", "visit.on", "visit.manager", "visit.saprovider.model", 
                    "identity.provider", "identity.saprovider.model.group", "identity.saprovider.model.permission",
                    "identity.saprovider.model.user", "identity.saprovider.model.visit", "identity.on"):
                new_conf[key] = conf.get("global").get(key, None) 
            turbogears.config.update({"global" : new_conf})

        except AttributeError, e:
            pass
Ejemplo n.º 14
0
 def scan_source_files(self):
     source_files = []
     kid_files = []
     js_files = []
     srcdir = self.options.source_dir or get_package_name().split('.', 1)[0]
     print 'Scanning source directory', srcdir
     for root, dirs, files in os.walk(srcdir):
         if os.path.basename(root).lower() in ('cvs', '.svn'):
             continue
         for fname in files:
             name, ext = os.path.splitext(fname)
             srcfile = os.path.join(root, fname)
             if ext == '.py':
                 source_files.append(srcfile)
             elif ext == '.kid':
                 kid_files.append(srcfile)
             elif ext == '.js':
                 js_files.append(srcfile)
             else:
                 pass  # do nothing
     tmp_handle, tmp_potfile = tempfile.mkstemp('.pot', 'tmp',
                                                self.locale_dir)
     os.close(tmp_handle)
     potbasename = os.path.basename(tmp_potfile)[:-4]
     pygettext_options = ['-v', '-d', potbasename, \
             '-p', os.path.dirname(tmp_potfile)]
     if self.options.ascii_output:
         pygettext_options.insert(0, '-E')
     pygettext.sys.argv = [''] + pygettext_options + source_files
     pygettext.main()
     if not os.path.exists(tmp_potfile):
         raise ProgramError, 'pygettext failed'
     atexit.register(silent_os_remove, tmp_potfile)
     if kid_files and self.options.kid_support:
         self.scan_kid_files(tmp_potfile, kid_files)
     if js_files and self.options.js_support:
         self.scan_js_files(tmp_potfile, js_files)
     potfile = self.get_potfile_path()
     if os.path.isfile(potfile):
         bakfile = potfile.replace('.pot', '.bak')
         silent_os_remove(bakfile)
         os.rename(potfile, bakfile)
         print 'Backup existing file to', bakfile
     os.rename(tmp_potfile, potfile)
     print 'Message templates written to', potfile
Ejemplo n.º 15
0
 def scan_source_files(self):
     source_files = []
     kid_files = []
     js_files = []
     srcdir = self.options.source_dir or get_package_name().split('.', 1)[0]
     print 'Scanning source directory', srcdir
     for root, dirs, files in os.walk(srcdir):
         if os.path.basename(root).lower() in ('cvs', '.svn'):
             continue
         for fname in files:
             name, ext = os.path.splitext(fname)
             srcfile = os.path.join(root, fname)
             if ext == '.py':
                 source_files.append(srcfile)
             elif ext == '.kid':
                 kid_files.append(srcfile)
             elif ext == '.js':
                 js_files.append(srcfile)
             else:
                 pass # do nothing
     tmp_handle, tmp_potfile = tempfile.mkstemp(
         '.pot', 'tmp', self.locale_dir)
     os.close(tmp_handle)
     potbasename = os.path.basename(tmp_potfile)[:-4]
     pygettext_options = ['-v', '-d', potbasename, \
             '-p', os.path.dirname(tmp_potfile)]
     if self.options.ascii_output:
         pygettext_options.insert(0, '-E')
     pygettext.sys.argv = [''] + pygettext_options + source_files
     pygettext.main()
     if not os.path.exists(tmp_potfile):
         raise ProgramError, 'pygettext failed'
     atexit.register(silent_os_remove, tmp_potfile)
     if kid_files and self.options.kid_support:
         self.scan_kid_files(tmp_potfile, kid_files)
     if js_files and self.options.js_support:
         self.scan_js_files(tmp_potfile, js_files)
     potfile = self.get_potfile_path()
     if os.path.isfile(potfile):
         bakfile = potfile.replace('.pot', '.bak')
         silent_os_remove(bakfile)
         os.rename(potfile, bakfile)
         print 'Backup existing file to', bakfile
     os.rename(tmp_potfile, potfile)
     print 'Message templates written to', potfile
Ejemplo n.º 16
0
    def run(self):
        import cherrypy
        from turbogears import toolbox

        # Make sure we have full configuration with every option
        # in it so other plugins or whatever find what they need
        # when starting even inside the toolblox
        conf = get_package_name()
        conf = conf and "%s.config" % conf or None
        conf = config.config_obj(configfile=self.config, modulename=conf)

        if 'global' in conf:
            config.update({'global': conf['global']})

        root = SecureObject(toolbox.Toolbox(), from_any_host(self.hostlist),
                exclude=['noaccess'])

        cherrypy.tree.mount(root, '/')

        # amend some parameters since we are running from the command
        # line in order to change port, log methods...
        config.update({'global': {
            'server.socket_port': self.port,
            'server.webpath': '/',
            'server.environment': 'development',
            'server.log_to_screen': True,
            'autoreload.on': False,
            'server.package': 'turbogears.toolbox',
            'log_debug_info_filter.on': False,
            'identity.failure_url': '/noaccess',
            'identity.force_external_redirect': False,
            'tg.strict_parameters': False,
            'tg.defaultview': 'genshi',
            'genshi.default_doctype': 'html',
            'genshi.default_encoding': 'utf-8',
            'kid.outputformat': 'html default',
            'kid.encoding': 'utf-8'
            }})

        if self.noopen:
            cherrypy.server.start()
        else:
            cherrypy.server.start_with_callback(self.openbrowser)
Ejemplo n.º 17
0
    def run(self):
        import cherrypy
        from turbogears import toolbox

        # Make sure we have full configuration with every option
        # in it so other plugins or whatever find what they need
        # when starting even inside the toolblox
        conf = get_package_name()
        conf = conf and "%s.config" % conf or None
        conf = config.config_obj(configfile=self.config, modulename=conf)

        if 'global' in conf:
            config.update({'global': conf['global']})

        root = SecureObject(toolbox.Toolbox(), from_any_host(self.hostlist),
                exclude=['noaccess'])

        cherrypy.tree.mount(root, "/")

        # amend some parameters since we are running from the command
        # line in order to change port, log methods...
        config.update({'global': {
            'server.socket_port': self.port,
            'server.webpath': '/',
            'server.environment': 'development',
            'server.log_to_screen': True,
            'autoreload.on': False,
            'server.package': 'turbogears.toolbox',
            'log_debug_info_filter.on': False,
            'identity.failure_url': '/noaccess',
            'identity.force_external_redirect': False,
            'tg.defaultview': 'kid',
            'tg.strict_parameters': False,
            'kid.outputformat': 'html default',
            'kid.encoding': 'utf-8'
            }})

        if not self.noopen:
            cherrypy.server.start_with_callback(self.openbrowser)
        else:
            cherrypy.server.start()
Ejemplo n.º 18
0
    def create_js_messages(self):
        self.load_project_config()
        languages = []
        # we assume the the structure of messages is always
        # <self.locale_dir>/<lang>/LC_MESSAGES ...
        # to extract the languages known to the app
        locale_dir_prefix = self.locale_dir.split(os.sep)
        for fname in self.list_message_catalogs():
            languages.append(fname.split(os.sep)[len(locale_dir_prefix):][0])
        import turbogears.i18n.utils as utils
        srcdir = self.options.source_dir or get_package_name().split('.', 1)[0]

        def list_js_files():
            for root, dirs, files in os.walk(srcdir):
                if os.path.basename(root).lower() in ('cvs', '.svn'):
                    continue
                for fname in files:
                    name, ext = os.path.splitext(fname)
                    srcfile = os.path.join(root, fname)
                    if ext == '.js':
                        yield srcfile

        def escape(arg):
            if "'" in arg:
                return '"%s"' % arg
            return "'%s'" % arg

        for locale in languages:

            def gl():
                return locale

            utils._get_locale = gl
            messages = []
            for filename in list_js_files():
                for key in self.get_strings_in_js(os.path.join(filename))[0]:
                    key = unicode(key)
                    msg = unicode(_(key, locale))
                    messages.append((key, msg))
            # for a final return
            header = """
if (typeof(MESSAGES) == "undefined") {
    MESSAGES = {};
}

LANG = '%s';
_messages = [
""" % locale
            footer = """
             ];

for(var i in _messages) {
  MESSAGES[_messages[i][0]] = _messages[i][1];
 }
"""
            message_block = u",\n".join([
                "[%s , %s]" % (escape(msgid), escape(msgstr))
                for msgid, msgstr in messages
            ]).encode("utf-8")
            message_block = message_block + "\n"
            outfilename = os.path.join(srcdir, self.options.js_base_dir,
                                       'messages-%s.js' % locale)
            print "Creating message file <%s>." % outfilename
            mf = open(outfilename, "w")
            mf.write(header)
            mf.write(message_block)
            mf.write(footer)
            mf.close()
Ejemplo n.º 19
0
    def create_js_messages(self):
        self.load_project_config()
        languages = []
        # we assume the the structure of messages is always
        # <self.locale_dir>/<lang>/LC_MESSAGES ...
        # to extract the languages known to the app
        locale_dir_prefix = self.locale_dir.split(os.sep)
        for fname in self.list_message_catalogs():
            languages.append(fname.split(os.sep)[len(locale_dir_prefix) :][0])
        import turbogears.i18n.utils as utils

        srcdir = self.options.source_dir or get_package_name().split(".", 1)[0]

        def list_js_files():
            for root, dirs, files in os.walk(srcdir):
                if os.path.basename(root).lower() in ("cvs", ".svn"):
                    continue
                for fname in files:
                    name, ext = os.path.splitext(fname)
                    srcfile = os.path.join(root, fname)
                    if ext == ".js":
                        yield srcfile

        def escape(arg):
            if "'" in arg:
                return '"%s"' % arg
            return "'%s'" % arg

        for locale in languages:

            def gl():
                return locale

            utils._get_locale = gl
            messages = []
            for filename in list_js_files():
                for key in self.get_strings_in_js(os.path.join(filename))[0]:
                    key = unicode(key)
                    msg = unicode(_(key, locale))
                    messages.append((key, msg))
            # for a final return
            header = (
                """
if (typeof(MESSAGES) == "undefined") {
    MESSAGES = {};
}

LANG = '%s';
_messages = [
"""
                % locale
            )
            footer = """
             ];

for(var i in _messages) {
  MESSAGES[_messages[i][0]] = _messages[i][1];
 }
"""
            message_block = u",\n".join(
                ["[%s , %s]" % (escape(msgid), escape(msgstr)) for msgid, msgstr in messages]
            ).encode("utf-8")
            message_block = message_block + "\n"
            outfilename = os.path.join(srcdir, self.options.js_base_dir, "messages-%s.js" % locale)
            print "Creating message file <%s>." % outfilename
            mf = open(outfilename, "w")
            mf.write(header)
            mf.write(message_block)
            mf.write(footer)
            mf.close()
Ejemplo n.º 20
0
class Designer(controllers.RootController):
    """Designer for SQLObject models.

    Create your classes, define your fields and manage your relations.
    Visualize and generate code for SQLObject models.

    """

    __label__ = "ModelDesigner"
    __version__ = "0.1"
    __author__ = "Ronald Jaramillo"
    __email__ = "*****@*****.**"
    __copyright__ = "Copyright 2005 Ronald Jaramillo"
    __license__ = "MIT"

    baseTemplate = 'turbogears.toolbox.designer'
    model = None
    icon = "/tg_static/images/designer.png"

    def __init__(self):
        if not sqlobject:
            raise ImportError, ("Cannot run the Model Designer.\n"
                                "The SQLObject package is not installed.")

    def set_model(self, model):
        self.model = model

    def get_model_name(self):
        if not get_project_name():
            return False
        return get_model()

    def register_static_directory(self):
        static_directory = pkg_resources.resource_filename(__name__, 'static')
        turbogears.config.update({
            '/tg_toolbox/designer': {
                'static_filter.on': True,
                'static_filter.dir': static_directory
            }
        })

    def column_type(self, column):
        """Given a column representation return the column type."""
        column_type = '%r' % column
        return column_type.split()[0][1:].split('.')[-1]

    def column_default(self, column, column_type):
        try:
            default = column.default
        except AttributeError:
            return ''
        if default == sqlobject.sqlbuilder.NoDefault:
            return ''
        if column_type in ('SOIntCol', 'SOFloatCol', 'SOStringCol',
                           'SODecimalCol', 'SOCurrencyCol'):
            return default
        elif column_type == 'SODateTimeCol':
            d = '%s' % default
            return ':'.join(d.split(':')[:-1])
        elif column_type == 'SODateCol':
            d = '%s' % default
            return d.split()[0]
        return ''

    def load_column(self, column_name, column, model_object):
        props = {}
        props['type'] = self.column_type(column)
        props['column_name'] = column_name
        props['name'] = column_name
        props['column_default'] = self.column_default(column, props['type'])
        try:
            props['title'] = getattr(column, 'title') or ''
        except AttributeError:
            props['title'] = ''
        if props['type'] == 'SOStringCol':
            props['length'] = column.length
            props['varchar'] = column.varchar
        if props['type'] == 'SOEnumCol':
            props['enum_values'] = column.enumValues
        if props['type'] == 'SOForeignKey':
            props['join_type'] = 'MultipleJoin'
            props['other_class_name'] = column.foreignKey
            props['other_method_name'] = self.other_method_name(
                column, model_object.__name__)
        if props['type'] in ('SOMultipleJoin', 'SORelatedJoin'):
            props['other_class_name'] = column.otherClassName
            props['join_type'] = props['type'].replace('SO', '')
            props['other_method_name'] = self.other_method_join_name(
                column, model_object.__name__)

        props['type'] = props['type'].replace('SO', '')
        return props

    def other_method_join_name(self, column, model_object_name):
        for col in column.otherClass.sqlmeta.columnList:
            if type(col) == sqlobject.SOForeignKey:
                if col.foreignKey == model_object_name:
                    return col.origName
        return 'id'

    def other_method_name(self, column, model_object_name):
        other_class_name = column.foreignKey
        model_object = getattr(self.get_model_name(), other_class_name)
        for col in model_object.sqlmeta.joins:
            if col.otherClassName == model_object_name:
                return col.joinMethodName
        return 'id'

    def is_inheritable_base_class(self, obj):
        """Check if the object is  a direct subclass of InheritableSQLObject"""
        return 'sqlobject.inheritance.InheritableSQLObject' in str(
            obj.__bases__)

    def load_columns(self, model_object):
        columns = {}
        # get normal columns
        for column_name in model_object.sqlmeta.columns:
            column = model_object.sqlmeta.columns[column_name]
            origname = column.origName
            if model_object._inheritable and column_name == 'childName':
                continue
            columns[origname] = self.load_column(origname, column,
                                                 model_object)
        # get join columns
        for column in model_object.sqlmeta.joins:
            columns[column.joinMethodName] = self.load_column(
                column.joinMethodName, column, model_object)
        return columns

    [expose(format='json')]

    def load_current_model(self):
        model = self.get_model_name()
        current_model = {}
        current_model['name'] = get_package_name()
        current_model['models'] = {}
        current_model['ordered_models'] = []

        for m in dir(model):
            if m in ('SQLObject', 'InheritableSQLObject'):
                continue
            model_object = getattr(model, m)
            if isinstance(model_object, type) and issubclass(
                    model_object, sqlobject.SQLObject):
                parent_class = 'SQLObject'
                if model_object._inheritable:
                    parent_class = model_object._parentClass.__name__
                columns = self.load_columns(model_object)
                current_model['ordered_models'].append(m)
                current_model['models'][m] = {
                    'name': m,
                    'parent_class': parent_class,
                    'table_name': model_object.sqlmeta.table,
                    'id_name': model_object.sqlmeta.idName,
                    'columns': columns,
                    'relations': {}
                }
        return dict(model=current_model)

    def save_session_as_name(self, name):
        # remove non-ascii
        if isinstance(name, unicode):
            name = name.encode('ascii', 'replace')
        # remove punctuation
        name = name.translate(string.maketrans('', ''), string.punctuation)
        # camelcase to remove spaces
        name = ''.join([x.title() for x in name.split()])
        sessions_directory = pkg_resources.resource_filename(
            __name__, os.path.join('static', 'sessions'))
        for idx in range(100):
            postfix = idx and '_%d' % idx or ''
            test_name = '%s%s.js' % (name, postfix)
            full_name = os.path.join(sessions_directory, test_name)
            if not os.path.exists(full_name):
                return full_name

    [expose(format='json')]

    def save_state(self, state, name=session_file_name):
        if name != session_file_name:
            name = self.save_session_as_name(name)
        if not name:
            return dict(state=False)
        f = open(name, 'w')
        f.write(state)
        f.close()
        return dict(state=True)

    def model_path(self):
        return os.path.abspath(os.path.join(get_package_name(), 'model.py'))

    def save_model(self, code):
        project_name = get_package_name()
        model_text = model_template % (project_name, code)
        model_path = self.model_path()
        if os.path.exists(model_path):
            version_file(model_path)
            f = open(model_path, 'w')
            f.write(model_text)
            f.close()
            return True, 'Saved %s' % model_path
        else:
            return False, 'Failed to save %s' % model_path

    def save_and_create_(self, code, order):
        model_path = os.path.join(get_project_name(), 'tmp2_model.py')
        model_path = os.path.abspath(model_path)
        open(model_path, 'w').write(str)
        package = __import__(get_package_name(), {}, {}, ["tmp2_model"])
        package.tmp2_model.Persona.createTable(ifNotExists=True)
        model = self.get_model_name()
        model.Persona = package.tmp2_model.Persona
        # pk = package.model
        # import tmp_model as pk
        # pk.Persona.createTable(ifNotExists=True)
        return dict(status='Tables ok')

    [expose(format='json')]

    def save_and_create(self, code, order):
        status_code, status = self.save_model(code)
        if not status_code:
            return dict(status=status)
        tmp_name = 'tmp_model'

        # copy the model file
        model_path = self.model_path()
        tmp_model_path = model_path.replace('model.py', '%s.py' % tmp_name)
        try:
            shutil.copy(model_path, tmp_model_path)
        except IOError, e:
            return dict(status='Failed to create a temporary model file: %s' %
                        e)

        model = self.get_model_name()
        package = __import__(get_package_name(), {}, {}, [tmp_name])
        tmp_model = getattr(package, tmp_name)

        ok = []
        fail = []
        classes = order.split(',')
        for class_name in classes:
            try:
                obj = getattr(tmp_model, class_name)
                obj.createTable(ifNotExists=True)
                setattr(model, class_name, obj)
                ok.append('Table created for class %s' % class_name)
            except Exception, e:
                fail.append('Failed to create table for class %s: %s' %
                            (class_name, e))
Ejemplo n.º 21
0
 def run(self):
     options, args = self.parser.parse_args()
     force, keep, reverse = options.force, options.keep, options.reverse
     from_index, to_index = 0, 1
     if reverse:
         from_index, to_index = to_index, from_index
     self.from_index, self.to_index = from_index, to_index
     engines, extensions, xmlns = self.engines, self.extensions, self.xmlns
     package_name = get_package_name()
     convert = [(r'<([a-z]+)\b([^<]*\bxmlns:py\s*=\s*[\'"])'
         r'%s([\'"][^<]*>.*</\1)>' % xmlns[from_index],
         r"<\1\2%s\3>" % self.xmlns[to_index])]
     if reverse:
         convert.append((r'<([a-z]+)\b([^<]*)\b'
             r'xmlns:xi(\s*=\s*")http://www.w3.org/2001/XInclude'
             r'("[^<]*>)\s*<xi:include\s+href=[\'"]'
             r'([^\'"]*)\.html[\'"]/>(.*</\1)>',
             r"<\1\2py:extends\3'\5.kid'\4\6>"))
     else:
         convert.append((r'<([a-z]+)\b([^<]*)\b'
             r'py:extends(\s*=\s*")\'([^\'"]*)\.kid\'("[^<]*>)(.*</\1)>',
             r'<\1\2xmlns:xi\3http://www.w3.org/2001/XInclude\5'
             r'<xi:include href="\4.html"/>\6>'))
     # we could append more conversion rules here
     self.re_convert = [(re.compile(r[0], re.S), r[1]) for r in convert]
     self.re_defaultview = re.compile(
         r'^(\s*tg.defaultview\s*=\s*[\'"])(?:%s)([\'"]\s*(?:#.*)?)$'
             % engines[from_index].lower(), re.M)
     print "Converting all %s to %s templates in package %s" % (
         engines[from_index], engines[to_index], package_name)
     print "(the %s templates will be %s) ..." % (engines[from_index],
         keep and 'kept' or 'removed')
     n = 0
     for dirpath, dirnames, filenames in os.walk(package_name):
         i = 0
         while i < len(dirnames):
             dirname = dirnames[i]
             if dirname.startswith('.') or dirname.endswith('~'):
                 del dirnames[i]
             else:
                 i += 1
         for filename in filenames:
             if filename.endswith('~'):
                 continue
             name, ext = os.path.splitext(filename)
             if ext == extensions[from_index]:
                 filename = os.path.join(dirpath, name)
                 if self.convert_template(filename, force, keep):
                     n += 1
     if n:
         if n > 1:
             print "%d %s templates have been converted to %s." % (
                 n, engines[from_index], engines[to_index])
         print "Changing the configuration of package %s ..." % package_name
         if not self.change_config(
                 os.path.join(package_name, 'config', 'app.cfg')):
             print "Application config with defaultview setting not found."
     elif force:
         print "No %s templates were found in the current project." % (
             engines[from_index])
     else:
         print "No %s templates needed to be converted in this project." % (
             engines[from_index])
Ejemplo n.º 22
0
 def model_path(self):
     return os.path.abspath(
         os.path.join(get_package_name(), 'model.py'))
Ejemplo n.º 23
0
 def model_path(self):
     return os.path.abspath(os.path.join(get_package_name(), 'model.py'))
Ejemplo n.º 24
0
 def run(self):
     options, args = self.parser.parse_args()
     force, keep, reverse = options.force, options.keep, options.reverse
     from_index, to_index = 0, 1
     if reverse:
         from_index, to_index = to_index, from_index
     self.from_index, self.to_index = from_index, to_index
     engines, extensions, xmlns = self.engines, self.extensions, self.xmlns
     package_name = get_package_name()
     convert = [(r'<([a-z]+)\b([^<]*\bxmlns:py\s*=\s*[\'"])'
                 r'%s([\'"][^<]*>.*</\1)>' % xmlns[from_index],
                 r"<\1\2%s\3>" % self.xmlns[to_index])]
     if reverse:
         convert.append(
             (r'<([a-z]+)\b([^<]*)\b'
              r'xmlns:xi(\s*=\s*")http://www.w3.org/2001/XInclude'
              r'("[^<]*>)\s*<xi:include\s+href=[\'"]'
              r'([^\'"]*)\.html[\'"]/>(.*</\1)>',
              r"<\1\2py:extends\3'\5.kid'\4\6>"))
     else:
         convert.append(
             (r'<([a-z]+)\b([^<]*)\b'
              r'py:extends(\s*=\s*")\'([^\'"]*)\.kid\'("[^<]*>)(.*</\1)>',
              r'<\1\2xmlns:xi\3http://www.w3.org/2001/XInclude\5'
              r'<xi:include href="\4.html"/>\6>'))
     # we could append more conversion rules here
     self.re_convert = [(re.compile(r[0], re.S), r[1]) for r in convert]
     self.re_defaultview = re.compile(
         r'^(\s*tg.defaultview\s*=\s*[\'"])(?:%s)([\'"]\s*(?:#.*)?)$' %
         engines[from_index].lower(), re.M)
     print "Converting all %s to %s templates in package %s" % (
         engines[from_index], engines[to_index], package_name)
     print "(the %s templates will be %s) ..." % (engines[from_index], keep
                                                  and 'kept' or 'removed')
     n = 0
     for dirpath, dirnames, filenames in os.walk(package_name):
         i = 0
         while i < len(dirnames):
             dirname = dirnames[i]
             if dirname.startswith('.') or dirname.endswith('~'):
                 del dirnames[i]
             else:
                 i += 1
         for filename in filenames:
             if filename.endswith('~'):
                 continue
             name, ext = os.path.splitext(filename)
             if ext == extensions[from_index]:
                 filename = os.path.join(dirpath, name)
                 if self.convert_template(filename, force, keep):
                     n += 1
     if n:
         if n > 1:
             print "%d %s templates have been converted to %s." % (
                 n, engines[from_index], engines[to_index])
         print "Changing the configuration of package %s ..." % package_name
         if not self.change_config(
                 os.path.join(package_name, 'config', 'app.cfg')):
             print "Application config with defaultview setting not found."
     elif force:
         print "No %s templates were found in the current project." % (
             engines[from_index])
     else:
         print "No %s templates needed to be converted in this project." % (
             engines[from_index])