Example #1
0
def get_supported_printers(include_virtual=False):
    result = {}
    config = [
        ('bematech', ['DP20C', 'MP20', 'MP2100', 'MP2100TH', 'MP4200TH', 'MP25']),
        ('daruma', ['DR700', 'FS2100', 'FS345', 'FS600MFD']),
        ('dataregis', ['EP375', 'Quick']),
        ('elgin', ['I9', 'KFiscal']),
        ('tanca', ['TP650']),
        ('epson', ['FBII', 'FBIII', 'TMT20']),
        ('fiscnet', ['FiscNetECF']),
        ('perto', ['Pay2023']),
        ('sweda', ['SI150']),
    ]
    if include_virtual:
        config.append(('virtual', ['Simple']))

    for brand, module_names in config:
        result[brand] = []
        for module_name in module_names:
            try:
                obj = namedAny("stoqdrivers.printers.%s.%s.%s"
                               % (brand, module_name, module_name))
            except AttributeError:
                raise ImportError("Can't find class %s for module %s"
                                  % (module_name, module_name))
            if not hasattr(obj, 'supported'):
                continue
            result[brand].append(obj)
    return result
Example #2
0
def get_all_classes(root):
    """
    Gets a generator with classes.
    :returns: a generator.
    """
    # Convert to absolute path so it works within documentation tools
    basedir = os.path.dirname(stoqlib.__path__[0])
    root = os.path.join(basedir, root)
    for package in listpackages(root):
        # Remove absolute path
        package = package[len(basedir):]
        if package.startswith('.'):
            package = package[1:]
        # stoqlib.domain -> stoqlib/domain
        package = package.replace('.', os.path.sep)

        # List all python files in stoqlib/domain
        for filename in glob.glob(os.path.join(package, '*.py')):
            # Avoid tests.
            if 'test/' in filename:
                continue

            # stoqlib/domain/base.py -> stoqlib.domain.base
            modulename = filename[:-3].replace(os.path.sep, '.')
            module = namedAny(modulename)
            for unused, klass in inspect.getmembers(module, inspect.isclass):
                yield klass
Example #3
0
    def get_parameter_type(self, field_name):
        detail = self.get_parameter_constant(field_name)

        if isinstance(detail.type, basestring):
            return namedAny('stoqlib.domain.' + detail.type)
        else:
            return detail.type
Example #4
0
def get_all_classes(root, basedir=None):
    """
    Gets a generator with classes.
    :param basedir: The directory from where the packages are being imported.
    :returns: a generator.
    """
    # Convert to absolute path so it works within documentation tools
    if basedir is None:
        basedir = os.path.dirname(stoqlib.__path__[0])
    root = os.path.join(basedir, root)
    for package in listpackages(root):
        # Remove absolute path
        package = package[len(basedir):]
        if package.startswith('.'):
            package = package[1:]
        # stoqlib.domain -> stoqlib/domain
        package = package.replace('.', os.path.sep)

        # List all python files in stoqlib/domain
        for filename in glob.glob(os.path.join(package, '*.py')):
            # Avoid tests.
            if 'test/' in filename:
                continue

            # stoqlib/domain/base.py -> stoqlib.domain.base
            modulename = filename[:-3].replace(os.path.sep, '.')
            module = namedAny(modulename)
            for unused, klass in inspect.getmembers(module, inspect.isclass):
                yield klass
Example #5
0
    def add_ormobject(self, orm_type, orm_name):
        if orm_type in dt.done:
            return
        dt.done.add(orm_type)
        module_name = orm_type.__module__
        pymodule = namedAny(module_name)
        assert pymodule
        module = MANAGER.astng_from_module(pymodule)
        assert module
        class_node = module[orm_name]

        t = ''
        t += 'class %s:\n' % (orm_name, )

        t += '    q = None\n'
        t += '    _connection = None\n'

        orm_ti = dt.orm_classes.get(orm_name)
        for name in sorted(orm_ti.get_column_names()):
            t += '    %s = None\n' % (name, )

        for name, class_name in sorted(orm_ti.get_foreign_columns()):
            self.add_ormobject(dt.orm_classes[class_name].orm_type, class_name)
            t += '    %s = None\n' % (class_name, )
            t += '    %s = %s()\n' % (name, class_name)

        for name, class_name in sorted(orm_ti.get_single_joins()):
            self.add_ormobject(dt.orm_classes[class_name].orm_type, class_name)
            t += '    %s = %s()\n' % (name, class_name)

        t += '\n'
        nodes = self.builder.string_build(t)
        for key, value in nodes[orm_name].items():
            class_node.locals[key] = [value]
