python mysql 持久连接_python-Django持久数据库连接

我做了一些小的自定义psycopg2后端,该后端使用全局变量实现了持久连接。有了这个,我能够将每秒的请求数量从350改善到1600(在非常简单的页面上,很少有选择)只需将其保存在任何目录中名为base.py的文件中(例如postgresql_psycopg2_persistent)并在设置中进行设置

DATABASE_ENGINE到项目名称.postgresql_psycopg2_persistent

注意!!! 代码不是线程安全的-由于意外的结果,您不能将其与python线程一起使用,如果使用mod_wsgi,请在线程= 1时使用prefork守护程序模式

# Custom DB backend postgresql_psycopg2 based

# implements persistent database connection using global variable

from django.db.backends.postgresql_psycopg2.base import DatabaseError, DatabaseWrapper as BaseDatabaseWrapper, \

IntegrityError

from psycopg2 import OperationalError

connection = None

class DatabaseWrapper(BaseDatabaseWrapper):

def _cursor(self, *args, **kwargs):

global connection

if connection is not None and self.connection is None:

try: # Check if connection is alive

connection.cursor().execute('SELECT 1')

except OperationalError: # The connection is not working, need reconnect

connection = None

else:

self.connection = connection

cursor = super(DatabaseWrapper, self)._cursor(*args, **kwargs)

if connection is None and self.connection is not None:

connection = self.connection

return cursor

def close(self):

if self.connection is not None:

self.connection.commit()

self.connection = None

或者这是一个线程安全的线程,但是python线程不使用多个内核,因此您将不会获得像上一个内核那样的性能提升。 您也可以将其与多进程一起使用。

# Custom DB backend postgresql_psycopg2 based

# implements persistent database connection using thread local storage

from threading import local

from django.db.backends.postgresql_psycopg2.base import DatabaseError, \

DatabaseWrapper as BaseDatabaseWrapper, IntegrityError

from psycopg2 import OperationalError

threadlocal = local()

class DatabaseWrapper(BaseDatabaseWrapper):

def _cursor(self, *args, **kwargs):

if hasattr(threadlocal, 'connection') and threadlocal.connection is \

not None and self.connection is None:

try: # Check if connection is alive

threadlocal.connection.cursor().execute('SELECT 1')

except OperationalError: # The connection is not working, need reconnect

threadlocal.connection = None

else:

self.connection = threadlocal.connection

cursor = super(DatabaseWrapper, self)._cursor(*args, **kwargs)

if (not hasattr(threadlocal, 'connection') or threadlocal.connection \

is None) and self.connection is not None:

threadlocal.connection = self.connection

return cursor

def close(self):

if self.connection is not None:

self.connection.commit()

self.connection = None

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值