当前位置: 首页>>代码示例>>Python>>正文


Python runtime.get_default_store函数代码示例

本文整理汇总了Python中stoqlib.database.runtime.get_default_store函数的典型用法代码示例。如果您正苦于以下问题:Python get_default_store函数的具体用法?Python get_default_store怎么用?Python get_default_store使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了get_default_store函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: _start_tasks

    def _start_tasks(self):
        tasks = [
            Task('_xmlrpc', start_xmlrpc_server, self._xmlrpc_conn2),
            # This is not working nice when using NTK lib (maybe related to the multiprocess lib).
            # Must be executed as a separate process for now.
            #Task('_flask', start_flask_server),
            Task('_updater', start_plugins_update_scheduler,
                 self._updater_event, self._doing_backup),
            Task('_backup', start_backup_scheduler, self._doing_backup),
        ]
        # TODO: Make those work on windows
        if not _is_windows:
            tasks.extend([
                Task('_htsql', start_htsql, self._htsql_port),
                Task('_server', start_server),
                Task('_rtc', start_rtc),
            ])

        manager = get_plugin_manager()
        for plugin_name in manager.installed_plugins_names:
            plugin = manager.get_plugin(plugin_name)
            if not hasattr(plugin, 'get_server_tasks'):
                continue

            # FIXME: Check that the plugin implements IPluginTask when
            # we Stoq 1.11 is released
            for plugin_task in plugin.get_server_tasks():
                task_name = plugin_task.name
                name = _get_plugin_task_name(plugin_name, task_name)
                if self._manager.is_running(name):
                    continue

                kwargs = {}
                if plugin_task.handle_actions:
                    conn1, conn2 = multiprocessing.Pipe(True)
                    self._plugins_pipes[name] = conn1
                    kwargs['pipe_connection'] = conn2

                # Since Windows has no os.fork, multiprocessing will actually
                # run the process again and pass the required objects by
                # pickling them. For some reason, passing a plugin task will
                # break some places, since the it will make some objects
                # like PluginManager be pickled/unpicled, and when unlicking
                # it will run its contructor again, but it should wait
                # to do that until we have configured the database.
                func = (plugin_name, task_name)

                tasks.append(Task(name, func, **kwargs))

        for task in tasks:
            if not self._manager.is_running(task.name):
                self._manager.run_task(task)

        # Close the default store because it not functioning anymore since the
        # forked processes closed its "clone", but open a new one later
        # or else Stoq will not be able to find this instance
        set_default_store(None)
        get_default_store()
开发者ID:hackedbellini,项目名称:stoq-server,代码行数:58,代码来源:taskmanager.py

示例2: action_resume_tasks

    def action_resume_tasks(self):
        logger.info("Resuming the tasks as requested..")

        if self._paused:
            # get_default_store will recreate it (since we closed it above)
            get_default_store()
            self._start_tasks()
            self._paused = False

        return True, "Tasks resumed successfully"
开发者ID:hackedbellini,项目名称:stoq-server,代码行数:10,代码来源:taskmanager.py

示例3: restore_database

def restore_database(user_hash, time=None):
    assert user_hash

    # If the database doesn't exist, get_default_store will fail
    try:
        default_store = get_default_store()
    except Exception:
        default_store = None

    if default_store is not None and db_settings.has_database():
        try:
            default_store.lock_database()
        except DatabaseError:
            raise TaskException(
                "Could not lock database. This means that there are other "
                "clients connected. Make sure to close every Stoq client "
                "before updating the database")
        except Exception:
            raise TaskException(
                "Database is empty or in a corrupted state. Fix or drop it "
                "before trying to proceed with the restore")
        else:
            default_store.unlock_database()

        # FIXME: Windows will not liberate resource for other process to
        # write to the file. We should write our own TemporaryFile on Stoq
        # that handles all those cases for us and use here
        with tempfile.NamedTemporaryFile(delete=False) as f:
            pass
        try:
            if not db_settings.dump_database(f.name):
                raise TaskException("Failed to dump the database")
            backup_name = db_settings.restore_database(f.name)
            logger.info("Created a backup of the current database state on %s",
                        backup_name)
        finally:
            os.unlink(f.name)

    tmp_path = tempfile.mkdtemp()
    try:
        restore_path = os.path.join(tmp_path, 'stoq')
        logger.info("restoring database to %s", restore_path)
        backup.restore(restore_path, user_hash, time=time)

        # None will make the default store be closed, which we need
        # to sucessfully restore the database
        set_default_store(None)
        db_settings.clean_database(db_settings.dbname, force=True)
        db_settings.execute_sql(os.path.join(restore_path, 'stoq.dump'),
                                lock_database=True)

        logger.info("Backup restore finished sucessfully")
    finally:
        # get_default_store will recreate it (since we closed it above)
        get_default_store()