Example #6
0
def get_supported_printers(include_virtual=False):
    result = {}
    config = [
        ('bematech',
         ['DP20C', 'MP20', 'MP2100', 'MP2100TH', 'MP4200TH', 'MP25']),
        ('daruma', ['DR700', 'FS2100', 'FS345', 'FS600MFD']),
        ('dataregis', ['EP375', 'Quick']),
        ('elgin', ['I9', 'KFiscal']),
        ('epson', ['FBII', 'FBIII', 'TMT20']),
        ('fiscnet', ['FiscNetECF']),
        ('perto', ['Pay2023']),
        ('sweda', ['SI150']),
    ]
    if include_virtual:
        config.append(('virtual', ['Simple']))

    for brand, module_names in config:
        result[brand] = []
        for module_name in module_names:
            try:
                obj = namedAny("stoqdrivers.printers.%s.%s.%s" %
                               (brand, module_name, module_name))
            except AttributeError:
                raise ImportError("Can't find class %s for module %s" %
                                  (module_name, module_name))
            if not hasattr(obj, 'supported'):
                continue
            result[brand].append(obj)
    return result
Example #7
0
def _introspect_tables():
    base_dir = domain.__path__[0]
    filenames = []
    filenames.extend(glob.glob(base_dir + '/*.py'))
    filenames.extend(glob.glob(base_dir + '/payment/*.py'))
    tables = []

    for filename in filenames:
        if '__init__' in filename:
            continue
        module_name = filename[len(base_dir) + 1:-3]
        module_name = 'stoqlib.domain.' + module_name.replace('/', '.')
        module = namedAny(module_name)
        for attr in dir(module):
            value = getattr(module, attr)
            try:
                if not issubclass(value, ORMObject):
                    continue
            except TypeError:
                continue
            if value.__dict__.get('__storm_table__', 'invalid') == 'invalid':
                continue

            tables.append(value)

    return tables
Example #8
0
def _introspect_tables():
    base_dir = domain.__path__[0]
    filenames = []
    filenames.extend(glob.glob(base_dir + '/*.py'))
    filenames.extend(glob.glob(base_dir + '/payment/*.py'))
    tables = []

    for filename in filenames:
        if '__init__' in filename:
            continue
        module_name = filename[len(base_dir) + 1:-3]
        module_name = 'stoqlib.domain.' + module_name.replace('/', '.')
        module = namedAny(module_name)
        for attr in dir(module):
            value = getattr(module, attr)
            try:
                if not issubclass(value, ORMObject):
                    continue
            except TypeError:
                continue
            if value.__dict__.get('__storm_table__', 'invalid') == 'invalid':
                continue

            tables.append(value)

    return tables
Example #9
0
 def _scan_module(self, package, name):
     module_name = '%s.%s' % (package, name)
     module = namedAny(module_name)
     for attr in dir(module):
         value = getattr(module, attr)
         if not my_issubclass(value, ORMObject):
             continue
         self._scan_orm_object(module, value)
Example #10
0
 def add_interfaces(self, module):
     f = namedAny(module.name).__file__.replace('.pyc', '.py')
     data = open(f).read()
     data = re.sub(r'(def \S+)\(\)', r'\1(self)', data)
     data = re.sub(r'(def \S+)\(', r'\1(self, ', data)
     data = data.replace('self, self', 'self')
     nodes = self.builder.string_build(data)
     self.module.locals = nodes.locals
Example #11
0
 def _scan_module(self, package, name):
     module_name = '%s.%s' % (package, name)
     module = namedAny(module_name)
     for attr in dir(module):
         value = getattr(module, attr)
         if not my_issubclass(value, ORMObject):
             continue
         self._scan_orm_object(module, value)
Example #12
0
 def add_interfaces(self, module):
     f = namedAny(module.name).__file__.replace('.pyc', '.py')
     data = open(f).read()
     data = re.sub(r'(def \S+)\(\)', r'\1(self)', data)
     data = re.sub(r'(def \S+)\(', r'\1(self, ', data)
     data = data.replace('self, self', 'self')
     nodes = self.builder.string_build(data)
     self.module.locals = nodes.locals
