Here are the examples of the python api django.db.close_old_connections taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
22 Examples
3
View Complete Implementation : routing.py
Copyright MIT License
Author : aduranil
Copyright MIT License
Author : aduranil
def __call__(self, scope):
try:
token_key = scope["query_string"].decode().split("=")[1]
if token_key:
token = Token.objects.get(key=token_key)
scope["user"] = token.user
close_old_connections()
except Token.DoesNotExist:
scope["user"] = AnonymousUser()
return self.inner(scope)
3
View Complete Implementation : commons.py
Copyright MIT License
Author : cuda-networks
Copyright MIT License
Author : cuda-networks
@contextmanager
def django_db_management():
# type: () -> None
reset_queries()
close_old_connections()
try:
yield
finally:
close_old_connections()
3
View Complete Implementation : base.py
Copyright Apache License 2.0
Author : edisonlz
Copyright Apache License 2.0
Author : edisonlz
def execute(self, query, args=None):
try:
# args is None means no string interpolation
# sql_statment = str(query).lower()
# c_time = datetime.datetime.now().strftime('%y-%m-%d %H:%M:%S')
# if 'select' not in sql_statment and 'homepublishedvideo' in sql_statment:
# print 'search_sql', c_time, query, args
return self.cursor.execute(query, args)
except Database.OperationalError as e:
# CR_SERVER_GONE_ERROR, CR_SERVER_LOST
if e.args[0] in (2006, 2013):
from django.db import close_old_connections
close_old_connections()
# Map some error codes to IntegrityError, since they seem to be
# misclastified and Django would prefer the more logical place.
if e.args[0] in self.codes_for_integrityerror:
six.reraise(utils.IntegrityError, utils.IntegrityError(*tuple(e.args)), sys.exc_info()[2])
raise
3
View Complete Implementation : base.py
Copyright Apache License 2.0
Author : edisonlz
Copyright Apache License 2.0
Author : edisonlz
def executemany(self, query, args):
try:
return self.cursor.executemany(query, args)
except Database.OperationalError as e:
if e.args[0] in (2006, 2013):
from django.db import close_old_connections
close_old_connections()
# Map some error codes to IntegrityError, since they seem to be
# misclastified and Django would prefer the more logical place.
if e.args[0] in self.codes_for_integrityerror:
six.reraise(utils.IntegrityError, utils.IntegrityError(*tuple(e.args)), sys.exc_info()[2])
raise
3
View Complete Implementation : monitor.py
Copyright Apache License 2.0
Author : erigones
Copyright Apache License 2.0
Author : erigones
def que_monitor_loop(server, worker):
log = worker.log
while True:
try:
que_monitor(cq, _info=log.info, _debug=log.debug)
except OPERATIONAL_ERRORS as ex:
log.exception(ex)
log.critical('Dedicated que event monitor terminated. Closing DB connection and restarting in 1 second...')
from django import db
db.close_old_connections()
except Exception as ex:
log.exception(ex)
log.critical('Dedicated que event monitor terminated. Restarting in 5 seconds...')
sleep(5)
3
View Complete Implementation : namespaces.py
Copyright Apache License 2.0
Author : erigones
Copyright Apache License 2.0
Author : erigones
def exception_handler_decorator(self, fun):
"""Close DB connection here - https://github.com/abourget/gevent-socketio/issues/174"""
def wrap(*args, **kwargs):
self.log('APINamespace.%s(%s, %s)', fun.__name__, args, kwargs, level=DEBUG)
try:
return fun(*args, **kwargs)
finally:
close_old_connections()
return wrap
3
View Complete Implementation : views.py
Copyright Apache License 2.0
Author : erigones
Copyright Apache License 2.0
Author : erigones
def socketio(request):
"""
Starting socket.io connection here.
"""
if request.user.is_authenticated():
if 'socketio' in request.environ:
socketio_manage(request.environ, namespaces={'': APINamespace}, request=request)
try:
return HttpResponse(None)
finally:
close_old_connections()
else:
return HttpResponse(None, status=204)
else:
raise PermissionDenied
3
View Complete Implementation : task_utils.py
Copyright GNU Affero General Public License v3.0
Author : LexPredict
Copyright GNU Affero General Public License v3.0
Author : LexPredict
@staticmethod
def prepare_task_execution():
"""
Clearing of old database connections for CONN_MAX_AGE option (database connection settings)
"""
if not TaskUtils.is_celery_worker():
return
try:
if TaskUtils.__connection_initialization_finished:
close_old_connections()
else:
for conn in connections.all():
conn.close()
TaskUtils.__connection_initialization_finished = True
except Exception:
past
3
View Complete Implementation : authentication.py
Copyright GNU Affero General Public License v3.0
Author : TheSpaghettiDetective
Copyright GNU Affero General Public License v3.0
Author : TheSpaghettiDetective
def __call__(self, scope):
close_old_connections()
headers = dict(scope['headers'])
try:
if b'authorization' in headers:
token_name, token_key = headers[b'authorization'].decode().split()
if token_name == 'bearer':
printer = Printer.objects.select_related('user').get(auth_token=token_key)
printer.is_authenticated = True # To make Printer duck-quack as authenticated User in Django Channels
scope['user'] = printer
elif scope['path'].startswith('/ws/shared/'):
printer = SharedResource.objects.select_related('printer').get(share_token=scope['path'].split('/')[-2]).printer # scope['path'].split('/')[-2] is the share_token in uri
printer.is_authenticated = True # To make Printer duck-quack as authenticated User in Django Channels
scope['user'] = printer
except ObjectDoesNotExist:
past
return self.inner(scope)
0
View Complete Implementation : graphql_ws_consumer.py
Copyright MIT License
Author : datadvance
Copyright MIT License
Author : datadvance
async def _run_in_worker(self, func):
"""Run a function in a thread with an event loop.
Run the `func` in a thread within a thread pool and wait for it
to finish. Each such thread has initialized event loop which is
NOT running. So the `func` can use it, for example by running
`asyncio.get_event_loop().run_until_complete(...)`. We also
cleanup Django database connections when `func` finishes.
Args:
func: The function to run in a thread.
Returns:
The result of the `func` invocation.
"""
# astert we run in a proper thread.
self._astert_thread()
def thread_func():
"""Wrap the `func` to init eventloop and to cleanup."""
# Create an eventloop if this worker thread does not have
# one yet. Eventually each worker will have its own
# eventloop for `func` can use it.
try:
loop = asyncio.get_event_loop()
except RuntimeError:
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
# Run a given function in a thread.
try:
return func()
finally:
# The `func` can open the connections to the database
# so let's close them. Django Channels does the same in
# the `channels.db.database_sync_to_async`.
django.db.close_old_connections()
return await asyncio.get_running_loop().run_in_executor(
self._workers, thread_func
)