开发者ID:hackedbellini,项目名称:stoq-server,代码行数:55,代码来源:tasks.py

示例4: _try_connect

    def _try_connect(self):
        from stoqlib.lib.message import error
        try:
            store_dsn = self._config.get_settings().get_store_dsn()
        except:
            type, value, trace = sys.exc_info()
            error(_("Could not open the database config file"),
                  _("Invalid config file settings, got error '%s', "
                    "of type '%s'") % (value, type))

        from stoqlib.database.exceptions import PostgreSQLError
        from stoqlib.database.runtime import get_default_store
        from stoqlib.exceptions import DatabaseError
        from stoqlib.lib.pgpass import write_pg_pass
        from stoq.lib.startup import setup

        # XXX: progress dialog for connecting (if it takes more than
        # 2 seconds) or creating the database
        log.debug('calling setup()')
        try:
            setup(self._config, self._options, register_station=False,
                  check_schema=False, load_plugins=False)
            # the setup call above is not really trying to connect (since
            # register_station, check_schema and load_plugins are all False).
            # Try to really connect here.
            get_default_store()
        except (StoqlibError, PostgreSQLError) as e:
            log.debug('Connection failed.')
            error(_('Could not connect to the database'),
                  'error=%s uri=%s' % (str(e), store_dsn))
        except DatabaseError:
            log.debug('Connection failed. Tring to setup .pgpass')
            # This is probably a missing password configuration. Setup the
            # pgpass file and try again.
            password = self._get_password()
            if not password:
                # There is no password stored in data file. Abort
                raise

            from stoqlib.database.settings import db_settings
            write_pg_pass(db_settings.dbname, db_settings.address,
                          db_settings.port, db_settings.username, password)
            # Now that there is a pg_pass file, try to connect again
            try:
                get_default_store()
            except DatabaseError as e:
                log.debug('Connection failed again.')
                error(_('Could not connect to the database'),
                      'error=%s uri=%s' % (str(e), store_dsn))
开发者ID:Guillon88,项目名称:stoq,代码行数:49,代码来源:shell.py

示例5: restore_database

def restore_database(user_hash, time=None):
    assert user_hash

    # If the database doesn't exist, get_default_store will fail
    try:
        default_store = get_default_store()
    except Exception:
        default_store = None

    if default_store is not None and db_settings.has_database():
        try:
            default_store.lock_database()
        except DatabaseError:
            raise TaskException(
                "Could not lock database. This means that there are other "
                "clients connected. Make sure to close every Stoq client "
                "before updating the database")
        except Exception:
            raise TaskException(
                "Database is empty or in a corrupted state. Fix or drop it "
                "before trying to proceed with the restore")
        else:
            default_store.unlock_database()

        with tempfile.NamedTemporaryFile() as f:
            if not db_settings.dump_database(f.name):
                raise TaskException("Failed to dump the database")
            backup_name = db_settings.restore_database(f.name)
            logger.info("Created a backup of the current database state on %s",
                        backup_name)

    tmp_path = tempfile.mkdtemp()
    try:
        # None will make the default store be closed, which we need
        # to sucessfully restore the database
        set_default_store(None)
        restore_path = os.path.join(tmp_path, 'stoq')

        backup.restore(restore_path, user_hash, time=time)

        db_settings.clean_database(db_settings.dbname, force=True)
        db_settings.execute_sql(os.path.join(restore_path, 'stoq.dump'),
                                lock_database=True)

        logger.info("Backup restore finished sucessfully")
    finally:
        # get_default_store will recreate it (since we closed it above)
        get_default_store()
        shutil.rmtree(tmp_path, ignore_errors=True)
开发者ID:fuinha,项目名称:stoq-server,代码行数:49,代码来源:tasks.py

示例6: testCacheInvalidation

    def testCacheInvalidation(self):
        # First create a new person in an outside transaction
        outside_store = new_store()
        outside_person = Person(name=u'doe', store=outside_store)
        outside_store.commit()

        # Get this person in the default store
        default_store = get_default_store()
        db_person = default_store.find(Person, id=outside_person.id).one()
        self.assertEqual(db_person.name, u'doe')

        # Now, select that same person in an inside store
        inside_store = new_store()
        inside_person = inside_store.fetch(outside_person)

        # Change and commit the changes on this inside store
        inside_person.name = u'john'

        # Flush to make sure the database was updated
        inside_store.flush()

        # Before comminting the other persons should still be 'doe'
        self.assertEqual(db_person.name, u'doe')
        self.assertEqual(outside_person.name, u'doe')

        inside_store.commit()

        # We expect the changes to reflect on the connection
        self.assertEqual(db_person.name, u'john')

        # and also on the outside store
        self.assertEqual(outside_person.name, u'john')

        outside_store.close()
        inside_store.close()