Example #13
0
def get_cardinal_module():
    lang = locale.getlocale()[0]
    if not lang:
        # For tests
        return generic

    # First try the full LANG, like 'pt_BR', 'en_US', etc
    path = 'stoqlib.lib.cardinals.%s' % (lang, )
    try:
        return namedAny(path)
    except (ImportError, AttributeError):
        # Then base lang, 'pt', 'en', etc
        base_lang = lang[:2]
        path = 'stoqlib.lib.cardinals.%s' % (base_lang, )
        try:
            return namedAny(path)
        except (ImportError, AttributeError):
            return generic
Example #14
0
def get_cardinal_module():
    lang = locale.getlocale()[0]
    if not lang:
        # For tests
        return generic

    # First try the full LANG, like 'pt_BR', 'en_US', etc
    path = "stoqlib.lib.cardinals.%s" % (lang,)
    try:
        return namedAny(path)
    except (ImportError, AttributeError):
        # Then base lang, 'pt', 'en', etc
        base_lang = lang[:2]
        path = "stoqlib.lib.cardinals.%s" % (base_lang,)
        try:
            return namedAny(path)
        except (ImportError, AttributeError):
            return generic
Example #15
0
    def add_wizard_step(self, module):
        from stoqlib.gui.wizards.purchasewizard import WizardEditorStep
        pymod = namedAny(module.name)
        for attr in dir(pymod):
            value = getattr(pymod, attr)
            if attr in module and isinstance(module[attr], From):
                continue

            if my_issubclass(value, WizardEditorStep):
                self.add_delegate(value, attr)
Example #16
0
def _get_tables_cache():
    if _tables_cache:
        return _tables_cache

    for path, table_names in _tables:
        for table_name in table_names:
            klass = namedAny('stoqlib.domain.%s.%s' % (path, table_name))
            _tables_cache[table_name] = klass

    p_manager = get_plugin_manager()
    for p_name in p_manager.installed_plugins_names:
        plugin = p_manager.get_plugin(p_name)
        for path, table_names in plugin.get_tables():
            for table_name in table_names:
                desc = p_manager.get_description_by_name(p_name)
                klass = namedAny('.'.join([desc.name, path, table_name]))
                _tables_cache[table_name] = klass

    return _tables_cache
Example #17
0
    def add_wizard_step(self, module):
        from stoqlib.gui.wizards.purchasewizard import WizardEditorStep
        pymod = namedAny(module.name)
        for attr in dir(pymod):
            value = getattr(pymod, attr)
            if attr in module and isinstance(module[attr], From):
                continue

            if my_issubclass(value, WizardEditorStep):
                self.add_delegate(value, attr)
Example #18
0
File: views.py Project: Schevo/kiwi
def _open_glade(view, gladefile, domain):
    if not gladefile:
        raise ValueError("A gladefile wasn't provided.")
    elif not isinstance(gladefile, basestring):
        raise TypeError(
              "gladefile should be a string, found %s" % type(gladefile))

    if gladefile.endswith('.ui'):
        directory = os.path.dirname(namedAny(view.__module__).__file__)
        gladefile = os.path.join(directory, gladefile)
    else:
        filename = os.path.splitext(os.path.basename(gladefile))[0]
        gladefile = environ.find_resource("glade", filename + '.glade')

    fp = open(gladefile)
    sniff = fp.read(200)
    fp.close()

    # glade-2
    #<?xml version="1.0" standalone="no"?> <!--*- mode: xml -*-->
    #<!DOCTYPE glade-interface SYSTEM "http://glade.gnome.org/glade-2.0.dtd">

    # glade-3
    # <?xml version="1.0" encoding="UTF-8" standalone="no"?>
    # <!DOCTYPE glade-interface SYSTEM "glade-2.0.dtd">
    if '<interface' in sniff:
        if not hasattr(gtk, 'Builder'):
            raise AssertionError(
                "PyGTK 2.12 or higher is required for builder support")
        WidgetTree = _get_builder()
        loader_name = 'builder'
    elif 'glade-2.0.dtd' in sniff:
        WidgetTree = _get_libglade()
        loader_name = 'libglade'
    elif 'gaxml-0.1.dtd' in sniff:
        WidgetTree = _get_gaxml()
        loader_name = 'gaxml'
    else:
        # gazpacho:
        #<?xml version="1.0" standalone="no"?> <!--*- mode: xml -*-->
        #<!DOCTYPE glade-interface SYSTEM "http://gazpacho.sicem.biz/gazpacho-0.1.dtd">
        if not 'gazpacho-0.1.dtd' in sniff:
            log.warning("Could not determine type/dtd of gladefile %s" % gladefile)

        WidgetTree = _get_gazpacho()
        loader_name = 'gazpacho.loader'

    # None means, failed to import
    if WidgetTree is None:
        raise RuntimeError(
            "Could not find %s, it needs to be installed to "
            "load the gladefile %s" % (loader_name, gladefile))

    return WidgetTree(view, gladefile, domain)
