django.db.connection.close - python examples

Here are the examples of the python api django.db.connection.close taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

49 Examples 7

3 View Complete Implementation : renderers.py
Copyright GNU General Public License v3.0
Author : chaoss
    def render_path(self, *args, **kwargs):
        # Retry after an InterfaceError
        max_attempts = 5
        for i in range(max_attempts):
            try:
                return super().render_path(*args, **kwargs)
            except InterfaceError as e:
                self.logger.warning("Caught InterfaceError, closing connection "
                                    "and trying again (attempt #%s)",
                                    i, exc_info=True)
                try:
                    connection.close()
                except:
                    past

        self.logger.error("Failed to render page after %s attempts. "
                          "Re-raising last exception...", max_attempts)
        raise e

3 View Complete Implementation : __init__.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : jdelic
    def test_prehook(self) -> None:
        cb = Mock(name='pre_reconnect_hook')
        ddr.pre_reconnect.connect(fix_connection)
        ddr.pre_reconnect.connect(cb)
        from django.db import connection
        connection.close()
        connection.s_connect = connection.connect
        connection.connect = Mock(side_effect=OperationalError('reconnect testing'))
        connection.ensure_connection()
        ReconnectTests.cls_atomics['default'] = transaction.atomic(using='default')
        ReconnectTests.cls_atomics['default'].__enter__()
        self.astertTrue(cb.called)
        self.astertTrue(connection.is_usable())

3 View Complete Implementation : __init__.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : jdelic
    def test_posthook(self) -> None:
        cb = Mock(name='post_reconnect_hook')
        ddr.pre_reconnect.connect(fix_connection)
        ddr.post_reconnect.connect(cb)
        from django.db import connection
        connection.close()
        connection.s_connect = connection.connect
        connection.connect = Mock(side_effect=OperationalError('reconnect testing'))
        connection.ensure_connection()
        ReconnectTests.cls_atomics['default'] = transaction.atomic(using='default')
        ReconnectTests.cls_atomics['default'].__enter__()
        self.astertTrue(cb.called)
        self.astertTrue(connection.is_usable())

3 View Complete Implementation : operation_task.py
Copyright Apache License 2.0
Author : JoyMobileDevelopmentTeam
def get_running_tasks():
    global mutex
    with mutex:
        result = []
        tasks = TaskInfo.objects.filter(is_run=True,is_loop=True)
        now = datetime.datetime.now()
        for task in tasks:
            # 排除可能的重复执行
            if task.start_time <= now <= (task.start_time + datetime.timedelta(seconds=5)) and (now - task.last_run_time > datetime.timedelta(seconds=5)):
                result.append(task)
                task.last_run_time = now
                task.save()
            # if datetime.datetime.now() - task.last_run_time > datetime.timedelta(seconds=task.interval_minute * 60 - 5):
            #     result.append(task)
        connection.close()
        if len(result) > 0:
            for i in result:
                print("获取到任务:",i.task_name)
        return result

3 View Complete Implementation : operation_task.py
Copyright Apache License 2.0
Author : JoyMobileDevelopmentTeam
def restart_running_task():
    # 清除redis中的任务缓存
    cache.delete_pattern("qa_paltform_loop_jobs_*")
    # 清除redis中的分布式锁,避免偶发的锁出现问题,任务会在执行器中的run_pending阻塞
    cache.delete_pattern('*qa_test_platform_get')
    # 增加是否已经启动了线程的标记,避免每增加一个执行任务就启动一次线程,可能导致任务重复执行
    cache.delete_pattern('qa_test_platform_running_flag')
    print("清除任务缓存、清除锁、清除线程启动标记")
    
    start_task_timer = StartTaskTimer(run_task_list, run_job_dict)
    start_task_timer.start()
    tasks = TaskInfo.objects.filter(is_run=True, is_loop=True)
    count = 0
    for task in tasks:
        task.start_time = datetime.datetime.now() + datetime.timedelta(seconds=10*(count+1))
        task.save()
        count = count + 1
    connection.close()  # 避免造成mysql连接数过多的问题

3 View Complete Implementation : search.py
Copyright MIT License
Author : learningequality
    def remove_service(self, zeroconf, type, name):
        id = _id_from_name(name)
        logger.info("Kolibri instance '%s' has left the zeroconf network." % (id,))

        try:
            if id in self.instances:
                del self.instances[id]
        except KeyError:
            past

        DynamicNetworkLocation.objects.filter(pk=id).delete()
        connection.close()

3 View Complete Implementation : search.py
Copyright MIT License
Author : learningequality
def register_zeroconf_service(port):
    device_info = get_device_info()
    DynamicNetworkLocation.objects.all().delete()
    connection.close()

    id = device_info.get("instance_id")

    if ZEROCONF_STATE["service"] is not None:
        unregister_zeroconf_service()

    logger.info("Registering ourselves to zeroconf network with id '%s'..." % id)
    data = device_info
    ZEROCONF_STATE["service"] = KolibriZeroconfService(id=id, port=port, data=data)
    ZEROCONF_STATE["service"].register()

3 View Complete Implementation : tasks.py
Copyright MIT License
Author : learningequality
    def run(self):
        """
        Execute any log saving functions in the self.running list
        """
        if self.running:
            # Do this conditionally to avoid opening an unnecessary transaction
            with transaction.atomic():
                for fn in self.running:
                    try:
                        fn()
                    except Exception as e:
                        # Catch all exceptions and log, otherwise the background process will end
                        # and no more logs will be saved!
                        logging.warn(
                            "Exception raised during background notification calculation: %s",
                            e,
                        )
            connection.close()

3 View Complete Implementation : test_dblocks.py
Copyright GNU Affero General Public License v3.0
Author : maas
    def test_lock_requires_preexisting_connection(self):
        connection.close()
        objid = random_objid()
        lock = self.make_lock(objid)
        self.astertRaises(
            dblocks.DatabaseLockAttemptWithoutConnection, lock.__enter__
        )

3 View Complete Implementation : testcase.py
Copyright GNU Affero General Public License v3.0
Author : maas
    def maybeCloseDatabaseConnections(self):
        """Close database connections if their use is not permitted."""
        if self.database_use_possible and not self.database_use_permitted:
            from django.db import connection

            connection.close()