开发者ID:marianaanselmo,项目名称:stoq,代码行数:35,代码来源:test_transaction.py

示例7: _check_param_online_services

    def _check_param_online_services(self):
        from stoqlib.database.runtime import get_default_store, new_store
        from stoqlib.lib.parameters import sysparam
        import gtk

        sparam = sysparam(get_default_store())
        if sparam.ONLINE_SERVICES is None:
            from kiwi.ui.dialogs import HIGAlertDialog
            # FIXME: All of this is to avoid having to set markup as the default
            #        in kiwi/ui/dialogs:HIGAlertDialog.set_details, after 1.0
            #        this can be simplified when we fix so that all descriptions
            #        sent to these dialogs are properly escaped
            dialog = HIGAlertDialog(
                parent=None,
                flags=gtk.DIALOG_MODAL,
                type=gtk.MESSAGE_WARNING)
            dialog.add_button(_("Not right now"), gtk.RESPONSE_NO)
            dialog.add_button(_("Enable online services"), gtk.RESPONSE_YES)

            dialog.set_primary(_('Do you want to enable Stoq online services?'))
            dialog.set_details(PRIVACY_STRING, use_markup=True)
            dialog.set_default_response(gtk.RESPONSE_YES)
            response = dialog.run()
            dialog.destroy()
            store = new_store()
            sysparam(store).ONLINE_SERVICES = int(bool(response == gtk.RESPONSE_YES))
            store.commit()
            store.close()
开发者ID:qman1989,项目名称:stoq,代码行数:28,代码来源:shell.py

示例8: _create_eggs_cache

    def _create_eggs_cache(self):
        log.info("Creating cache for plugins eggs")

        # $HOME/.stoq/plugins
        default_store = get_default_store()
        path = os.path.join(get_application_dir(), 'plugins')
        if not os.path.exists(path):
            os.makedirs(path)

        existing_eggs = {
            unicode(os.path.basename(f)[:-4]): md5sum_for_filename(f) for f in
            glob.iglob(os.path.join(path, '*.egg'))}

        # Now extract all eggs from the database and put it where stoq know
        # how to load them
        for plugin_name, egg_md5sum in default_store.using(PluginEgg).find(
                (PluginEgg.plugin_name, PluginEgg.egg_md5sum)):
            # A little optimization to avoid loading the egg in memory if we
            # already have a valid version cached.
            if existing_eggs.get(plugin_name, u'') == egg_md5sum:
                log.info("Plugin %r egg md5sum matches. Skipping it..." % (
                    plugin_name, ))
                continue

            log.info("Creating egg cache for plugin %r" % (plugin_name, ))
            egg_filename = '%s.egg' % (plugin_name, )
            plugin_egg = default_store.find(
                PluginEgg, plugin_name=plugin_name).one()

            with open(os.path.join(path, egg_filename), 'wb') as f:
                f.write(plugin_egg.egg_content)
开发者ID:amaurihamasu,项目名称:stoq,代码行数:31,代码来源:pluginmanager.py

示例9: download_plugin

    def download_plugin(self, plugin_name):
        """Download a plugin from webservice

        :param plugin_name: the name of the plugin to download
        :returns: a deferred
        """
        from stoqlib.lib.webservice import WebService

        def callback(filename):
            md5sum = unicode(md5sum_for_filename(filename))
            with open(filename) as f:
                with new_store() as store:
                    existing_egg = store.find(PluginEgg,
                                              plugin_name=plugin_name).one()
                    if existing_egg is not None:
                        existing_egg.egg_content = f.read()
                        existing_egg.md5sum = md5sum
                    else:
                        PluginEgg(
                            store=store,
                            plugin_name=plugin_name,
                            egg_md5sum=md5sum,
                            egg_content=f.read(),
                        )

            self._reload()

        default_store = get_default_store()
        existing_egg = default_store.find(PluginEgg,
                                          plugin_name=plugin_name).one()
        md5sum = existing_egg and existing_egg.egg_md5sum

        webapi = WebService()
        return webapi.download_plugin(plugin_name, callback=callback,
                                      md5sum=md5sum)
开发者ID:amaurihamasu,项目名称:stoq,代码行数:35,代码来源:pluginmanager.py