Example #19
0
def _get_tables_cache():
    if _tables_cache:
        return _tables_cache

    for path, table_names in _tables:
        for table_name in table_names:
            klass = namedAny('stoqlib.domain.%s.%s' % (path, table_name))
            _tables_cache[table_name] = klass

    p_manager = get_plugin_manager()
    for p_name in p_manager.installed_plugins_names:
        plugin = p_manager.get_plugin(p_name)
        for path, table_names in plugin.get_tables():
            for table_name in table_names:
                desc = p_manager.get_description_by_name(p_name)
                basepath = os.path.basename(desc.dirname)
                klass = namedAny('.'.join([basepath, path, table_name]))
                _tables_cache[table_name] = klass

    return _tables_cache
Example #20
0
    def _get_main(self):
        try:
            module = namedAny(self._path)
        except:
            log.warn('importing %s' % self._path)
            raise

        main = getattr(module, 'main', None)
        if not main or not callable(main):
            raise SystemExit("ERROR: Could not find item '%s' in module %s" %
                             'main', self._path)
        return main
Example #21
0
def main(args):
    usage = "usage: %prog [options] command [args]"
    parser = optparse.OptionParser(usage=usage)
    parser.add_option('-t',
                      '--type',
                      action="store",
                      dest="type",
                      default="printers",
                      help='Device type')
    parser.add_option('-b',
                      '--brand',
                      action="store",
                      dest="brand",
                      help='Device brand')
    parser.add_option('-m',
                      '--model',
                      action="store",
                      dest="model",
                      help='Device model')
    parser.add_option('-p',
                      '--port',
                      action="store",
                      dest="port",
                      default="/dev/ttyS0",
                      help='Device port')

    options, args = parser.parse_args(args)
    if len(args) < 2:
        raise SystemExit("Need a command")

    driver = namedAny(
        'stoqdrivers.%s.%s.%s.%s' %
        (options.type, options.brand, options.model, options.model))

    device = driver(port=SerialPort(options.port))

    command = args[1]
    cb = getattr(device, command)

    items = []
    for item in args[2:]:
        try:
            item = int(item)
        except ValueError:
            pass
        items.append(item)
    print items
    retval = cb(*items)
    if retval is not None:
        print '%s returned:' % (command, )
        import pprint
        pprint.pprint(retval)
    return 0
Example #22
0
    def _get_main(self):
        try:
            module = namedAny(self._path)
        except:
            log.warn('importing %s' % self._path)
            raise

        main = getattr(module, 'main', None)
        if not main or not callable(main):
            raise SystemExit(
                "ERROR: Could not find item '%s' in module %s" % 'main',
                self._path)
        return main
Example #23
0
def _open_glade(view, gladefile, domain, translation_domain):
    if not gladefile:
        raise ValueError("A gladefile wasn't provided.")
    elif not isinstance(gladefile, str):
        raise TypeError(
            "gladefile should be a string, found %s" % type(gladefile))

    if gladefile.endswith('.ui'):
        directory = os.path.dirname(namedAny(view.__module__).__file__)
        gladefile = os.path.join(directory, gladefile)
    else:
        for ext in ['.glade', '.ui']:
            if environ.get_resource_exists(domain, 'glade', gladefile + ext):
                gladefile = environ.get_resource_filename(domain, 'glade',
                                                          gladefile + ext)
                break
        else:
            raise EnvironmentError(
                "Glade resource %s was not found on domain %s" % (
                    gladefile, domain))

    # XXX: Opening this not in binary mode was raising an weird error on win32
    fp = open(gladefile, 'rb')
    sniff = fp.read(200).decode()
    fp.close()

    if '<interface' in sniff:
        WidgetTree = _get_builder()
        loader_name = 'builder'
    # glade-2: <!DOCTYPE glade-interface SYSTEM "http://glade.gnome.org/glade-2.0.dtd">
    # glade-3: <!DOCTYPE glade-interface SYSTEM "glade-2.0.dtd">
    elif 'glade-2.0.dtd' in sniff:
        WidgetTree = _get_libglade()
        loader_name = 'libglade'
    elif 'gaxml-0.1.dtd' in sniff:
        WidgetTree = _get_gaxml()
        loader_name = 'gaxml'
    else:
        log.warning("Could not determine type/dtd of gladefile %s" % gladefile)
        # Defaulting to builder
        WidgetTree = _get_builder()
        loader_name = 'builder'

    # None means, failed to import
    if WidgetTree is None:
        raise RuntimeError(
            "Could not find %s, it needs to be installed to "
            "load the gladefile %r" % (loader_name, gladefile))

    return WidgetTree(view, gladefile, translation_domain)
