├── .circleci └── config.yml ├── .gitignore ├── LICENSE ├── README.md ├── django_mysql_geventpool ├── __init__.py ├── backends │ ├── __init__.py │ ├── connection_pool.py │ ├── mysql │ │ ├── __init__.py │ │ ├── base.py │ │ ├── connection_pool.py │ │ └── creation.py │ └── mysql_gis │ │ ├── __init__.py │ │ └── base.py └── utils.py ├── setup.py ├── testproj ├── manage.py ├── testproj │ ├── __init__.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py └── tests │ ├── __init__.py │ ├── models.py │ └── tests.py └── tox.ini /.circleci/config.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | jobs: 3 | toxtest: 4 | docker: 5 | - image: circleci/python:3.6.7 6 | - image: mysql:5.7.22 7 | command: ["mysqld", "--character-set-server=utf8mb4", "--collation-server=utf8mb4_bin"] 8 | environment: 9 | - MYSQL_ROOT_PASSWORD: test 10 | - MYSQL_DATABASE: test_test 11 | - MYSQL_USER: test 12 | - MYSQL_PASSWORD: test 13 | steps: 14 | - checkout 15 | - run: 16 | name: venv 17 | command: | 18 | python3 -m venv venv 19 | . venv/bin/activate 20 | pip install tox 21 | - run: 22 | name: Wait for db 23 | command: dockerize -wait tcp://localhost:3306 -timeout 1m 24 | - run: 25 | name: test 26 | command: | 27 | . venv/bin/activate 28 | tox 29 | workflows: 30 | version: 2 31 | test: 32 | jobs: 33 | - toxtest -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | *.egg-info/ 24 | .installed.cfg 25 | *.egg 26 | MANIFEST 27 | 28 | # PyInstaller 29 | # Usually these files are written by a python script from a template 30 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 31 | *.manifest 32 | *.spec 33 | 34 | # Installer logs 35 | pip-log.txt 36 | pip-delete-this-directory.txt 37 | 38 | # Unit test / coverage reports 39 | htmlcov/ 40 | .tox/ 41 | .coverage 42 | .coverage.* 43 | .cache 44 | nosetests.xml 45 | coverage.xml 46 | *.cover 47 | .hypothesis/ 48 | .pytest_cache/ 49 | 50 | # Translations 51 | *.mo 52 | *.pot 53 | 54 | # Django stuff: 55 | *.log 56 | local_settings.py 57 | db.sqlite3 58 | 59 | # Flask stuff: 60 | instance/ 61 | .webassets-cache 62 | 63 | # Scrapy stuff: 64 | .scrapy 65 | 66 | # Sphinx documentation 67 | docs/_build/ 68 | 69 | # PyBuilder 70 | target/ 71 | 72 | # Jupyter Notebook 73 | .ipynb_checkpoints 74 | 75 | # pyenv 76 | .python-version 77 | 78 | # celery beat schedule file 79 | celerybeat-schedule 80 | 81 | # SageMath parsed files 82 | *.sage.py 83 | 84 | # Environments 85 | .env 86 | .venv 87 | env/ 88 | venv/ 89 | ENV/ 90 | env.bak/ 91 | venv.bak/ 92 | 93 | # Spyder project settings 94 | .spyderproject 95 | .spyproject 96 | 97 | # Rope project settings 98 | .ropeproject 99 | 100 | # mkdocs documentation 101 | /site 102 | 103 | # mypy 104 | .mypy_cache/ 105 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # django-mysql-geventpool 2 | 3 | [![CircleCI](https://circleci.com/gh/shunsukeaihara/django-mysql-geventpool/tree/master.svg?style=svg)](https://circleci.com/gh/shunsukeaihara/django-mysql-geventpool/tree/master) 4 | 5 | Mysql Connection Pooling backend for Django 2.0+ using gevent, only supports Python 3.4 or newer. 6 | It works with gunicorn async worker via gevent. 7 | 8 | This implimentation is based on django-db-geventpool(https://github.com/jneight/django-db-geventpool). 9 | 10 | ## install 11 | 12 | ``` 13 | pip install django-mysql-geventpool 14 | ``` 15 | 16 | ## Settings 17 | 18 | Add the 'django_mysql_geventpool' modules to the INSTALLED_APPS like this: 19 | 20 | ``` 21 | INSTALLED_APPS = ( 22 | 'django.contrib.admin', 23 | 'django.contrib.auth', 24 | 'django.contrib.contenttypes', 25 | 'django.contrib.sessions', 26 | 'django.contrib.messages', 27 | 'django.contrib.staticfiles', 28 | 'django_mysql_geventpool', 29 | # ...other installed applications... 30 | ) 31 | 32 | ``` 33 | 34 | Add MAX_CONNS to OPTIONS to set the maximun number of connections allowed to database (default=4) 35 | 36 | ``` 37 | DATABASES = { 38 | 'default': { 39 | 'ENGINE': 'django_mysql_geventpool.backends.mysql', 40 | 'NAME': 'dbname', 41 | 'USER': 'dbuser', 42 | 'PASSWORD': 'dbpassword', 43 | 'HOST': 'dbhost', 44 | 'PORT': 'dbport', 45 | 'OPTIONS': { 46 | 'MAX_CONNS': 20, 47 | 'MAX_LIFETIME': 5 * 60 # connection lifetime in seconds, and if set 0, unlimited persistent connections if usable. default is 0. 48 | } 49 | } 50 | } 51 | ``` -------------------------------------------------------------------------------- /django_mysql_geventpool/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shunsukeaihara/django-mysql-geventpool/119d8bccc5a1b5a39fbcc82fcf7549acf0fc9073/django_mysql_geventpool/__init__.py -------------------------------------------------------------------------------- /django_mysql_geventpool/backends/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shunsukeaihara/django-mysql-geventpool/119d8bccc5a1b5a39fbcc82fcf7549acf0fc9073/django_mysql_geventpool/backends/__init__.py -------------------------------------------------------------------------------- /django_mysql_geventpool/backends/connection_pool.py: -------------------------------------------------------------------------------- 1 | import logging 2 | try: 3 | from gevent import queue 4 | except ImportError: 5 | from eventlet import queue 6 | 7 | logger = logging.getLogger('django.geventpool') 8 | 9 | 10 | class DatabaseConnectionPool(object): 11 | def __init__(self, maxsize=100, maxlifetime=0): 12 | self.maxsize = maxsize 13 | self.maxlifetime = maxlifetime 14 | self.pool = queue.Queue(maxsize=maxsize) 15 | self.size = 0 16 | 17 | def get(self, conn_params): 18 | if self.size >= self.maxsize or self.pool.qsize(): 19 | conn = self.pool.get() 20 | if not self.is_usable(conn): 21 | try: 22 | conn.close() 23 | except Exception: 24 | pass 25 | conn = self.create_connection(conn_params) 26 | return conn 27 | else: 28 | self.size += 1 29 | try: 30 | conn = self.create_connection(conn_params) 31 | except Exception: 32 | self.size -= 1 33 | raise 34 | return conn 35 | 36 | def put(self, item): 37 | if item is None: 38 | self.size -= 1 39 | return 40 | try: 41 | self.pool.put(item, timeout=2) 42 | except queue.Full: 43 | item.close() 44 | 45 | def closeall(self): 46 | while not self.pool.empty(): 47 | conn = self.pool.get_nowait() 48 | try: 49 | conn.close() 50 | except Exception: 51 | pass 52 | self.size = 0 53 | 54 | def create_connection(self, *args, **kwargs): 55 | raise NotImplementedError("create_connection") 56 | 57 | def is_usable(self, obj): 58 | raise NotImplementedError("is_usable") 59 | -------------------------------------------------------------------------------- /django_mysql_geventpool/backends/mysql/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shunsukeaihara/django-mysql-geventpool/119d8bccc5a1b5a39fbcc82fcf7549acf0fc9073/django_mysql_geventpool/backends/mysql/__init__.py -------------------------------------------------------------------------------- /django_mysql_geventpool/backends/mysql/base.py: -------------------------------------------------------------------------------- 1 | import logging 2 | try: 3 | from gevent.lock import Semaphore 4 | except ImportError: 5 | from eventlet.semaphore import Semaphore 6 | 7 | from django.db.backends.mysql.base import DatabaseWrapper as OriginalDatabaseWrapper 8 | from .creation import DatabaseCreation 9 | from .connection_pool import MysqlConnectionPool 10 | 11 | 12 | logger = logging.getLogger('django.geventpool') 13 | 14 | connection_pools = {} 15 | connection_pools_lock = Semaphore(value=1) 16 | 17 | DEFAULT_MAX_CONNS = 4 18 | DEFAULT_MAX_LIFETIME = 0 19 | 20 | 21 | class ConnectionPoolMixin(object): 22 | creation_class = DatabaseCreation 23 | 24 | def __init__(self, settings_dict, *args, **kwargs): 25 | def pop_max_conn(settings_dict): 26 | if "OPTIONS" in settings_dict: 27 | return settings_dict["OPTIONS"].pop("MAX_CONNS", DEFAULT_MAX_CONNS) 28 | else: 29 | return DEFAULT_MAX_CONNS 30 | 31 | def pop_max_lifetime(settings_dict): 32 | if "OPTIONS" in settings_dict: 33 | return settings_dict["OPTIONS"].pop("MAX_LIFETIME", DEFAULT_MAX_LIFETIME) 34 | else: 35 | return DEFAULT_MAX_LIFETIME 36 | self._pool = None 37 | settings_dict['CONN_MAX_AGE'] = 0 38 | self._max_cons = pop_max_conn(settings_dict) 39 | self._max_lifetime = pop_max_lifetime(settings_dict) 40 | super(ConnectionPoolMixin, self).__init__(settings_dict, *args, **kwargs) 41 | self.prepare_pool() 42 | 43 | def prepare_pool(self): 44 | self.pool 45 | 46 | @property 47 | def pool(self): 48 | if self._pool is not None: 49 | return self._pool 50 | connection_pools_lock.acquire() 51 | if self.alias not in connection_pools: 52 | self._pool = MysqlConnectionPool(self._max_cons, self._max_lifetime) 53 | connection_pools[self.alias] = self._pool 54 | else: 55 | self._pool = connection_pools[self.alias] 56 | connection_pools_lock.release() 57 | return self._pool 58 | 59 | def get_new_connection(self, conn_params): 60 | if self.connection is None: 61 | self.connection = self.pool.get(conn_params) 62 | self.closed_in_transaction = False 63 | return self.connection 64 | 65 | def _close(self): 66 | if self.connection is None: 67 | self.pool.closeall() 68 | else: 69 | with self.wrap_database_errors: 70 | if not self.in_atomic_block and not self.errors_occurred: 71 | self.pool.put(self.connection) 72 | else: 73 | self.pool.put(None) 74 | self.connection.close() 75 | 76 | def closeall(self): 77 | for pool in connection_pools.values(): 78 | pool.closeall() 79 | 80 | 81 | class DatabaseWrapper(ConnectionPoolMixin, OriginalDatabaseWrapper): 82 | pass 83 | -------------------------------------------------------------------------------- /django_mysql_geventpool/backends/mysql/connection_pool.py: -------------------------------------------------------------------------------- 1 | import datetime 2 | from django.core.exceptions import ImproperlyConfigured 3 | from django.utils import timezone 4 | from six import raise_from 5 | try: 6 | import MySQLdb as Database 7 | except ImportError as err: 8 | raise_from(ImproperlyConfigured( 9 | 'Error loading MySQLdb module.\n' 10 | 'Did you install mysqlclient? or install PyMySQL as MySQLdb' 11 | ), err) 12 | from ..connection_pool import DatabaseConnectionPool 13 | 14 | CREATED_AT_KEY = "created_at" 15 | 16 | 17 | class MysqlConnectionPool(DatabaseConnectionPool): 18 | def __init__(self, maxsize, maxlifetime): 19 | super(MysqlConnectionPool, self).__init__(maxsize, maxlifetime) 20 | 21 | def create_connection(self, conn_params): 22 | conn = Database.connect(**conn_params) 23 | setattr(conn, CREATED_AT_KEY, timezone.now()) 24 | return conn 25 | 26 | def is_usable(self, conn): 27 | if self.maxlifetime > 0: 28 | if not hasattr(conn, CREATED_AT_KEY): 29 | return False 30 | created_at = getattr(conn, CREATED_AT_KEY) 31 | if not created_at: 32 | return False 33 | td = datetime.timedelta(seconds=self.maxlifetime) 34 | if timezone.now() - created_at > td: 35 | return False 36 | try: 37 | conn.ping() 38 | except Database.Error: 39 | return False 40 | else: 41 | return True 42 | -------------------------------------------------------------------------------- /django_mysql_geventpool/backends/mysql/creation.py: -------------------------------------------------------------------------------- 1 | from django.db.backends.mysql.creation import DatabaseCreation as OriginalDatabaseCreation 2 | 3 | 4 | class DatabaseCreation(OriginalDatabaseCreation): 5 | def _create_test_db(self, verbosity, autoclobber, keepdb=False): 6 | self.connection.closeall() 7 | return super(DatabaseCreation, self)._create_test_db(verbosity, autoclobber, keepdb) 8 | 9 | def _destroy_test_db(self, test_database_name, verbosity): 10 | self.connection.closeall() 11 | return super(DatabaseCreation, self)._destroy_test_db(test_database_name, verbosity) 12 | -------------------------------------------------------------------------------- /django_mysql_geventpool/backends/mysql_gis/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shunsukeaihara/django-mysql-geventpool/119d8bccc5a1b5a39fbcc82fcf7549acf0fc9073/django_mysql_geventpool/backends/mysql_gis/__init__.py -------------------------------------------------------------------------------- /django_mysql_geventpool/backends/mysql_gis/base.py: -------------------------------------------------------------------------------- 1 | from ..mysql.base import ConnectionPoolMixin 2 | 3 | from django.contrib.gis.db.backends.mysql.base import DatabaseWrapper as GisDatabaseWrapper 4 | 5 | 6 | class DatabaseWrapper(ConnectionPoolMixin, GisDatabaseWrapper): 7 | pass 8 | -------------------------------------------------------------------------------- /django_mysql_geventpool/utils.py: -------------------------------------------------------------------------------- 1 | from functools import wraps 2 | 3 | from django.core.signals import request_finished 4 | 5 | 6 | def close_connection(f): 7 | @wraps(f) 8 | def wrapper(*args, **kwargs): 9 | try: 10 | return f(*args, **kwargs) 11 | finally: 12 | request_finished.send(sender='greenlet') 13 | return wrapper 14 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | from setuptools import setup, find_packages 2 | 3 | setup( 4 | name='django-mysql-geventpool', 5 | version='0.2.5', 6 | install_requires=['django>=1.11', 'gevent', 'six'], 7 | description='Add a MySQL connection pool for django using gevent', 8 | long_description=open("README.md").read(), 9 | long_description_content_type="text/markdown", 10 | packages=find_packages(), 11 | include_package_data=True, 12 | license='Apache 2.0', 13 | lassifiers=[ 14 | 'Environment :: Web Environment', 15 | 'Framework :: Django', 16 | 'Intended Audience :: Developers', 17 | 'License :: OSI Approved :: Apache Software License', 18 | 'Operating System :: OS Independent', 19 | 'Programming Language :: Python', 20 | 'Programming Language :: Python :: 3', 21 | 'Topic :: Software Development :: Libraries :: Application Frameworks', 22 | ], 23 | author='aihara', 24 | author_email='aihara@argmax.jp' 25 | ) 26 | -------------------------------------------------------------------------------- /testproj/manage.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import os 3 | import sys 4 | 5 | from six import raise_from 6 | 7 | if __name__ == '__main__': 8 | import gevent.monkey 9 | gevent.monkey.patch_all() 10 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'testproj.settings') 11 | try: 12 | from django.core.management import execute_from_command_line 13 | except ImportError as exc: 14 | raise_from(ImportError( 15 | "Couldn't import Django. Are you sure it's installed and " 16 | "available on your PYTHONPATH environment variable? Did you " 17 | "forget to activate a virtual environment?" 18 | ), exc) 19 | execute_from_command_line(sys.argv) 20 | -------------------------------------------------------------------------------- /testproj/testproj/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shunsukeaihara/django-mysql-geventpool/119d8bccc5a1b5a39fbcc82fcf7549acf0fc9073/testproj/testproj/__init__.py -------------------------------------------------------------------------------- /testproj/testproj/settings.py: -------------------------------------------------------------------------------- 1 | """ 2 | Django settings for testproj project. 3 | 4 | Generated by 'django-admin startproject' using Django 2.1.1. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/2.1/topics/settings/ 8 | 9 | For the full list of settings and their values, see 10 | https://docs.djangoproject.com/en/2.1/ref/settings/ 11 | """ 12 | 13 | import os 14 | import pymysql 15 | pymysql.install_as_MySQLdb() 16 | 17 | # Build paths inside the project like this: os.path.join(BASE_DIR, ...) 18 | BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) 19 | 20 | 21 | # Quick-start development settings - unsuitable for production 22 | # See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/ 23 | 24 | # SECURITY WARNING: keep the secret key used in production secret! 25 | SECRET_KEY = '@hko03u)0)jm7s@8$phkabhc%&iac)-vur!6f4m5)75fgn6k#u' 26 | 27 | # SECURITY WARNING: don't run with debug turned on in production! 28 | DEBUG = True 29 | 30 | ALLOWED_HOSTS = [] 31 | 32 | 33 | # Application definition 34 | 35 | INSTALLED_APPS = [ 36 | 'django.contrib.admin', 37 | 'django.contrib.auth', 38 | 'django.contrib.contenttypes', 39 | 'django.contrib.sessions', 40 | 'django.contrib.messages', 41 | 'django.contrib.staticfiles', 42 | 'django_mysql_geventpool', 43 | 'tests', 44 | ] 45 | 46 | MIDDLEWARE = [ 47 | 'django.middleware.security.SecurityMiddleware', 48 | 'django.contrib.sessions.middleware.SessionMiddleware', 49 | 'django.middleware.common.CommonMiddleware', 50 | 'django.middleware.csrf.CsrfViewMiddleware', 51 | 'django.contrib.auth.middleware.AuthenticationMiddleware', 52 | 'django.contrib.messages.middleware.MessageMiddleware', 53 | 'django.middleware.clickjacking.XFrameOptionsMiddleware', 54 | ] 55 | 56 | ROOT_URLCONF = 'testproj.urls' 57 | 58 | TEMPLATES = [ 59 | { 60 | 'BACKEND': 'django.template.backends.django.DjangoTemplates', 61 | 'DIRS': [], 62 | 'APP_DIRS': True, 63 | 'OPTIONS': { 64 | 'context_processors': [ 65 | 'django.template.context_processors.debug', 66 | 'django.template.context_processors.request', 67 | 'django.contrib.auth.context_processors.auth', 68 | 'django.contrib.messages.context_processors.messages', 69 | ], 70 | }, 71 | }, 72 | ] 73 | 74 | WSGI_APPLICATION = 'testproj.wsgi.application' 75 | 76 | 77 | # Database 78 | # https://docs.djangoproject.com/en/2.1/ref/settings/#databases 79 | 80 | DATABASES = { 81 | 'default': { 82 | 'ENGINE': 'django_mysql_geventpool.backends.mysql', 83 | 'NAME': 'test', 84 | 'USER': 'test', 85 | 'PASSWORD': 'test', 86 | 'ATOMIC_REQUESTS': False, 87 | 'CONN_MAX_AGE': 0, 88 | 'OPTIONS': { 89 | 'MAX_CONNS': 20, 90 | 'MAX_LIFETIME': 10 91 | } 92 | }, 93 | } 94 | 95 | 96 | # Password validation 97 | # https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators 98 | 99 | AUTH_PASSWORD_VALIDATORS = [ 100 | { 101 | 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', 102 | }, 103 | { 104 | 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', 105 | }, 106 | { 107 | 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', 108 | }, 109 | { 110 | 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', 111 | }, 112 | ] 113 | 114 | 115 | # Internationalization 116 | # https://docs.djangoproject.com/en/2.1/topics/i18n/ 117 | 118 | LANGUAGE_CODE = 'en-us' 119 | 120 | TIME_ZONE = 'UTC' 121 | 122 | USE_I18N = True 123 | 124 | USE_L10N = True 125 | 126 | USE_TZ = True 127 | 128 | 129 | # Static files (CSS, JavaScript, Images) 130 | # https://docs.djangoproject.com/en/2.1/howto/static-files/ 131 | 132 | STATIC_URL = '/static/' 133 | -------------------------------------------------------------------------------- /testproj/testproj/urls.py: -------------------------------------------------------------------------------- 1 | """testproj URL Configuration 2 | 3 | The `urlpatterns` list routes URLs to views. For more information please see: 4 | https://docs.djangoproject.com/en/2.1/topics/http/urls/ 5 | Examples: 6 | Function views 7 | 1. Add an import: from my_app import views 8 | 2. Add a URL to urlpatterns: path('', views.home, name='home') 9 | Class-based views 10 | 1. Add an import: from other_app.views import Home 11 | 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') 12 | Including another URLconf 13 | 1. Import the include() function: from django.urls import include, path 14 | 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) 15 | """ 16 | from django.contrib import admin 17 | try: 18 | from django.urls import path 19 | except: 20 | from django.conf.urls import url as path 21 | 22 | urlpatterns = [ 23 | path('admin/', admin.site.urls), 24 | ] 25 | -------------------------------------------------------------------------------- /testproj/testproj/wsgi.py: -------------------------------------------------------------------------------- 1 | """ 2 | WSGI config for testproj project. 3 | 4 | It exposes the WSGI callable as a module-level variable named ``application``. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/2.1/howto/deployment/wsgi/ 8 | """ 9 | 10 | import os 11 | 12 | from django.core.wsgi import get_wsgi_application 13 | 14 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'testproj.settings') 15 | 16 | application = get_wsgi_application() 17 | -------------------------------------------------------------------------------- /testproj/tests/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shunsukeaihara/django-mysql-geventpool/119d8bccc5a1b5a39fbcc82fcf7549acf0fc9073/testproj/tests/__init__.py -------------------------------------------------------------------------------- /testproj/tests/models.py: -------------------------------------------------------------------------------- 1 | from django.db import models 2 | 3 | 4 | class TestModel(models.Model): 5 | data = models.CharField(max_length=32, blank=True) 6 | 7 | def __str__(self): 8 | return str(self.pk) 9 | -------------------------------------------------------------------------------- /testproj/tests/tests.py: -------------------------------------------------------------------------------- 1 | from django.test import TestCase 2 | import gevent 3 | import gevent.monkey 4 | from django_mysql_geventpool.utils import close_connection 5 | from django.db import connections, transaction 6 | import random 7 | 8 | from .models import TestModel 9 | 10 | gevent.monkey.patch_all() 11 | 12 | 13 | @close_connection 14 | def multiple_connections(count, pk): 15 | for x in range(0, 20): 16 | assert TestModel.objects.count() == 2 17 | 18 | 19 | @close_connection 20 | def select_for_update_error(pk): 21 | try: 22 | with transaction.atomic(): 23 | obj = TestModel.objects.select_for_update().get(pk=pk) 24 | obj.data = 'a' 25 | obj.save() 26 | raise Exception 27 | except Exception: 28 | pass 29 | 30 | 31 | @close_connection 32 | def select_for_update(pk): 33 | try: 34 | with transaction.atomic(): 35 | obj = TestModel.objects.select_for_update().get(pk=pk) 36 | gevent.sleep(0.05) 37 | obj.data = 'a' 38 | obj.save() 39 | except Exception as e: 40 | print(e) 41 | 42 | 43 | @close_connection 44 | def create_obj(obj): 45 | setattr(obj, "obj", TestModel.objects.create(data="aaaaa")) 46 | setattr(obj, "obj2", TestModel.objects.create(data="bbbbb")) 47 | 48 | 49 | class ModelTest(TestCase): 50 | def setUp(self): 51 | gevent.spawn(create_obj, self).join() 52 | 53 | def test_model_save(self): 54 | obj2 = TestModel.objects.get(pk=self.obj.pk) 55 | self.assertEqual(self.obj.data, obj2.data) 56 | 57 | def test_connections(self): 58 | greenlets = [] 59 | for x in range(0, 50): 60 | greenlets.append(gevent.spawn(multiple_connections, x, self.obj.pk)) 61 | gevent.joinall(greenlets) 62 | self.assertEqual(connections['default'].pool.maxsize, 20) 63 | 64 | def test_select_for_update_fail(self): 65 | greenlets = [] 66 | for x in range(0, 100): 67 | greenlets.append(gevent.spawn(select_for_update_error, self.obj.pk)) 68 | gevent.joinall(greenlets) 69 | obj2 = TestModel.objects.get(pk=self.obj.pk) 70 | self.assertEqual(obj2.data, "aaaaa") 71 | 72 | def test_select_for_update(self): 73 | greenlets = [] 74 | for x in range(0, 500): 75 | greenlets.append(gevent.spawn(select_for_update, self.obj2.pk)) 76 | gevent.joinall(greenlets) 77 | obj2 = TestModel.objects.get(pk=self.obj2.pk) 78 | self.assertEqual(obj2.data, "a") 79 | -------------------------------------------------------------------------------- /tox.ini: -------------------------------------------------------------------------------- 1 | [tox] 2 | envlist = py27-dj111, py35-dj20, py35-dj21, py36-dj20, py36-dj21 3 | 4 | [testenv] 5 | basepython = 6 | py27: python2.7 7 | py35: python3.5 8 | py36: python3.6 9 | deps = 10 | pymysql 11 | gevent 12 | six 13 | dj20: Django>=2.0,<2.1 14 | dj21: Django>=2.1,<2.2 15 | dj22: Django>=2.2,<2.3 16 | dj111: Django>=1.11,<2.0 17 | commands = 18 | python -V 19 | python testproj/manage.py test tests --noinput 20 | 21 | [pep8] 22 | exclude = migrations,south_migrations,.tox,docs,test_proj,setup.py --------------------------------------------------------------------------------