示例10: __init__

    def __init__(self):
        self._ui = None
        self.default_store = get_default_store()
        self._printer_verified = False
        # Delay printer creation until we are accessing pos or till app. Other
        # applications should still be accessible without a printer
        self._printer = None

        SaleStatusChangedEvent.connect(self._on_SaleStatusChanged)
        ECFIsLastSaleEvent.connect(self._on_ECFIsLastSale)
        TillOpenEvent.connect(self._on_TillOpen)
        TillCloseEvent.connect(self._on_TillClose)
        TillAddCashEvent.connect(self._on_TillAddCash)
        TillAddTillEntryEvent.connect(self._on_AddTillEntry)
        TillRemoveCashEvent.connect(self._on_TillRemoveCash)
        StartApplicationEvent.connect(self._on_StartApplicationEvent)
        StopApplicationEvent.connect(self._on_StopApplicationEvent)
        CouponCreatedEvent.connect(self._on_CouponCreatedEvent)
        GerencialReportPrintEvent.connect(self._on_GerencialReportPrintEvent)
        GerencialReportCancelEvent.connect(self._on_GerencialReportCancelEvent)
        CheckECFStateEvent.connect(self._on_CheckECFStateEvent)
        HasPendingReduceZ.connect(self._on_HasPendingReduceZ)
        HasOpenCouponEvent.connect(self._on_HasOpenCouponEvent)

        self._till_summarize_action = gtk.Action(
            'Summary', _('Summary'), None, None)
        self._till_summarize_action.connect(
            'activate', self._on_TillSummary__activate)

        add_bindings([
            ('plugin.ecf.read_memory', '<Primary>F9'),
            ('plugin.ecf.summarize', '<Primary>F11'),
        ])
开发者ID:LeonamSilva,项目名称:stoq,代码行数:33,代码来源:ecfui.py

示例11: _check_branch

    def _check_branch(self):
        from stoqlib.database.runtime import (get_default_store, new_store,
                                              get_current_station,
                                              set_current_branch_station)
        from stoqlib.domain.person import Company
        from stoqlib.lib.parameters import sysparam
        from stoqlib.lib.message import info

        default_store = get_default_store()

        compaines = default_store.find(Company)
        if (compaines.count() == 0 or
                not sysparam.has_object('MAIN_COMPANY')):
            from stoqlib.gui.base.dialogs import run_dialog
            from stoqlib.gui.dialogs.branchdialog import BranchDialog
            if self._ran_wizard:
                info(_("You need to register a company before start using Stoq"))
            else:
                info(_("Could not find a company. You'll need to register one "
                       "before start using Stoq"))
            store = new_store()
            person = run_dialog(BranchDialog, None, store)
            if not person:
                raise SystemExit
            branch = person.branch
            sysparam.set_object(store, 'MAIN_COMPANY', branch)
            current_station = get_current_station(store)
            if current_station is not None:
                current_station.branch = branch
            store.commit()
            store.close()

        set_current_branch_station(default_store, station_name=None)
开发者ID:hackedbellini,项目名称:stoq,代码行数:33,代码来源:shell.py

示例12: _get_interface

 def _get_interface(cls, iface):
     store = get_default_store()
     station = get_current_station(store)
     device = DeviceSettings.get_by_station_and_type(store, station, iface)
     if not device:
         return None
     return device.get_interface()
开发者ID:hackedbellini,项目名称:stoq,代码行数:7,代码来源:devicemanager.py

示例13: _build_field_cache

 def _build_field_cache(self):
     # Instead of making one query for each field, let's build a cache for
     # all fields at once. If there's no cache built yet, builds it.
     if self._field_cache:
         return
     default_store = get_default_store()
     for field in default_store.find(UIField):
         self._field_cache[(field.ui_form_id, field.field_name)] = field
开发者ID:EasyDevSolutions,项目名称:stoq,代码行数:8,代码来源:uiform.py

示例14: _enable_plugin

 def _enable_plugin(self, plugin_model):
     plugin_name = plugin_model.name
     # This should not really be necessary, but there may be deadlocks when
     # activating the plugin. See bug 5272
     default_store = get_default_store()
     default_store.commit()
     self._manager.install_plugin(plugin_name)
     self._manager.activate_plugin(plugin_name)
开发者ID:romaia,项目名称:stoq,代码行数:8,代码来源:pluginsdialog.py

示例15: __init__

    def __init__(self):
        super(ServiceImporter, self).__init__()
        default_store = get_default_store()
        self.tax_constant = SellableTaxConstant.get_by_type(
            TaxType.SERVICE, default_store)

        self._code = 11
        assert self.tax_constant
开发者ID:EasyDevSolutions,项目名称:stoq,代码行数:8,代码来源:serviceimporter.py


注:本文中的stoqlib.database.runtime.get_default_store函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。