Example #24
0
def get_by_type(importer_type):
    """Gets an importers class, instantiates it returns it
    :param importer_type: an importer
    :type importer_type: string
    :returns: an importer instance
    :type: :class:`Importer` subclass
    """

    if not importer_type in _available_importers:
        raise ValueError(u"Invalid importer %s, must be one of %s" % (
            importer_type, u', '.join(sorted(_available_importers))))
    name = _available_importers[importer_type]
    cls = namedAny('stoqlib.importers.%s' % (name, ))
    return cls()
Example #25
0
def _open_glade(view, gladefile, domain):
    if not gladefile:
        raise ValueError("A gladefile wasn't provided.")
    elif not isinstance(gladefile, basestring):
        raise TypeError(
              "gladefile should be a string, found %s" % type(gladefile))

    if gladefile.endswith('.ui'):
        directory = os.path.dirname(namedAny(view.__module__).__file__)
        gladefile = os.path.join(directory, gladefile)
    else:
        filename = os.path.splitext(os.path.basename(gladefile))[0]
        try:
            gladefile = environ.find_resource("glade", filename + '.glade')
        except EnvironmentError:
            gladefile = environ.find_resource("glade", filename + '.ui')


    fp = open(gladefile)
    sniff = fp.read(200)
    fp.close()

    if '<interface' in sniff:
        WidgetTree = _get_builder()
        loader_name = 'builder'
    # glade-2: <!DOCTYPE glade-interface SYSTEM "http://glade.gnome.org/glade-2.0.dtd">
    # glade-3: <!DOCTYPE glade-interface SYSTEM "glade-2.0.dtd">
    elif 'glade-2.0.dtd' in sniff:
        WidgetTree = _get_libglade()
        loader_name = 'libglade'
    elif 'gaxml-0.1.dtd' in sniff:
        WidgetTree = _get_gaxml()
        loader_name = 'gaxml'
    # gazpacho: <!DOCTYPE glade-interface SYSTEM "http://gazpacho.sicem.biz/gazpacho-0.1.dtd">
    elif 'gazpacho-0.1.dtd' in sniff:
        WidgetTree = _get_gazpacho()
        loader_name = 'gazpacho.loader'
    else:
        log.warning("Could not determine type/dtd of gladefile %s" % gladefile)
        # Defaulting to builder
        WidgetTree = _get_builder()
        loader_name = 'builder'

    # None means, failed to import
    if WidgetTree is None:
        raise RuntimeError(
            "Could not find %s, it needs to be installed to "
            "load the gladefile %r" % (loader_name, gladefile))

    return WidgetTree(view, gladefile, domain)
Example #26
0
def main(args):
    usage = "usage: %prog [options] command [args]"
    parser = optparse.OptionParser(usage=usage)
    parser.add_option('-t', '--type',
                      action="store",
                      dest="type",
                      default="printers",
                      help='Device type')
    parser.add_option('-b', '--brand',
                      action="store",
                      dest="brand",
                      help='Device brand')
    parser.add_option('-m', '--model',
                      action="store",
                      dest="model",
                      help='Device model')
    parser.add_option('-p', '--port',
                      action="store",
                      dest="port",
                      default="/dev/ttyS0",
                      help='Device port')

    options, args = parser.parse_args(args)
    if len(args) < 2:
        raise SystemExit("Need a command")

    driver = namedAny('stoqdrivers.%s.%s.%s.%s' % (
        options.type, options.brand, options.model, options.model))

    device = driver(port=SerialPort(options.port))

    command = args[1]
    cb = getattr(device, command)

    items = []
    for item in args[2:]:
        try:
            item = int(item)
        except ValueError:
            pass
        items.append(item)
    print items
    retval = cb(*items)
    if retval is not None:
        print '%s returned:' % (command,)
        import pprint
        pprint.pprint(retval)
    return 0
