├── .gitignore ├── .travis.yml ├── HISTORY.md ├── LICENSE ├── MANIFEST.in ├── README.md ├── django_sae ├── __init__.py ├── cache │ ├── __init__.py │ ├── backends.py │ ├── managers.py │ ├── models.py │ └── tests │ │ ├── __init__.py │ │ ├── base.py │ │ ├── models.py │ │ ├── test_backends.py │ │ ├── test_managers.py │ │ └── test_models.py ├── conf │ ├── __init__.py │ └── settings.py ├── contrib │ ├── __init__.py │ └── tasks │ │ ├── __init__.py │ │ ├── cron.py │ │ ├── models.py │ │ ├── operations.py │ │ ├── settings.py │ │ ├── tests │ │ ├── __init__.py │ │ ├── base.py │ │ ├── operations.py │ │ ├── test_cron.py │ │ ├── test_operations.py │ │ ├── test_views.py │ │ └── views.py │ │ ├── urls.py │ │ └── views.py ├── db │ ├── __init__.py │ ├── models.py │ ├── repository.py │ ├── routers.py │ └── utils.py ├── management │ ├── __init__.py │ └── commands │ │ ├── __init__.py │ │ ├── compress_site_packages.py │ │ ├── sae_migrate.py │ │ └── upgrade_requirements.py └── utils │ ├── __init__.py │ ├── counts.py │ ├── decorators.py │ ├── log.py │ ├── taskqueue.py │ ├── text.py │ └── timestamp.py ├── requirements.txt ├── setup.py └── tests ├── __init__.py ├── conf ├── __init__.py └── test_settings.py ├── db ├── __init__.py ├── test_models.py ├── test_repository.py ├── test_routers.py └── test_utils.py ├── downloads └── requests-master.zip ├── index.wsgi ├── management ├── __init__.py ├── base.py ├── test_compress_site_packages.py ├── test_sae_migrate.py └── test_upgrade_requirements.py ├── models.py ├── requirements.txt ├── settings.py ├── urls.py └── utils ├── __init__.py ├── test_counts.py ├── test_decorators.py ├── test_log.py ├── test_taskqueue.py ├── test_text.py └── test_timestamp.py /.gitignore: -------------------------------------------------------------------------------- 1 | *.py[cod] 2 | 3 | # C extensions 4 | *.so 5 | 6 | # Packages 7 | *.egg 8 | *.egg-info 9 | dist 10 | build 11 | eggs 12 | parts 13 | bin 14 | var 15 | sdist 16 | develop-eggs 17 | .installed.cfg 18 | lib 19 | lib64 20 | __pycache__ 21 | 22 | # Installer logs 23 | pip-log.txt 24 | 25 | # Unit test / coverage reports 26 | .coverage 27 | .tox 28 | nosetests.xml 29 | 30 | # Translations 31 | *.mo 32 | 33 | # Mr Developer 34 | .mr.developer.cfg 35 | .project 36 | .pydevproject 37 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: python 2 | python: 3 | - "2.7" 4 | # command to install dependencies 5 | install: "pip install -r requirements.txt" 6 | # command to run tests 7 | script: nosetests -------------------------------------------------------------------------------- /HISTORY.md: -------------------------------------------------------------------------------- 1 | .. :changelog: 2 | 3 | Release History 4 | --------------- 5 | 6 | 0.2.1 (2014-06-27) 7 | ++++++++++++++++++ 8 | 9 | - 删除模块:http(Django1.7已支持JsonResponse) 10 | - 修改设置:LANGUAGE_CODE为zh-hans(zh-cn从1.9版本后弃用) 11 | 12 | 0.2.0 (2014-05-17) 13 | ++++++++++++++++++ 14 | 15 | - 修改扩展命令:sae_migrate(使用Django1.7自带的migrate命令) 16 | - 删除扩展命令:sae_syncdb(Django1.7已移除syncdb命令) 17 | 18 | 0.1.23 (2014-03-21) 19 | ++++++++++++++++++ 20 | 21 | - 添加日志过滤器:RequireInSAE,RequireNotInSAE 22 | 23 | 0.1.21 (2014-03-20) 24 | ++++++++++++++++++ 25 | 26 | - 删除扩展命令:sae_schemamigration(因为此命令不需要链接SAE数据库) 27 | 28 | 0.1.18 (2014-03-19) 29 | ++++++++++++++++++ 30 | 31 | - 添加扩展命令:upgrade_requirements 32 | 33 | 0.1.13 (2014-03-18) 34 | ++++++++++++++++++ 35 | 36 | - 重命名扩展命令: updatepackages -> compress_site_packages, 37 | - 添加扩展命令:sae_migrate, sae_schemamigration, sae_syncdb 38 | 39 | 0.1.11 (2014-03-17) 40 | ++++++++++++++++++ 41 | 42 | - commands(扩展命令): updatepackages(更新依赖库并压缩为site-packages.zip) 43 | 44 | 0.1.1 (2014-03-16) 45 | ++++++++++++++++++ 46 | 47 | - patches: 自动设置 48 | - conf: SAE平台的默认设置 49 | 50 | 0.1.0 (2014-03-15) 51 | ++++++++++++++++++ 52 | 53 | - db: 通用模型和读写分离 54 | - cache: 缓存模型 55 | - utils: 时间戳模块和装饰模块 56 | - tasks: 用于执行任务 -------------------------------------------------------------------------------- /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 | 203 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include README.md HISTORY.md -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | #django-sae 2 | 3 | [![PyPI version](https://badge.fury.io/py/django-sae.png)](http://badge.fury.io/py/django-sae) 4 | 5 | 用于新浪云平台SAE 6 | 7 | ### 扩展命令 8 | * compress_site_packages:压缩 site_packages 9 | * upgrade_requirements:更新requirements.txt中所有依赖的库 10 | * sae_migrate:切换到SAE数据库,并进行migrate操作 11 | 12 | 使用sae_migrate等与数据库相关的扩展命令时,请手工获取SAE数据库的相关常数,如MYSQL_DB、MYSQL_USER、MYSQL_PASS等,并在settings中对DATABASES进行修改。 13 | 14 | ### 数据库 15 | 如需数据库读写操作分离,请在settings中进行设置(示例如下): 16 | ```python 17 | from sae.const import MYSQL_HOST, MYSQL_HOST_S, MYSQL_PORT, MYSQL_USER, MYSQL_PASS, MYSQL_DB 18 | DATABASES = { 19 | 'default': { 20 | 'ENGINE': 'django.db.backends.mysql', 21 | 'NAME': MYSQL_DB, 22 | 'USER': MYSQL_USER, 23 | 'PASSWORD': MYSQL_PASS, 24 | 'HOST': MYSQL_HOST, 25 | 'PORT': MYSQL_PORT, 26 | 'OPTIONS': {'init_command': "SET storage_engine=MYISAM;"}, 27 | }, 28 | 'slave': { 29 | 'ENGINE': 'django.db.backends.mysql', 30 | 'NAME': MYSQL_DB, 31 | 'USER': MYSQL_USER, 32 | 'PASSWORD': MYSQL_PASS, 33 | 'HOST': MYSQL_HOST_S, 34 | 'PORT': MYSQL_PORT, 35 | 'OPTIONS': {'init_command': "SET storage_engine=MYISAM;"}, 36 | }, 37 | } 38 | DATABASE_ROUTERS = ['django_sae.db.routers.MasterSlaveRouter'] 39 | ``` 40 | 41 | ### 缓存 42 | 使用 SAE Memcache 服务时,请在settings中进行设置(示例如下): 43 | ```python 44 | CACHES={ 45 | 'default': { 46 | 'BACKEND': 'django_sae.cache.backends.SaePyLibMCCache', 47 | } 48 | } 49 | ``` 50 | 51 | ### 日志 52 | 使用日志过滤器RequireInSAE和RequireNotInSAE时,请在settings中进行设置(示例如下): 53 | ```python 54 | LOGGING = { 55 | 'version': 1, 56 | 'disable_existing_loggers': True, 57 | 'filters': { 58 | 'require_in_sae': { 59 | '()': 'django_sae.utils.log.RequireInSAE', 60 | }, 61 | 'require_not_in_sae': { 62 | '()': 'django_sae.utils.log.RequireNotInSAE', 63 | }, 64 | }, 65 | 'handlers': { 66 | 'console': { 67 | 'level': 'DEBUG', 68 | 'class': 'logging.StreamHandler', 69 | 'filters': [ 'require_in_sae'], 70 | }, 71 | }, 72 | 'loggers': { 73 | 'django': { 74 | 'handlers': ['console'], 75 | }, 76 | } 77 | } 78 | ``` 79 | 80 | -------------------------------------------------------------------------------- /django_sae/__init__.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | 3 | 4 | __title__ = 'django_sae' 5 | __version__ = '0.2.1' 6 | __author__ = 'smallcode (45945756@qq.com)' 7 | __license__ = 'Apache 2.0' -------------------------------------------------------------------------------- /django_sae/cache/__init__.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | -------------------------------------------------------------------------------- /django_sae/cache/backends.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | from threading import local 3 | from django.core.cache.backends.memcached import BaseMemcachedCache 4 | 5 | 6 | class SaePyLibMCCache(BaseMemcachedCache): 7 | """ 8 | see: http://sae.sina.com.cn/?m=devcenter&catId=291#anchor_6c1bc2dacfd850c36fc3db0ec84e9ab3 9 | http://sae.sina.com.cn/?m=devcenter&catId=292#anchor_7267dff3baebb5655c19095bce390a7a 10 | """ 11 | 12 | def __init__(self, server, params): 13 | import pylibmc 14 | 15 | self._local = local() 16 | #pylibmc.NotFound需更改为None,否则在本地会出现错误,模拟的sae.memcache中没有NotFound属性 17 | super(SaePyLibMCCache, self).__init__(server, params, library=pylibmc, value_not_found_exception=None) 18 | 19 | @property 20 | def _cache(self): 21 | client = getattr(self._local, 'client', None) 22 | if client: 23 | return client 24 | 25 | client = self._lib.Client() # Client不需要传入参数 26 | if self._options: 27 | client.behaviors = self._options 28 | 29 | self._local.client = client 30 | 31 | return client 32 | -------------------------------------------------------------------------------- /django_sae/cache/managers.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | 3 | 4 | class Manager(object): 5 | def __init__(self): 6 | self.instance = None 7 | 8 | def __get__(self, instance, model): 9 | if instance is not None and instance.pk is None: 10 | raise ValueError( 11 | "%s objects need to have a primary key value before you can access their bans." % model.__name__) 12 | self.instance = instance 13 | return self 14 | 15 | def __getattribute__(self, item): 16 | if item != 'instance' and self.instance is None: 17 | raise ValueError(u'%s必须通过实例调用', item) 18 | return super(Manager, self).__getattribute__(item) -------------------------------------------------------------------------------- /django_sae/cache/models.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | from logging import getLogger 3 | 4 | from django.core.cache import cache 5 | from django_sae.utils.timestamp import make_timestamp, to_datetime 6 | 7 | 8 | log = getLogger('django.cache') 9 | 10 | 11 | class Model(object): 12 | KEYS = () 13 | VALUES = () 14 | 15 | def __init__(self, expires_in): 16 | self.expired_at = None 17 | self.expires_in = expires_in 18 | 19 | @property 20 | def key(self): 21 | keys = [] 22 | for attr in self.KEYS: 23 | value = getattr(self, attr) 24 | if value is None: 25 | raise KeyError(u'组装键时出现错误:属性{0}的值不能为None'.format(attr)) 26 | keys.append(str(value)) 27 | keys.insert(0, self.__class__.__name__) 28 | return '_'.join(keys) 29 | 30 | @property 31 | def value(self): 32 | values = {} 33 | attr_list = list(self.VALUES) 34 | attr_list.append('expired_at') 35 | for attr in attr_list: 36 | value = getattr(self, attr) 37 | if value is None: 38 | raise ValueError(u'属性{0}的值不能为None'.format(attr)) 39 | values[attr] = value 40 | return values 41 | 42 | def _get_expires_in(self): 43 | if self.expired_at: 44 | return self.expired_at - make_timestamp() 45 | 46 | def _set_expires_in(self, expires_in): 47 | if expires_in: 48 | self.expired_at = int(expires_in) + make_timestamp() 49 | 50 | expires_in = property(_get_expires_in, _set_expires_in) 51 | 52 | def load_values(self, **values): 53 | for key, value in values.items(): 54 | setattr(self, key, value) 55 | 56 | def load_cache(self): 57 | values = cache.get(self.key) 58 | if values is not None: 59 | self.load_values(**values) 60 | 61 | @property 62 | def is_expires(self): 63 | return self.expired_at is None or make_timestamp() >= self.expired_at 64 | 65 | def save(self): 66 | if not self.is_expires: 67 | log.debug(u'[{2}][缓存]{0}:{1}'.format(self.key, self.value, to_datetime(self.expired_at))) 68 | # times秒数如果大于30天,则需传入到期时间的时间戳(且必须为整数) 69 | cache.set(self.key, self.value, int(self.expired_at)) 70 | 71 | def delete(self): 72 | self.expired_at = None 73 | cache.delete(self.key) 74 | 75 | -------------------------------------------------------------------------------- /django_sae/cache/tests/__init__.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | -------------------------------------------------------------------------------- /django_sae/cache/tests/base.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | from django.test import SimpleTestCase 3 | from django.test.utils import override_settings 4 | from django.core.cache import cache 5 | 6 | 7 | @override_settings( 8 | CACHES={ 9 | 'default': { 10 | 'BACKEND': 'django_sae.cache.backends.SaePyLibMCCache', 11 | } 12 | }) 13 | class CacheTestBase(SimpleTestCase): 14 | def tearDown(self): 15 | cache.clear() 16 | 17 | 18 | class ModelTestBase(CacheTestBase): 19 | def assertCache(self, model): 20 | model.save() 21 | self.assertEqual(cache.get(model.key), model.value) 22 | 23 | def assertNotCache(self, model): 24 | model.save() 25 | self.assertIsNone(cache.get(model.key)) 26 | 27 | def assertIsExpires(self, model): 28 | self.assertTrue(model.is_expires) 29 | 30 | def assertIsNotExpires(self, model): 31 | self.assertFalse(model.is_expires) -------------------------------------------------------------------------------- /django_sae/cache/tests/models.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | from django_sae.cache import models 3 | 4 | 5 | class ModelMock(models.Model): 6 | KEYS = ('uid',) 7 | VALUES = ('name',) 8 | 9 | def __init__(self, uid, name, expires_in=None): 10 | super(ModelMock, self).__init__(expires_in) 11 | self.uid = uid 12 | self.name = name 13 | 14 | 15 | class ManagerModelMock(object): 16 | def __init__(self, pk): 17 | self.pk = pk -------------------------------------------------------------------------------- /django_sae/cache/tests/test_backends.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | from django_sae.cache.tests.base import CacheTestBase 3 | from django.core.cache import cache 4 | 5 | 6 | class CacheTest(CacheTestBase): 7 | def test_cache(self): 8 | key = 'my_key' 9 | value = 'hello, world!' 10 | cache.set(key, value, 3) 11 | self.assertEqual(cache.get(key), value) -------------------------------------------------------------------------------- /django_sae/cache/tests/test_managers.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | from django_sae.cache.managers import Manager 3 | from django_sae.cache.tests.base import CacheTestBase 4 | from django_sae.cache.tests.models import ManagerModelMock 5 | 6 | 7 | class ManagerMock(ManagerModelMock): 8 | manager = Manager() 9 | 10 | 11 | class ManagerTest(CacheTestBase): 12 | def setUp(self): 13 | self.obj = ManagerMock(123) 14 | 15 | def test_get(self): 16 | self.assertEqual(self.obj.manager.instance, self.obj) 17 | 18 | def test_value_error(self): 19 | self.assertRaises(ValueError, lambda: ManagerMock(None).manager.instance) 20 | self.assertRaises(ValueError, lambda: ManagerMock.manager.func()) -------------------------------------------------------------------------------- /django_sae/cache/tests/test_models.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | import time 3 | 4 | from django_sae.cache.tests.base import ModelTestBase 5 | from django_sae.cache.tests.models import ModelMock 6 | 7 | 8 | class ModelTest(ModelTestBase): 9 | def setUp(self): 10 | self.name = 'name' 11 | self.expires_in = 3 12 | self.uid = 123 13 | 14 | def test_save(self): 15 | model = ModelMock('123', self.name, self.expires_in) 16 | self.assertIsNotExpires(model) 17 | self.assertEqual(model.expires_in, model.expires_in) 18 | self.assertEqual(model.key, 'ModelMock_123') 19 | self.assertEqual(model.value['name'], 'name') 20 | self.assertGreater(model.value['expired_at'], time.time()) 21 | self.assertCache(model) 22 | 23 | def test_delete(self): 24 | model = ModelMock('123', self.name, self.expires_in) 25 | model.save() 26 | model.delete() 27 | self.assertIsExpires(model) 28 | self.assertIsExpires(ModelMock('123', self.name)) 29 | 30 | def test_load_cache(self): 31 | ModelMock(self.uid, self.name, self.expires_in).save() 32 | model = ModelMock(self.uid, self.name) 33 | model.load_cache() 34 | self.assertIsNotExpires(model) 35 | 36 | def test_is_expires(self): 37 | model = ModelMock(self.uid, self.name, expires_in=-1) 38 | self.assertIsExpires(model) 39 | self.assertNotCache(model) 40 | 41 | def test_none_expires_in(self): 42 | model = ModelMock(self.uid, self.name, expires_in=None) 43 | self.assertIsExpires(model) 44 | self.assertNotCache(model) 45 | 46 | def test_key_error(self): 47 | model = ModelMock(None, self.name, self.expires_in) 48 | self.assertRaises(KeyError, lambda: model.save()) 49 | 50 | def test_value_error(self): 51 | model = ModelMock(self.uid, None, self.expires_in) 52 | self.assertRaises(ValueError, lambda: model.save()) 53 | 54 | 55 | 56 | 57 | 58 | -------------------------------------------------------------------------------- /django_sae/conf/__init__.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | -------------------------------------------------------------------------------- /django_sae/conf/settings.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | import os 3 | import sys 4 | from sae.const import MYSQL_HOST, MYSQL_PORT, MYSQL_USER, MYSQL_PASS, MYSQL_DB, MYSQL_HOST_S 5 | 6 | # 重载字符集 7 | reload(sys) 8 | sys.setdefaultencoding('utf8') 9 | 10 | IN_SAE = 'SERVER_SOFTWARE' in os.environ # 是否在SAE引擎上运行 11 | 12 | DATABASES = { 13 | 'default': { 14 | 'ENGINE': 'django.db.backends.mysql', 15 | 'NAME': MYSQL_DB, 16 | 'USER': MYSQL_USER, 17 | 'PASSWORD': MYSQL_PASS, 18 | 'HOST': MYSQL_HOST, 19 | 'PORT': MYSQL_PORT, 20 | 'OPTIONS': {'init_command': "SET storage_engine=MYISAM;"}, 21 | }, 22 | 'slave': { 23 | 'ENGINE': 'django.db.backends.mysql', 24 | 'NAME': MYSQL_DB, 25 | 'USER': MYSQL_USER, 26 | 'PASSWORD': MYSQL_PASS, 27 | 'HOST': MYSQL_HOST_S, 28 | 'PORT': MYSQL_PORT, 29 | 'OPTIONS': {'init_command': "SET storage_engine=MYISAM;"}, 30 | }, 31 | } 32 | 33 | CACHES = { 34 | 'default': { 35 | 'BACKEND': 'django_sae.cache.backends.SaePyLibMCCache', 36 | 'TIMEOUT': 86400, 37 | 'VERSION': 1, 38 | } 39 | } 40 | 41 | LANGUAGE_CODE = 'zh-hans' # zh-cn从1.7版本后弃用 42 | 43 | USE_I18N = False # 关闭多语言引擎,优化性能 44 | 45 | TIME_ZONE = 'Asia/Shanghai' 46 | 47 | USE_TZ = False # 不开启时区,如开启,数据库字段将会保存为UTC时间,而不是本地时间 48 | 49 | STATIC_URL = '/static/' 50 | 51 | 52 | # patchers 53 | 54 | def patch_disable_fetchurl(): 55 | """ 禁用掉fetchurl服务, 使用socket服务来处理请求,如此一来,可进行follow操作(如果用fetchurl服务,则无法进行follow操作) 56 | 请参见:http://sae.sina.com.cn/?m=devcenter&catId=291 57 | """ 58 | os.environ['disable_fetchurl'] = '1' 59 | 60 | 61 | def patch_task_queue(host='localhost', port=8080): 62 | """ 用于虚拟SAE的TaskQueue服务,仅用于本地开发环境 63 | """ 64 | os.environ['HTTP_HOST'] = '%s:%d' % (host, port) 65 | 66 | 67 | def patch_memcache(): 68 | """ 用于虚拟本地开发环境的Memcache服务,数据将保存在内存中 69 | """ 70 | import sae.memcache 71 | 72 | sys.modules['pylibmc'] = sae.memcache 73 | 74 | 75 | def patch_kvdb(file_path): 76 | """ 用于虚拟本地开发环境的KVDB服务,数据将保存到指定的文件中 77 | """ 78 | os.environ['sae.kvdb.file'] = os.path.abspath(file_path) 79 | 80 | 81 | def patch_storage(file_path): 82 | """ 用于虚拟本地开发环境的Storage服务,数据将保存到指定的文件中 83 | """ 84 | os.environ['sae.storage.path'] = os.path.abspath(file_path) 85 | 86 | 87 | def patch_app_info(name, version='1'): 88 | """ 用于虚拟环境变量APP_NAME和APP_VERSION 89 | """ 90 | os.environ['APP_NAME'] = name 91 | os.environ['APP_VERSION'] = version 92 | 93 | 94 | def patch_sae_restful_mysql(): 95 | """ 用于直接操作线上的数据库 96 | """ 97 | from sae._restful_mysql import monkey 98 | 99 | monkey.patch() 100 | 101 | 102 | def get_database(name, user, password, host=MYSQL_HOST, port=MYSQL_PORT, alias='default', 103 | engine='django.db.backends.mysql', **options): 104 | options.setdefault('init_command', "SET storage_engine=MYISAM;") 105 | return { 106 | alias: { 107 | 'ENGINE': engine, 108 | 'NAME': name, 109 | 'USER': user, 110 | 'PASSWORD': password, 111 | 'HOST': host, 112 | 'PORT': port, 113 | 'OPTIONS': options, 114 | } 115 | } 116 | 117 | 118 | if IN_SAE: 119 | DEBUG = False 120 | TEMPLATE_DEBUG = False 121 | DATABASE_ROUTERS = ['django_sae.db.routers.MasterSlaveRouter'] # 读写分离 122 | else: 123 | DEBUG = True 124 | TEMPLATE_DEBUG = True 125 | DATABASE_ROUTERS = [] 126 | 127 | patch_memcache() 128 | patch_task_queue() -------------------------------------------------------------------------------- /django_sae/contrib/__init__.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | -------------------------------------------------------------------------------- /django_sae/contrib/tasks/__init__.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | -------------------------------------------------------------------------------- /django_sae/contrib/tasks/cron.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | from django.http import HttpResponse 3 | from django.views.generic import View 4 | from django_sae.contrib.tasks.settings import PARALLEL_QUEUE_NAME 5 | from sae.taskqueue import TaskQueue 6 | 7 | 8 | class OperationView(View): 9 | QUEUE_NAME = PARALLEL_QUEUE_NAME 10 | 11 | @staticmethod 12 | def as_task(operation): 13 | if operation is None: 14 | return [] 15 | try: 16 | operations = list(iter(operation)) 17 | except TypeError: 18 | operations = [operation] 19 | return [operation.as_task() for operation in operations] 20 | 21 | def get_operation(self, request): 22 | raise NotImplementedError 23 | 24 | def get(self, request, *args, **kwargs): 25 | operation = self.get_operation(request) 26 | tasks = self.as_task(operation) 27 | TaskQueue(self.QUEUE_NAME).add(tasks) 28 | content = 'added {0:d} tasks'.format(len(tasks)) 29 | return HttpResponse(content) -------------------------------------------------------------------------------- /django_sae/contrib/tasks/models.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | from django_sae.contrib.tasks import settings as t_settings 3 | 4 | 5 | t_settings.patch_root_urlconf() -------------------------------------------------------------------------------- /django_sae/contrib/tasks/operations.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | import random 3 | import time 4 | 5 | from django.core.urlresolvers import reverse 6 | from django.core.cache import cache 7 | from django_sae.contrib.tasks.settings import ORDER_QUEUE_NAME, PARALLEL_QUEUE_NAME 8 | from django_sae.utils.taskqueue import get_queue 9 | from sae.taskqueue import Task 10 | 11 | 12 | class OperationBase(object): 13 | def __init__(self, **kwargs): 14 | self.data = kwargs 15 | 16 | def pre_post(self): 17 | pass 18 | 19 | def post(self): 20 | raise NotImplementedError 21 | 22 | def save(self, response): 23 | pass 24 | 25 | def next(self, response): 26 | pass 27 | 28 | def execute(self): 29 | self.pre_post() 30 | response = self.post() 31 | if response is not None: 32 | self.save(response) 33 | self.next(response) 34 | return response 35 | 36 | 37 | class TaskOperationMixin(object): 38 | QUEUE_NAME = PARALLEL_QUEUE_NAME 39 | 40 | @staticmethod 41 | def get_random_id(digits=8): 42 | return 'r%d' % (int(time.time()) + random.randint(0, pow(10, digits) - 1)) 43 | 44 | def get_key_fields(self): 45 | return [self.get_random_id()] 46 | 47 | def get_key(self): 48 | fields = [self.__module__.split('.')[0], self.__class__.__name__] 49 | sub_fields = self.get_key_fields() 50 | if sub_fields: 51 | fields.extend(sub_fields) 52 | return '.'.join([str(field) for field in fields]) 53 | 54 | def save_to_mc(self, key): 55 | cache.set(key, self) 56 | 57 | @staticmethod 58 | def get_execute_uri(key): 59 | return reverse('tasks:execute', kwargs={'key': key}) 60 | 61 | def as_task(self, **kwargs): 62 | key = self.get_key() 63 | self.save_to_mc(key) 64 | return Task(self.get_execute_uri(key), **kwargs) 65 | 66 | def execute_by_queue(self, queue_name=QUEUE_NAME, **kwargs): 67 | task = self.as_task(**kwargs) 68 | queue = get_queue(queue_name) 69 | return queue.add(task) 70 | 71 | def execute_by_order(self, **kwargs): 72 | return self.execute_by_queue(ORDER_QUEUE_NAME, **kwargs) 73 | 74 | def execute_by_parallel(self, **kwargs): 75 | return self.execute_by_queue(PARALLEL_QUEUE_NAME, **kwargs) 76 | 77 | 78 | class TaskOperationBase(OperationBase, TaskOperationMixin): 79 | pass -------------------------------------------------------------------------------- /django_sae/contrib/tasks/settings.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | from django.conf import settings 3 | 4 | ORDER_QUEUE_NAME = getattr(settings, 'ORDER_QUEUE_NAME', 'order') 5 | PARALLEL_QUEUE_NAME = getattr(settings, 'PARALLEL_QUEUE_NAME', 'parallel') 6 | 7 | 8 | def patch_root_urlconf(): 9 | from django.conf.urls import include, patterns, url 10 | from django.core.urlresolvers import clear_url_caches, reverse, NoReverseMatch 11 | from django.utils.importlib import import_module 12 | 13 | try: 14 | reverse('tasks:execute') 15 | except NoReverseMatch: 16 | root = import_module(settings.ROOT_URLCONF) 17 | root.urlpatterns = patterns('', url(r'^tasks/', include('django_sae.contrib.tasks.urls', 'tasks', 18 | 'tasks')), ) + root.urlpatterns 19 | clear_url_caches() -------------------------------------------------------------------------------- /django_sae/contrib/tasks/tests/__init__.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | -------------------------------------------------------------------------------- /django_sae/contrib/tasks/tests/base.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | from django.test import SimpleTestCase as TestCase 3 | 4 | 5 | class CronViewTestMixin(TestCase): 6 | def assertResult(self, r, count): 7 | self.assertEqual(200, r.status_code) 8 | self.assertEqual('added %s tasks' % count, r.content) -------------------------------------------------------------------------------- /django_sae/contrib/tasks/tests/operations.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | from django_sae.contrib.tasks.operations import OperationBase, TaskOperationBase 3 | 4 | 5 | class OperationMock(OperationBase): 6 | def post(self): 7 | return 'foo' 8 | 9 | 10 | class TaskOperationMock(TaskOperationBase): 11 | def __init__(self, account): 12 | super(TaskOperationMock, self).__init__() 13 | self.account = account 14 | 15 | def post(self): 16 | pass -------------------------------------------------------------------------------- /django_sae/contrib/tasks/tests/test_cron.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | from django_sae.contrib.tasks.cron import OperationView 3 | from django_sae.contrib.tasks.operations import TaskOperationMixin 4 | from django_sae.contrib.tasks.tests.base import CronViewTestMixin 5 | 6 | 7 | class CronViewTest(CronViewTestMixin): 8 | def test_router_return_none(self): 9 | response = self.client.get('/mock') 10 | self.assertResult(response, 3) 11 | 12 | def test_as_task(self): 13 | r = OperationView.as_task(TaskOperationMixin()) 14 | self.assertEqual(len(r), 1) 15 | 16 | def test_as_task_with_none(self): 17 | r = OperationView.as_task(None) 18 | self.assertEqual(len(r), 0) 19 | 20 | def test_get_operation(self): 21 | view = OperationView() 22 | self.assertRaises(NotImplementedError, view.get_operation, None) -------------------------------------------------------------------------------- /django_sae/contrib/tasks/tests/test_operations.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | from django.test import SimpleTestCase as TestCase 3 | from django.core.cache import cache 4 | 5 | from django_sae.contrib.tasks.operations import OperationBase, TaskOperationMixin 6 | from django_sae.contrib.tasks.tests.operations import OperationMock 7 | 8 | 9 | class OperationTest(TestCase): 10 | def test_execute_when_raise_error(self): 11 | self.assertRaises(NotImplementedError, OperationBase().execute) 12 | 13 | def test_execute(self): 14 | r = OperationMock().execute() 15 | self.assertEqual(r, 'foo') 16 | 17 | def test_data(self): 18 | self.data = dict(foo='bar') 19 | self.operation = OperationMock(**self.data) 20 | self.assertEqual(self.operation.data, self.data) 21 | 22 | 23 | class TaskOperationTest(TestCase): 24 | def setUp(self): 25 | self.operation = TaskOperationMixin() 26 | 27 | def tearDown(self): 28 | cache.clear() 29 | 30 | def test_save_to_mc(self): 31 | key = self.operation.get_key() 32 | self.assertIn(self.operation.__class__.__name__, key) 33 | self.assertIn(self.operation.__module__.split('.')[0], key) 34 | self.operation.save_to_mc(key) 35 | self.assertIsNotNone(cache.get(key)) 36 | 37 | def test_execute_by_queue(self): 38 | r = self.operation.execute_by_queue('test') 39 | self.assertTrue(r) 40 | 41 | def test_execute_by_order(self): 42 | r = self.operation.execute_by_order() 43 | self.assertTrue(r) 44 | 45 | def test_execute_by_parallel(self): 46 | r = self.operation.execute_by_parallel() 47 | self.assertTrue(r) 48 | -------------------------------------------------------------------------------- /django_sae/contrib/tasks/tests/test_views.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | from django.test import SimpleTestCase as TestCase 3 | from django.core.cache import cache 4 | 5 | from django_sae.contrib.tasks.tests.operations import TaskOperationMock 6 | 7 | 8 | class ViewsTest(TestCase): 9 | def setUp(self): 10 | self.operation = TaskOperationMock('foo') 11 | self.key = self.operation.get_key() 12 | self.uri = self.operation.get_execute_uri(self.key) 13 | 14 | def tearDown(self): 15 | cache.clear() 16 | 17 | def test_execute(self): 18 | self.operation.save_to_mc(self.key) 19 | response = self.client.get(self.uri) 20 | self.assertContains(response, 'success') 21 | self.assertIsNone(cache.get(self.key)) 22 | 23 | def test_execute_not_exist_key(self): 24 | response = self.client.get(self.uri) 25 | self.assertEqual(response.status_code, 404) 26 | self.assertIsNone(cache.get(self.key)) 27 | -------------------------------------------------------------------------------- /django_sae/contrib/tasks/tests/views.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | from django_sae.contrib.tasks.cron import OperationView 3 | from django_sae.contrib.tasks.operations import TaskOperationMixin 4 | 5 | 6 | class OperationViewMock(OperationView): 7 | def get_operation(self, request): 8 | return [TaskOperationMixin() for _ in range(0, 3)] -------------------------------------------------------------------------------- /django_sae/contrib/tasks/urls.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | from django.conf.urls import patterns, url 3 | 4 | 5 | urlpatterns = patterns('', 6 | url(r'^execute/(?P.+)/$', 'django_sae.contrib.tasks.views.execute', name='execute'), 7 | ) -------------------------------------------------------------------------------- /django_sae/contrib/tasks/views.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | from django.http import HttpResponse, Http404 3 | 4 | 5 | def execute(request, key): 6 | from django.core.cache import cache 7 | 8 | try: 9 | o = cache.get(str(key)) 10 | if o is None: 11 | raise Http404('not exist key: %s' % key) 12 | else: 13 | o.execute() 14 | return HttpResponse('success') 15 | finally: 16 | cache.delete(key) -------------------------------------------------------------------------------- /django_sae/db/__init__.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | -------------------------------------------------------------------------------- /django_sae/db/models.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | from django.db import models 3 | from django.utils import timezone 4 | 5 | 6 | class AutoIdEntity(models.Model): 7 | created_at = models.DateTimeField(default=None) 8 | updated_at = models.DateTimeField(auto_now=True) 9 | 10 | class Meta: 11 | abstract = True 12 | 13 | def __unicode__(self): 14 | """ 15 | __unicode__和__str__用于显示(给人看的),__str__返回字节(bytes),__unicode__返回字符(characters) 16 | __repr__ 用于判断(给解释器看的) 17 | """ 18 | return unicode(self.id) 19 | 20 | def save(self, *args, **kwargs): 21 | if self.created_at is None: 22 | self.created_at = timezone.now() 23 | super(AutoIdEntity, self).save(*args, **kwargs) 24 | 25 | 26 | class LongIdEntity(AutoIdEntity): 27 | id = models.BigIntegerField(primary_key=True) 28 | 29 | class Meta: 30 | abstract = True -------------------------------------------------------------------------------- /django_sae/db/repository.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | from django.db import models, IntegrityError, OperationalError, connection 3 | from django.utils import timezone 4 | from django_sae.utils.decorators import retry 5 | import datetime 6 | 7 | DEFAULT_RETRIES = 3 # 重试次数 8 | DEFAULT_UPDATE_CYCLE = datetime.timedelta(weeks=1) # 更新周期 9 | 10 | 11 | def close_connection(e): 12 | """ Fix: '2006: MySQL server has gone away', Ref:https://code.djangoproject.com/ticket/21597#comment:29 13 | """ 14 | connection.close() 15 | 16 | 17 | class RepositoryBase(object): 18 | Model = models.Model 19 | PK = 'id' # 与解析对象的ITEM_PK对应的数据库字段名 20 | ITEM_PK = 'id' # 与解析对象的主键 21 | UPDATE_CHECK_FIELDS = [] 22 | 23 | def distinct(self, items): 24 | return {self._get_item_pk(item): item for item in items} 25 | 26 | @classmethod 27 | def get_values_list(cls, *fields, **kwargs): 28 | return cls.Model.objects.filter(**kwargs).values_list(*fields, flat=True) 29 | 30 | @classmethod 31 | def get_not_in(cls, id_field, ids): 32 | """获取不存在于数据库的ID 33 | :param id_field: ID字段名 34 | :param ids: ID列表 35 | :return: 不存在于数据库的ID 36 | """ 37 | kwargs = {'%s__in' % id_field: ids} 38 | exist_ids = cls.get_values_list(id_field, **kwargs) 39 | return [item_id for item_id in ids if item_id not in exist_ids] 40 | 41 | @classmethod 42 | def get_pk_list(cls, **kwargs): 43 | return cls.get_values_list(cls.PK, **kwargs) 44 | 45 | def get_exist_ids(self, item_ids): 46 | return self.get_pk_list(id__in=item_ids) 47 | 48 | def get_exist_objects(self, item_ids): 49 | return self.Model.objects.filter(id__in=item_ids) 50 | 51 | def get_pk_fields(self, item): 52 | """ 获取响应结果中的数据库主键字段 53 | """ 54 | return {self.PK: self._get_item_pk(item)} 55 | 56 | def update_defaults_fields(self, fields, item): 57 | """ 更新和补充响应结果中的数据库非主键字段 58 | """ 59 | pass 60 | 61 | def get_defaults_fields(self, item): 62 | """ 获取响应结果中的数据库非主键字段 63 | """ 64 | fields = {} 65 | self.update_defaults_fields(fields, item) 66 | return fields 67 | 68 | def to_fields(self, item): 69 | """ 将响应结果转换为数据库字段(Dict) 70 | """ 71 | fields = self.get_pk_fields(item) 72 | defaults = self.get_defaults_fields(item) 73 | if defaults: 74 | fields.update(defaults) 75 | return fields 76 | 77 | def build(self, item): 78 | return self.Model(**self.to_fields(item)) 79 | 80 | def _pre_create(self, item): 81 | pass 82 | 83 | @retry(2, OperationalError, close_connection) 84 | def _try_create(self, item, fields): 85 | try: 86 | return self.Model.objects.create(**fields) 87 | except IntegrityError: 88 | return self.update_or_create(item) 89 | 90 | def create(self, item): 91 | self._pre_create(item) 92 | return self._try_create(item, self.to_fields(item)) 93 | 94 | def _pre_bulk_create(self, items): 95 | pass 96 | 97 | @retry(DEFAULT_RETRIES, IntegrityError) 98 | def _try_bulk_create(self, items_dict): 99 | """如主键重复,则重新尝试""" 100 | all_ids = items_dict.keys() 101 | exist_ids = self.get_exist_ids(all_ids) 102 | new_ids = set(all_ids) - set(exist_ids) 103 | new_objects = [self.build(items_dict[k]) for k in new_ids] 104 | return self.Model.objects.bulk_create(new_objects) 105 | 106 | def bulk_create(self, items): 107 | """批量创建记录(忽略已存在的记录),只返回新的记录""" 108 | self._pre_bulk_create(items) 109 | items_dict = self.distinct(items) 110 | return self._try_bulk_create(items_dict) 111 | 112 | def _get_pk(self, obj): 113 | return getattr(obj, self.PK) 114 | 115 | def _get_item_pk(self, item): 116 | return item.get(self.ITEM_PK) 117 | 118 | def is_updatable(self, obj, item): 119 | """判断是否可更新""" 120 | if self.UPDATE_CHECK_FIELDS: 121 | for field in self.UPDATE_CHECK_FIELDS: 122 | if getattr(obj, field) != item.get(field): 123 | return True 124 | return timezone.now() - obj.updated_at > DEFAULT_UPDATE_CYCLE 125 | 126 | def update(self, obj, item, is_check_updatable=True): 127 | defaults = self.get_defaults_fields(item) 128 | if not is_check_updatable or self.is_updatable(obj, defaults): 129 | for key, value in defaults.iteritems(): 130 | setattr(obj, key, value) 131 | obj.save() 132 | 133 | def bulk_update_or_create(self, items): 134 | """批量创建记录,并自动更新(已存在的且超过更新周期的)记录,返回所有记录""" 135 | self._pre_bulk_create(items) 136 | items_dict = self.distinct(items) 137 | new_objects = self._try_bulk_create(items_dict) 138 | if len(items) != len(new_objects): 139 | new_ids = [self._get_pk(obj) for obj in new_objects] 140 | old_ids = set(items_dict.keys()) - set(new_ids) 141 | old_objects = self.get_exist_objects(old_ids) 142 | for obj in old_objects: 143 | item = items_dict[self._get_pk(obj)] 144 | self.update(obj, item) 145 | new_objects.extend(old_objects) 146 | return new_objects 147 | 148 | def get_or_create(self, item): 149 | self._pre_create(item) 150 | pk = self.get_pk_fields(item) 151 | defaults = self.get_defaults_fields(item) 152 | pk.update(defaults=defaults) 153 | return self.Model.objects.get_or_create(**pk) 154 | 155 | def update_or_create(self, item): 156 | self._pre_create(item) 157 | pk = self.get_pk_fields(item) 158 | try: 159 | obj = self.Model.objects.get(**pk) 160 | self.update(obj, item) 161 | except self.Model.DoesNotExist: 162 | fields = self.get_defaults_fields(item) 163 | fields.update(pk) 164 | obj = self.Model(**fields) 165 | obj.save() 166 | return obj 167 | 168 | def delete(self, item): 169 | pk = self.get_pk_fields(item) 170 | self.Model.objects.filter(**pk).delete() -------------------------------------------------------------------------------- /django_sae/db/routers.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | 3 | 4 | class MasterSlaveRouter(object): 5 | def db_for_read(self, model, **hints): 6 | """ 7 | Reads always go to slave. 8 | """ 9 | return 'slave' 10 | 11 | def db_for_write(self, model, **hints): 12 | """ 13 | Writes always go to default master. 14 | """ 15 | return 'default' 16 | 17 | def allow_relation(self, obj1, obj2, **hints): 18 | return True 19 | 20 | def allow_syncdb(self, db, model): 21 | return True -------------------------------------------------------------------------------- /django_sae/db/utils.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | from django.db import connection 3 | from django.template import Template, Context 4 | 5 | 6 | def print_sql(): 7 | if connection.queries: 8 | time = sum([float(q['time']) for q in connection.queries]) 9 | t = Template( 10 | "{{count}} quer{{count|pluralize:\"y,ies\"}} in {{time}} seconds:\n{% for sql in sqllog %}[{{forloop.counter}}] {{sql.time}}s: {{sql.sql|safe}}{% if not forloop.last %}\n{% endif %}{% endfor %}") 11 | print t.render(Context({'sqllog': connection.queries, 'count': len(connection.queries), 'time': time})) 12 | 13 | 14 | def clear_sql(): 15 | connection.queries = [] -------------------------------------------------------------------------------- /django_sae/management/__init__.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | -------------------------------------------------------------------------------- /django_sae/management/commands/__init__.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | 3 | 4 | -------------------------------------------------------------------------------- /django_sae/management/commands/compress_site_packages.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | import os 3 | import sys 4 | import zipfile 5 | import time 6 | import re 7 | from distutils.sysconfig import get_python_lib 8 | from django.conf import settings 9 | from django.core.management.base import NoArgsCommand 10 | from django_extensions.management.commands import clean_pyc, compile_pyc 11 | 12 | 13 | def zip_folder(folder_path, zip_name, include_empty_folder=True, check_root=None, check_file=None): 14 | root_length = len(folder_path) + 1 15 | zip_file = zipfile.ZipFile(zip_name, "w", zipfile.ZIP_DEFLATED) 16 | for root, folders, files in os.walk(folder_path): 17 | short_root = root[root_length:] 18 | if check_root is None or check_root(short_root): 19 | empty_folders = [folder for folder in folders if os.listdir(os.path.join(root, folder)) == []] 20 | for f in files: 21 | if check_file is None or check_file(short_root, f): 22 | file_name = os.path.join(root, f) 23 | zip_file.write(file_name, file_name[root_length:]) 24 | if include_empty_folder: 25 | for folder in empty_folders: 26 | zif = zipfile.ZipInfo(os.path.join(root, folder) + "/") 27 | zip_file.writestr(zif, "") 28 | zip_file.close() 29 | 30 | 31 | class Command(NoArgsCommand): 32 | help = "Compress site-packages folder to a zip file." 33 | usage_str = "Usage: ./manage.py compress_site_packages" 34 | filter_modules = ("_markerlib", "pip", "setuptools", "sae", "MySQLdb", "lxml", "PIL", 35 | "werkzeug", "prettytable", "yaml", "argparse", "grizzled", "sqlcmd", "enum", 36 | "test", "tests", "_mysql", "_mysql_exceptions", "_mysql", 37 | "easy_install", "pkg_resources") 38 | 39 | @classmethod 40 | def check_root(cls, root): 41 | module_name = root.split(os.path.sep)[0] 42 | if module_name in cls.filter_modules or "." in module_name: 43 | return False 44 | return True 45 | 46 | @classmethod 47 | def check_file(cls, root, f): 48 | if not root: 49 | file_name, extend_name = os.path.splitext(f) 50 | if file_name in cls.filter_modules or extend_name in ['.egg', '.txt', '.pth']: 51 | return False 52 | return True 53 | 54 | @staticmethod 55 | def get_wsgi_file(): 56 | return os.path.join(settings.BASE_DIR, 'index.wsgi') 57 | 58 | @staticmethod 59 | def replace_site_packages(path, name): 60 | if os.path.exists(path): 61 | with open(path) as rf: 62 | text = rf.read() 63 | m = re.search("sys.path.insert\(0, os.path.join\(root, '(?P.+)'\)\)", text) 64 | if m: 65 | with open(path, 'w') as wf: 66 | wf.write(text.replace(m.group('name'), name)) 67 | 68 | def handle(self, path=None, name=None, **options): 69 | if path is None: 70 | path = get_python_lib() 71 | if name is None: 72 | name = "site-packages%s.zip" % int(time.time()) 73 | 74 | # 用户可以上传和使用 .pyc 文件,注意 .pyc 文件必须是python2.7.3生成的,否则无效。 75 | # http://sae.sina.com.cn/doc/python/runtime.html#id3 76 | if options.get("clean_pyc", sys.version_info[0:3] != (2, 7, 3)): 77 | clean_pyc.Command().execute(path=path, verbosity=0) 78 | else: 79 | compile_pyc.Command().execute(path=path, verbosity=0) 80 | 81 | zip_folder(path, name, True, self.check_root, self.check_file) 82 | self.replace_site_packages(self.get_wsgi_file(), name) 83 | self.stdout.write("compressed success:%s" % name) -------------------------------------------------------------------------------- /django_sae/management/commands/sae_migrate.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | from django.core.management.commands import migrate 3 | from django.db.utils import DEFAULT_DB_ALIAS 4 | from django_sae.conf.settings import patch_sae_restful_mysql 5 | 6 | 7 | class Command(migrate.Command): 8 | def handle(self, *args, **kwargs): 9 | patch_sae_restful_mysql() 10 | kwargs.setdefault('database', DEFAULT_DB_ALIAS) 11 | super(Command, self).handle(*args, **kwargs) 12 | -------------------------------------------------------------------------------- /django_sae/management/commands/upgrade_requirements.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | import os 3 | import sys 4 | import pip 5 | from django.conf import settings 6 | from django.core.management.base import NoArgsCommand 7 | from pip.commands import InstallCommand 8 | 9 | 10 | class Command(NoArgsCommand): 11 | help = "Upgrade packages list in requirements." 12 | 13 | def handle_noargs(self, **options): 14 | if options.get('requirements', False): 15 | req_files = options["requirements"] 16 | elif os.path.exists("requirements.txt"): 17 | req_files = ["requirements.txt"] 18 | elif os.path.exists("requirements"): 19 | req_files = ["requirements/{0}".format(f) for f in os.listdir("requirements") 20 | if os.path.isfile(os.path.join("requirements", f)) and 21 | f.lower().endswith(".txt")] 22 | else: 23 | sys.exit("requirements not found") 24 | 25 | initial_args = ['install', '--upgrade', '--no-deps'] 26 | [initial_args.extend(['--requirement', os.path.join(settings.BASE_DIR, req)]) for req in req_files] 27 | cmd_name, args = pip.parseopts(initial_args) 28 | 29 | InstallCommand().main(args) 30 | 31 | -------------------------------------------------------------------------------- /django_sae/utils/__init__.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | -------------------------------------------------------------------------------- /django_sae/utils/counts.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | 3 | 4 | def count_pages(page_length, total_number): 5 | """ 计算页数 6 | """ 7 | quotient, remainder = divmod(total_number, page_length) 8 | return quotient + int(remainder != 0) 9 | 10 | 11 | def count_length(string): 12 | """ 计算字符数,1个中文算一个字符,1个英文算半个字符。应用场景:如微博字符计算。 13 | """ 14 | length = len(string) 15 | utf_length = len(string.encode('utf-8')) 16 | cn_length = (utf_length - length) / 2 17 | en_length = length - cn_length 18 | return cn_length + count_pages(2, en_length) -------------------------------------------------------------------------------- /django_sae/utils/decorators.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | from functools import wraps 3 | 4 | 5 | def retry(max_tries, exceptions=(Exception,), hook=None): 6 | """Retry calling the decorated function 7 | """ 8 | def deco_retry(f): 9 | @wraps(f) 10 | def f_retry(*args, **kwargs): 11 | tries = max_tries 12 | while tries > 1: 13 | try: 14 | return f(*args, **kwargs) 15 | except exceptions, e: 16 | if hook is not None: 17 | hook(e) 18 | tries -= 1 19 | return f(*args, **kwargs) 20 | 21 | return f_retry # true decorator 22 | return deco_retry -------------------------------------------------------------------------------- /django_sae/utils/log.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | import logging 3 | from django.conf import settings 4 | from django_sae.conf import settings as sae_settings 5 | 6 | 7 | class RequireInSAE(logging.Filter): 8 | def filter(self, record): 9 | return getattr(settings, 'IN_SAE', sae_settings.IN_SAE) 10 | 11 | 12 | class RequireNotInSAE(logging.Filter): 13 | def filter(self, record): 14 | return not getattr(settings, 'IN_SAE', sae_settings.IN_SAE) -------------------------------------------------------------------------------- /django_sae/utils/taskqueue.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | from sae.taskqueue import TaskQueue 3 | from django.utils.six import string_types 4 | 5 | CachedQueue = {} 6 | 7 | 8 | def get_queue(queue_name): 9 | """ 获取队列 10 | """ 11 | if queue_name not in CachedQueue: 12 | CachedQueue[queue_name] = TaskQueue(queue_name) 13 | return CachedQueue[queue_name] 14 | 15 | 16 | def get_queue_size(queue_names): 17 | """ 获取队列中尚未执行的任务数 18 | """ 19 | if isinstance(queue_names, string_types): 20 | names = [queue_names] 21 | else: 22 | names = list(iter(queue_names)) 23 | return sum([get_queue(name).size() for name in names]) -------------------------------------------------------------------------------- /django_sae/utils/text.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | 3 | 4 | def any_in(words, text): 5 | """ Check list of words in another string 6 | """ 7 | for word in words: 8 | if word in text: 9 | return True 10 | return False -------------------------------------------------------------------------------- /django_sae/utils/timestamp.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | import time 3 | from datetime import datetime, timedelta 4 | from django.conf import settings 5 | from django.utils import timezone 6 | 7 | 8 | def to_datetime(timestamp): 9 | dt = datetime.fromtimestamp(long(timestamp)) 10 | if settings.USE_TZ: 11 | return dt.replace(tzinfo=timezone.get_current_timezone()) 12 | return dt 13 | 14 | 15 | def to_timestamp(dt): 16 | return int(time.mktime(dt.timetuple())) if isinstance(dt, datetime) else dt 17 | 18 | 19 | def make_datetime(**kwargs): 20 | """ 21 | 已现在为起始的偏移日期,将来用整数,过去用负数,默认为现在 22 | kwargs: days, seconds, microseconds, milliseconds, minutes, hours, weeks 23 | 如:make_datetime(days=-1) 24 | """ 25 | return timezone.now() + timedelta(**kwargs) 26 | 27 | 28 | def make_timestamp(**kwargs): 29 | """ 30 | 已现在为起始的偏移时间戳,将来用整数,过去用负数,默认为现在 31 | kwargs: days, seconds, microseconds, milliseconds, minutes, hours, weeks 32 | 如:make_timestamp(days=-1) 33 | """ 34 | return to_timestamp(make_datetime(**kwargs)) -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | sae-python-dev>=1.3.2 2 | django>=1.6.5 3 | django-extensions>=1.3.7 4 | django-debug-toolbar>=1.2 5 | pytz>=2014.3 6 | pip>=1.5.6 -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | import django_sae 3 | 4 | 5 | try: 6 | from setuptools import setup 7 | except ImportError: 8 | from distutils.core import setup 9 | 10 | packages = [ 11 | 'django_sae', 12 | 'django_sae.conf', 13 | 'django_sae.cache', 14 | 'django_sae.cache.tests', 15 | 'django_sae.contrib', 16 | 'django_sae.contrib.tasks', 17 | 'django_sae.contrib.tasks.tests', 18 | 'django_sae.management', 19 | 'django_sae.management.commands', 20 | 'django_sae.db', 21 | 'django_sae.utils', 22 | ] 23 | 24 | requires = [ 25 | 'django>=1.6.4,<1.7', 26 | 'django-extensions>=1.3.4', 27 | 'django-debug-toolbar>=1.2', 28 | 'pytz>=2014.2', 29 | 'South>=0.8.4', 30 | 'pip>=1.5.5', 31 | ] 32 | 33 | with open('README.md') as f: 34 | readme = f.read() 35 | with open('HISTORY.md') as f: 36 | history = f.read() 37 | 38 | setup( 39 | name='django-sae', 40 | version=django_sae.__version__, 41 | description='for django in sae', 42 | long_description=readme + '\n\n' + history, 43 | author='smallcode', 44 | author_email='45945756@qq.com', 45 | url='https://github.com/smallcode/django-sae', 46 | packages=packages, 47 | package_dir={'django_sae': 'django_sae'}, 48 | include_package_data=True, 49 | install_requires=requires, 50 | license=django_sae.__license__, 51 | zip_safe=True, 52 | classifiers=[ 53 | 'Development Status :: 5 - Production/Stable', 54 | 'Environment :: Web Environment', 55 | 'Framework :: Django', 56 | 'Intended Audience :: Developers', 57 | 'License :: OSI Approved :: Apache Software License', 58 | 'Programming Language :: Python', 59 | 'Topic :: Software Development :: Libraries :: Python Modules' 60 | ], 61 | ) 62 | 63 | -------------------------------------------------------------------------------- /tests/__init__.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | -------------------------------------------------------------------------------- /tests/conf/__init__.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | -------------------------------------------------------------------------------- /tests/conf/test_settings.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | import os 3 | import sys 4 | import sae.memcache 5 | import sae._restful_mysql 6 | from django.test import SimpleTestCase 7 | from django_sae.conf import settings 8 | 9 | 10 | class PatchesTestCase(SimpleTestCase): 11 | def test_patch_disable_fetchurl(self): 12 | settings.patch_disable_fetchurl() 13 | self.assertEqual(os.environ.get('disable_fetchurl'), '1') 14 | 15 | def test_patch_task_queue(self): 16 | settings.patch_task_queue() 17 | self.assertEqual(os.environ.get('HTTP_HOST'), 'localhost:8080') 18 | 19 | def test_patch_memcache(self): 20 | settings.patch_memcache() 21 | self.assertEqual(sys.modules['pylibmc'], sae.memcache) 22 | 23 | def test_patch_kvdb(self): 24 | file_path = 'tests/kvdb' 25 | settings.patch_kvdb(file_path) 26 | self.assertEqual(os.environ['sae.kvdb.file'], os.path.abspath(file_path)) 27 | 28 | def test_patch_storage(self): 29 | file_path = 'tests/storage' 30 | settings.patch_storage(file_path) 31 | self.assertEqual(os.environ['sae.storage.path'], os.path.abspath(file_path)) 32 | 33 | def test_patch_app_info(self): 34 | name = 'django_sae' 35 | settings.patch_app_info(name) 36 | self.assertEqual(os.environ.get('APP_NAME'), name) 37 | self.assertEqual(os.environ.get('APP_VERSION'), '1') 38 | 39 | def test_patch_sae_restful_mysql(self): 40 | settings.patch_sae_restful_mysql() 41 | self.assertEqual(sys.modules['MySQLdb'], sae._restful_mysql) 42 | 43 | def test_get_database(self): 44 | name = 'name' 45 | user = 'user' 46 | password = 'password' 47 | database = settings.get_database(name, user, password) 48 | self.assertEqual(database, { 49 | 'default': { 50 | 'ENGINE': 'django.db.backends.mysql', 51 | 'NAME': name, 52 | 'USER': user, 53 | 'PASSWORD': password, 54 | 'HOST': settings.MYSQL_HOST, 55 | 'PORT': settings.MYSQL_PORT, 56 | 'OPTIONS': {'init_command': "SET storage_engine=MYISAM;"}, 57 | } 58 | }) -------------------------------------------------------------------------------- /tests/db/__init__.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | -------------------------------------------------------------------------------- /tests/db/test_models.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | from django.test import TestCase 3 | from tests.models import User 4 | 5 | 6 | class ModelsTest(TestCase): 7 | def test_user(self): 8 | user = User() 9 | user.save() 10 | self.assertIsNotNone(user.created_at) 11 | self.assertIsNotNone(user.updated_at) 12 | self.assertEqual(str(user), '1') -------------------------------------------------------------------------------- /tests/db/test_repository.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | from django.test import TestCase 3 | from django_sae.db.repository import RepositoryBase 4 | from tests.models import User 5 | 6 | 7 | class UserRepository(RepositoryBase): 8 | Model = User 9 | 10 | 11 | class RepositoryTest(TestCase): 12 | def setUp(self): 13 | self.r = UserRepository() 14 | 15 | def test_create(self): 16 | item_id = 123 17 | item = dict(id=item_id) 18 | 19 | self.r.create(item) 20 | self.assertTrue(User.objects.filter(id=item_id).exists()) 21 | 22 | self.r.delete(item) 23 | self.assertFalse(User.objects.filter(id=item_id).exists()) 24 | 25 | -------------------------------------------------------------------------------- /tests/db/test_routers.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | from django.test import TestCase 3 | from django_sae.db.routers import MasterSlaveRouter 4 | 5 | 6 | class MasterSlaveRouterTest(TestCase): 7 | def setUp(self): 8 | self.router = MasterSlaveRouter() 9 | 10 | def test_db_for_read(self): 11 | self.assertEqual(self.router.db_for_read(None), 'slave') 12 | 13 | def test_db_for_write(self): 14 | self.assertTrue(self.router.db_for_write(None), 'master') 15 | 16 | def test_allow_syncdb(self): 17 | self.assertTrue(self.router.allow_syncdb(None, None)) 18 | 19 | def test_allow_relation(self): 20 | self.assertTrue(self.router.allow_relation(None, None)) 21 | -------------------------------------------------------------------------------- /tests/db/test_utils.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | from django.test import SimpleTestCase as TestCase 3 | from django.db import connection 4 | 5 | from django_sae.db.utils import print_sql, clear_sql 6 | 7 | 8 | class UtilsTest(TestCase): 9 | def setUp(self): 10 | query_mock = {'time': 1, 'sql': 'sql mock'} 11 | connection.queries = [query_mock] 12 | 13 | def test_print_url(self): 14 | print_sql() 15 | 16 | def test_clear_sql(self): 17 | clear_sql() 18 | self.assertFalse(connection.queries) -------------------------------------------------------------------------------- /tests/downloads/requests-master.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/twz915/django-sae/3b12b3bd1edf0ad002d94bd3607a796762fb5840/tests/downloads/requests-master.zip -------------------------------------------------------------------------------- /tests/index.wsgi: -------------------------------------------------------------------------------- 1 | import os 2 | import sys 3 | 4 | root = os.path.dirname(__file__) 5 | sys.path.insert(0, os.path.join(root, 'site-packages123.zip')) 6 | 7 | import sae 8 | 9 | from app_name import wsgi 10 | 11 | application = sae.create_wsgi_app(wsgi.application) -------------------------------------------------------------------------------- /tests/management/__init__.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | -------------------------------------------------------------------------------- /tests/management/base.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | from cStringIO import StringIO 3 | from django.test import SimpleTestCase 4 | 5 | 6 | class CommandTestBase(SimpleTestCase): 7 | def setUp(self): 8 | self.maxDiff = None 9 | self.stdout = StringIO() 10 | self.stderr = StringIO() 11 | 12 | def tearDown(self): 13 | self.stdout.close() 14 | self.stderr.close() 15 | 16 | def execute(self, command, *args, **options): 17 | options.setdefault('stdout', self.stdout) 18 | options.setdefault('stderr', self.stderr) 19 | command.execute(*args, **options) 20 | return self.stdout.getvalue().strip() -------------------------------------------------------------------------------- /tests/management/test_compress_site_packages.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | import os 3 | from django_sae.management.commands import compress_site_packages 4 | from .base import CommandTestBase 5 | 6 | 7 | class CompressSitePackagesTest(CommandTestBase): 8 | def setUp(self): 9 | super(CompressSitePackagesTest, self).setUp() 10 | self.command = compress_site_packages.Command() 11 | 12 | def assertCompressed(self, command_output): 13 | self.assertIn("compressed success", command_output) 14 | zip_name = command_output.split(':')[-1] 15 | self.assertTrue(os.path.exists(zip_name)) 16 | os.remove(zip_name) 17 | 18 | def test_command(self): 19 | command_output = self.execute(self.command, path='tests', clean_pyc=True) 20 | self.assertCompressed(command_output) 21 | 22 | def test_compress_site_packages_without_clean_pyc(self): 23 | command_output = self.execute(self.command, path='tests', clean_pyc=False) 24 | self.assertCompressed(command_output) 25 | 26 | def test_replace_site_packages(self): 27 | origin_zip_name = 'site-packages123.zip' 28 | zip_name = 'site-packages456.zip' 29 | path = os.path.join('tests', 'index.wsgi') 30 | self.command.replace_site_packages(path, zip_name) 31 | with open(path) as wsgi_file: 32 | self.assertIn("sys.path.insert(0, os.path.join(root, '%s'))" % zip_name, wsgi_file.read()) 33 | self.command.replace_site_packages(path, origin_zip_name) # 复原 34 | 35 | def test_check_file(self): 36 | self.assertFalse(self.command.check_file('', 'foo.pth')) 37 | self.assertTrue(self.command.check_file('', 'foo.py')) 38 | 39 | def test_check_root(self): 40 | for module in self.command.filter_modules: 41 | self.assertFalse(self.command.check_root(module)) 42 | self.assertFalse(self.command.check_root('test.egg-info')) 43 | self.assertTrue(self.command.check_root('foo')) -------------------------------------------------------------------------------- /tests/management/test_sae_migrate.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | from django_sae.management.commands import sae_migrate 3 | from .base import CommandTestBase 4 | 5 | 6 | class SaeMigrateTestCase(CommandTestBase): 7 | def test_command(self): 8 | command = sae_migrate.Command() 9 | self.execute(command, db_dry_run=True, verbosity=2) # verbosity大于1,则打印详细信息 10 | 11 | 12 | -------------------------------------------------------------------------------- /tests/management/test_upgrade_requirements.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | import os 3 | from unittest import skip 4 | import pip 5 | from pip.commands import UninstallCommand 6 | from distutils.sysconfig import get_python_lib 7 | from django_sae.management.commands import upgrade_requirements 8 | from .base import CommandTestBase 9 | 10 | 11 | class UpgradeRequirementsTestCase(CommandTestBase): 12 | def is_exists(self, package): 13 | return os.path.exists(os.path.join(get_python_lib(), package)) or os.path.exists( 14 | os.path.join(get_python_lib(), '%s.py' % package)) 15 | 16 | def uninstall(self, package): 17 | cmd_name, args = pip.parseopts(['uninstall', '--yes', package]) 18 | UninstallCommand().main(args) 19 | self.assertFalse(self.is_exists(package)) 20 | 21 | @skip(u'测试用时太久') 22 | def test_command(self): 23 | package = 'requests' 24 | command = upgrade_requirements.Command() 25 | self.execute(command, requirements=['tests/requirements.txt']) 26 | self.assertTrue(self.is_exists(package)) 27 | self.uninstall(package) -------------------------------------------------------------------------------- /tests/models.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | from django.db import models 3 | from django_sae.db.models import AutoIdEntity 4 | 5 | 6 | class User(AutoIdEntity): 7 | name = models.CharField(max_length=75) 8 | -------------------------------------------------------------------------------- /tests/requirements.txt: -------------------------------------------------------------------------------- 1 | #django>=1.6.2,<1.7 2 | 3 | # for local test upgrade packages command 4 | tests/downloads/requests-master.zip 5 | 6 | # the real package url 7 | # https://github.com/kennethreitz/requests/zipball/master#egg=requests 8 | 9 | # the invalid ur, will raise exception: Cannot find command 'git' in virtualenv 10 | # -e git+https://github.com/kennethreitz/requests.git@master#egg=requests -------------------------------------------------------------------------------- /tests/settings.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | """Django settings for tests.""" 3 | 4 | import os 5 | from django_sae.conf.settings import IN_SAE 6 | 7 | BASE_DIR = os.path.dirname(os.path.dirname(__file__)) 8 | 9 | DEBUG = not IN_SAE 10 | 11 | # Quick-start development settings - unsuitable for production 12 | 13 | SECRET_KEY = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890' 14 | 15 | INTERNAL_IPS = ['127.0.0.1'] 16 | 17 | 18 | # Application definition 19 | 20 | INSTALLED_APPS = [ 21 | 'django_sae', 22 | 'django_sae.contrib.tasks', 23 | 'tests', 24 | ] 25 | 26 | MIDDLEWARE_CLASSES = [ 27 | ] 28 | 29 | ROOT_URLCONF = 'tests.urls' 30 | 31 | # database 32 | 33 | DATABASES = { 34 | 'default': { 35 | 'ENGINE': 'django.db.backends.sqlite3', 36 | } 37 | } 38 | 39 | # SOUTH_TESTS_MIGRATE=False -------------------------------------------------------------------------------- /tests/urls.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | from django.conf.urls import patterns, url 3 | from django_sae.contrib.tasks.tests.views import OperationViewMock 4 | 5 | urlpatterns = patterns('', 6 | url(r'^mock$', OperationViewMock.as_view()), 7 | ) -------------------------------------------------------------------------------- /tests/utils/__init__.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | -------------------------------------------------------------------------------- /tests/utils/test_counts.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | from django.test import SimpleTestCase 3 | from django_sae.utils.counts import count_length, count_pages 4 | 5 | 6 | class CountsTest(SimpleTestCase): 7 | def test_count_pages(self): 8 | self.assertEqual(count_pages(10, 100), 10) 9 | self.assertEqual(count_pages(10, 99), 10) 10 | 11 | def test_count_length(self): 12 | self.assertEqual(count_length(u'中文'), 2) 13 | self.assertEqual(count_length(u'en'), 1) 14 | self.assertEqual(count_length(u'eng'), 2) 15 | self.assertEqual(count_length(u'中文en'), 3) 16 | self.assertEqual(count_length(u'中文eng'), 4) -------------------------------------------------------------------------------- /tests/utils/test_decorators.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | from django.test import SimpleTestCase as TestCase 3 | from django_sae.utils.decorators import retry 4 | 5 | 6 | class DecoratorsTest(TestCase): 7 | n = 0 8 | 9 | @staticmethod 10 | def handle_error(exception): 11 | print exception 12 | 13 | def test_retry(self): 14 | @retry(3, hook=self.handle_error) 15 | def retry_me(): 16 | self.n += 1 17 | raise Exception(u'exception in try %s' % self.n) 18 | 19 | self.assertRaises(Exception, retry_me) 20 | self.assertEqual(self.n, 3) 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /tests/utils/test_log.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | from django.test import SimpleTestCase as TestCase 3 | from django.test.utils import override_settings 4 | from django_sae.utils.log import RequireInSAE, RequireNotInSAE 5 | 6 | 7 | class LogTest(TestCase): 8 | @override_settings(IN_SAE=True) 9 | def test_require_in_sae(self): 10 | self.assertTrue(RequireInSAE().filter(None)) 11 | 12 | @override_settings(IN_SAE=False) 13 | def test_require_not_in_sae(self): 14 | self.assertTrue(RequireNotInSAE().filter(None)) 15 | -------------------------------------------------------------------------------- /tests/utils/test_taskqueue.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | from django.test import SimpleTestCase as TestCase 3 | from django_sae.utils.taskqueue import get_queue, get_queue_size 4 | 5 | 6 | class TaskQueueTest(TestCase): 7 | def test_get_queue(self): 8 | queue_name = 'test' 9 | queue1 = get_queue(queue_name) 10 | queue2 = get_queue(queue_name) 11 | self.assertEqual(queue1, queue2) 12 | 13 | def test_get_queue_size(self): 14 | self.assertEqual(0, get_queue_size('queue1')) 15 | self.assertEqual(0, get_queue_size(['queue1', 'queue2'])) -------------------------------------------------------------------------------- /tests/utils/test_text.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | from django.test import SimpleTestCase 3 | from django_sae.utils.text import any_in 4 | 5 | 6 | class TextTest(SimpleTestCase): 7 | def test_any_in(self): 8 | self.assertTrue(any_in([u'测试'], u'这是个测试语句')) 9 | self.assertFalse(any_in([u'不包含'], u'这是个测试语句')) -------------------------------------------------------------------------------- /tests/utils/test_timestamp.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | import time 3 | 4 | from django.test import SimpleTestCase as TestCase 5 | from django.test.utils import override_settings 6 | 7 | from django_sae.utils.timestamp import to_timestamp, to_datetime, make_timestamp 8 | 9 | 10 | class TimestampTest(TestCase): 11 | def test_timestamp(self): 12 | ts = time.time() 13 | dt = to_datetime(ts) 14 | self.assertEqual(int(ts), to_timestamp(dt)) 15 | 16 | @override_settings(USE_TZ=False) 17 | def test_timestamp_not_use_timezone(self): 18 | self.test_timestamp() 19 | 20 | @override_settings(USE_TZ=True, TIME_ZONE='Asia/Shanghai') 21 | def test_timestamp_use_timezone(self): 22 | self.test_timestamp() 23 | 24 | @override_settings(USE_TZ=False) 25 | def test_make_timestamp(self): 26 | self.assertEqual(make_timestamp(days=1) - make_timestamp(), 86400) 27 | self.assertEqual(make_timestamp(days=-1) - make_timestamp(), -86400) 28 | --------------------------------------------------------------------------------