Example #27
0
def stoq_transform(module):
    fake = FakeBuilder(module)
    if module.name == 'hashlib':
        nodes = fake.builder.string_build("""
class _Internal:
    def hexdigest(self):
        return hash('foo')
def md5(enc):
    return _Internal()""")
        module.locals = nodes.locals
    if module.name == 'storm.info':
        # Actually we only need an override for ClassAlias,
        # but I don't know how to just override one attribute,
        # so implement the whole API we need.
        nodes = fake.builder.string_build("""
class ClassInfo(dict):
    columns = []
def ClassAlias(class_, b):
    return class_
def get_cls_info(cls):
    return ClassInfo()
def get_obj_info(obj):
    return {}
""")
        module.locals = nodes.locals

    if module.name == 'stoqlib.domain.base':
        pass
    if module.name == 'stoqlib.domain.interfaces':
        fake.add_interfaces(module)
    elif module.name.startswith('stoqlib.domain.'):
        pymod = namedAny(module.name)
        for attr in dir(pymod):
            value = getattr(pymod, attr)
            if attr in module and isinstance(module[attr], From):
                continue

            if my_issubclass(value, ORMObject):
                fake.add_ormobject(value, attr)
    elif module.name == 'stoqlib.lib.parameters':
        fake.add_parameter_access()
    elif module.name == 'kiwi.log':
        nodes = fake.builder.string_build(
"""class Logger(object):
    def info(self, msg):
        pass
""")
        module.locals = nodes.locals
Example #28
0
    def getFacets(self):
        """Gets a list of facets assoicated with the current object.
        :returns: a list of facets
        """
        facet_types = getattr(self, '_facets', [])

        facets = []
        for iface_name in facet_types:
            iface = namedAny(iface_name)

            facet = iface(self, None)
            # Filter out facets which are not set
            if facet is None:
                continue
            facets.append(facet)
        return facets
Example #29
0
def get_l10n_module(country=None):
    if not country:
        from stoqlib.lib.parameters import sysparam
        country = sysparam.get_string('COUNTRY_SUGGESTED')

    short = iso639_list.get(country.lower(), None)
    if short is None:
        return generic

    path = 'stoqlib.l10n.%s.%s' % (short, short)
    try:
        module = namedAny(path)
    except (ImportError, AttributeError):
        return generic

    return module
Example #30
0
def get_supported_barcode_readers():
    result = {}
    for brand, module_names in [('metrologic', ['MC630'])]:
        result[brand] = []
        for module_name in module_names:
            try:
                obj = namedAny("stoqdrivers.readers.barcode.%s.%s.%s" %
                               (brand, module_name, module_name))
            except AttributeError:
                raise ImportError("Can't find class %s for module %s" %
                                  (module_name, module_name))
            if not IBarcodeReader.implementedBy(obj):
                raise TypeError("The driver %s %s doesn't implements a "
                                "valid interface" % (brand, obj.model_name))
            result[brand].append(obj)
    return result
Example #31
0
def get_supported_barcode_readers():
    result = {}
    for brand, module_names in [('metrologic', ['MC630'])]:
        result[brand] = []
        for module_name in module_names:
            try:
                obj = namedAny("stoqdrivers.readers.barcode.%s.%s.%s"
                               % (brand, module_name, module_name))
            except AttributeError:
                raise ImportError("Can't find class %s for module %s"
                                  % (module_name, module_name))
            if not IBarcodeReader.implementedBy(obj):
                raise TypeError("The driver %s %s doesn't implements a "
                                "valid interface"
                                % (brand, obj.model_name))
            result[brand].append(obj)
    return result
Example #32
0
def get_supported_scales():
    result = {}

    for brand, module_names in [(u'toledo', [u'PrixIII'])]:
        result[brand] = []
        for module_name in module_names:
            try:
                obj = namedAny("stoqdrivers.scales.%s.%s.%s" %
                               (brand, module_name, module_name))
            except AttributeError:
                raise ImportError("Can't find class %s for module %s" %
                                  (module_name, module_name))
            if not IScale.implementedBy(obj):
                raise TypeError("The driver %s %s doesn't implements a "
                                "valid interface" % (brand, obj.model_name))
            result[brand].append(obj)
    return result
Example #33
0
def get_supported_scales():
    result = {}

    for brand, module_names in [(u'toledo', [u'PrixIII'])]:
        result[brand] = []
        for module_name in module_names:
            try:
                obj = namedAny("stoqdrivers.scales.%s.%s.%s"
                               % (brand, module_name, module_name))
            except AttributeError:
                raise ImportError("Can't find class %s for module %s"
                                  % (module_name, module_name))
            if not IScale.implementedBy(obj):
                raise TypeError("The driver %s %s doesn't implements a "
                                "valid interface"
                                % (brand, obj.model_name))
            result[brand].append(obj)
    return result
Example #34
0
def _get_all_classes(root):
    root = os.path.dirname(os.path.dirname(kiwi.__file__)) + '/'
    # We cannot import setup.py neither kiwiwidgets.py using namedAny
    for filename in _get_kiwi_sources(root, with_toplevel_sources=False):
        # Avoid tests.
        if 'test/' in filename:
            continue

        modulename = filename[len(root):-3].replace(os.path.sep, '.')
        try:
            module = namedAny(modulename)
        except ImportError as e:
            # FIXME: Some modules (like db.sqlobj, db.sqlalch) will try to
            # import things that we don't have on out development environment
            print("module %s is trying to import something "
                  "not importable: %s" % (modulename, e))
            continue

        for unused, klass in inspect.getmembers(module, inspect.isclass):
            yield klass
Example #35
0
def _get_all_classes(root):
    root = os.path.dirname(os.path.dirname(kiwi.__file__)) + '/'
    # We cannot import setup.py neither kiwiwidgets.py using namedAny
    for filename in _get_kiwi_sources(root, with_toplevel_sources=False):
        # Avoid tests.
        if 'test/' in filename:
            continue

        modulename = filename[len(root):-3].replace(os.path.sep, '.')
        try:
            module = namedAny(modulename)
        except ImportError as e:
            # FIXME: Some modules (like db.sqlobj, db.sqlalch) will try to
            # import things that we don't have on out development environment
            print("module %s is trying to import something "
                  "not importable: %s" % (modulename, e))
            continue

        for unused, klass in inspect.getmembers(module, inspect.isclass):
            yield klass
Example #36
0
def stoq_transform(module):
    fake = FakeBuilder(module)
    if module.name == 'hashlib':
        nodes = fake.builder.string_build("""
class _Internal:
    def hexdigest(self):
        return hash('foo')
def md5(enc):
    return _Internal()""")
        module.locals = nodes.locals
    if module.name == 'storm.info':
        # Actually we only need an override for ClassAlias,
        # but I don't know how to just override one attribute,
        # so implement the whole API we need.
        nodes = fake.builder.string_build("""
class ClassInfo(dict):
    columns = []
def ClassAlias(class_, b):
    return class_
def get_cls_info(cls):
    return ClassInfo()
def get_obj_info(obj):
    return {}
""")
        module.locals = nodes.locals

    if module.name == 'stoqlib.domain.base':
        pass
    if module.name == 'stoqlib.domain.interfaces':
        fake.add_interfaces(module)
    elif module.name.startswith('stoqlib.domain.'):
        pymod = namedAny(module.name)
        for attr in dir(pymod):
            value = getattr(pymod, attr)
            if attr in module and isinstance(module[attr], From):
                continue

            if my_issubclass(value, ORMObject):
                fake.add_ormobject(value, attr)
    elif module.name == 'stoqlib.lib.parameters':
        fake.add_parameter_access()
Example #37
0
def get_supported_printers():
    result = {}
    for brand, module_names in [
        ('bematech', ['DP20C', 'MP20', 'MP2100', 'MP25', 'MP4000']),
        ('bixolon', ['SRP350']), ('daruma', ['FS2100', 'FS345', 'FS600MFD']),
        ('dataregis', ['EP375', 'Quick']), ('epson', ['FBII', 'FBIII']),
        ('fiscnet', ['FiscNetECF']), ('perto', ['Pay2023']),
        ('sweda', ['IFS9000I'])
    ]:
        result[brand] = []
        for module_name in module_names:
            try:
                obj = namedAny("stoqdrivers.printers.%s.%s.%s" %
                               (brand, module_name, module_name))
            except AttributeError:
                raise ImportError("Can't find class %s for module %s" %
                                  (module_name, module_name))
            if not hasattr(obj, 'supported'):
                continue
            result[brand].append(obj)
    return result
Example #38
0
 def get_parameter_by_field(self, field_name, field_type):
     from stoqlib.domain.base import Domain
     if isinstance(field_type, basestring):
         field_type = namedAny('stoqlib.domain.' + field_type)
     if field_name in self._cache:
         param = self._cache[field_name]
         if issubclass(field_type, Domain):
             return self.store.get(field_type, param.id)
         elif issubclass(field_type, PathParameter):
             return param
         else:
             return field_type(param)
     value = self.store.find(ParameterData, field_name=field_name).one()
     if value is None:
         return
     if issubclass(field_type, Domain):
         if value.field_value == u'' or value.field_value is None:
             return
         param = self.store.get(field_type, unicode(value.field_value))
         if param is None:
             return None
     else:
         # XXX: workaround to works with boolean types:
         value = value.field_value
         if field_type is bool:
             if value == u'True':
                 param = True
             elif value == u'False':
                 param = False
             # This is a pre-1.0 migration specific hack
             elif value == u"":
                 return None
             else:
                 param = bool(int(value))
         elif field_type is unicode:
             param = value
         else:
             param = field_type(value)
     self._cache[field_name] = param
     return param
Example #39
0
def get_supported_printers():
    result = {}
    for brand, module_names in [
            ('bematech', ['DP20C', 'MP20', 'MP2100', 'MP25']),
            ('daruma', ['FS2100', 'FS345', 'FS600MFD']),
            ('dataregis', ['EP375', 'Quick']),
            ('elgin', ['KFiscal']),
            ('epson', ['FBII', 'FBIII']),
            ('fiscnet', ['FiscNetECF']),
            ('perto', ['Pay2023'])]:
        result[brand] = []
        for module_name in module_names:
            try:
                obj = namedAny("stoqdrivers.printers.%s.%s.%s"
                               % (brand, module_name, module_name))
            except AttributeError:
                raise ImportError("Can't find class %s for module %s"
                                  % (module_name, module_name))
            if not hasattr(obj, 'supported'):
                continue
            result[brand].append(obj)
    return result
Example #40
0
    def add_ormobject(self, orm_type, orm_name):
        if orm_type in dt.done:
            return
        dt.done.add(orm_type)
        module_name = orm_type.__module__
        pymodule = namedAny(module_name)
        assert pymodule
        module = MANAGER.astng_from_module(pymodule)
        assert module
        class_node = module[orm_name]

        t = ''
        t += 'class %s:\n' % (orm_name, )

        t += '    q = None\n'
        t += '    _connection = None\n'

        orm_ti = dt.orm_classes.get(orm_name)
        if orm_ti is not None:
            for name in sorted(orm_ti.get_column_names()):
                t += '    %s = None\n' % (name, )

            for name, class_name in sorted(orm_ti.get_foreign_columns()):
                self.add_ormobject(dt.orm_classes[class_name].orm_type,
                                   class_name)
                t += '    %s = None\n' % (class_name, )
                t += '    %s = %s()\n' % (name, class_name)

            for name, class_name in sorted(orm_ti.get_single_joins()):
                self.add_ormobject(
                    dt.orm_classes[class_name].orm_type,
                    class_name)
                t += '    %s = %s()\n' % (name, class_name)

        t += '\n'
        nodes = self.builder.string_build(t)
        for key, value in nodes[orm_name].items():
            class_node.locals[key] = [value]
Example #41
0
def get_chart_class(chart_name):
    location = _charts.get(chart_name)
    if not location:
        raise ValueError(chart_name)
    return namedAny('stoqlib.chart.%s.%s' % (location, chart_name))
Example #42
0
 def _resolve_lazy_callbacks(cls):
     for klass_string, func in cls._lazy_callbacks[:]:
         klass = namedAny(klass_string)
         cls._callbacks_list.append(lambda *a, **kw: func(klass, *a, **kw))
         cls._lazy_callbacks.remove((klass_string, func))
Example #43
0
def _import():
    for path, table_names in _tables:
        for table_name in table_names:
            klass = namedAny('stoqlib.domain.%s.%s' % (path, table_name))
            _table_cache[table_name] = klass
            _table_list.append(klass)
Example #44
0
 def get_parameter_type(self):
     if isinstance(self.type, basestring):
         return namedAny('stoqlib.domain.' + self.type)
     else:
         return self.type
Example #45
0
 def _resolve_lazy_callbacks(cls):
     for klass_string, func in cls._lazy_callbacks[:]:
         klass = namedAny(klass_string)
         cls._callbacks_list.append(lambda *a, **kw: func(klass, *a, **kw))
         cls._lazy_callbacks.remove((klass_string, func))
Example #46
0
def _import():
    for path, table_names in _tables:
        for table_name in table_names:
            klass = namedAny('stoqlib.domain.%s.%s' % (path, table_name))
            _table_cache[table_name] = klass
            _table_list.append(klass)
Example #47
0
 def get_parameter_type(self):
     if isinstance(self.type, basestring):
         return namedAny('stoqlib.domain.' + self.type)
     else:
         return self.type