├── .coveragerc ├── .gitignore ├── .travis.yml ├── AUTHORS.rst ├── CONTRIBUTING.rst ├── HISTORY.rst ├── LICENSE ├── MANIFEST.in ├── README.rst ├── appengine_toolkit ├── __init__.py ├── management │ ├── __init__.py │ └── commands │ │ ├── __init__.py │ │ ├── _utils.py │ │ └── collectdeps.py ├── models.py ├── settings.py ├── static │ ├── css │ │ └── appengine_toolkit.css │ ├── img │ │ └── .gitignore │ └── js │ │ └── appengine_toolkit.js ├── storage.py └── templates │ └── appengine_toolkit │ └── base.html ├── docs ├── Makefile ├── authors.rst ├── conf.py ├── contributing.rst ├── history.rst ├── index.rst ├── installation.rst ├── make.bat ├── readme.rst └── usage.rst ├── requirements-test.txt ├── requirements.txt ├── runtests.py ├── setup.py ├── tests ├── __init__.py ├── test_commands.py ├── test_storage.py ├── test_toolkit.py └── test_utils.py └── tox.ini /.coveragerc: -------------------------------------------------------------------------------- 1 | [run] 2 | source = appengine_toolkit 3 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .idea 2 | 3 | *.py[cod] 4 | 5 | # C extensions 6 | *.so 7 | 8 | # Packages 9 | *.egg 10 | *.egg-info 11 | dist 12 | build 13 | eggs 14 | parts 15 | bin 16 | var 17 | sdist 18 | develop-eggs 19 | .installed.cfg 20 | lib 21 | lib64 22 | 23 | # Installer logs 24 | pip-log.txt 25 | 26 | # Unit test / coverage reports 27 | .coverage 28 | .tox 29 | nosetests.xml 30 | 31 | # Translations 32 | *.mo 33 | 34 | # Mr Developer 35 | .mr.developer.cfg 36 | .project 37 | .pydevproject 38 | 39 | # Complexity 40 | output/*.html 41 | output/*/index.html 42 | 43 | # Sphinx 44 | docs/_build 45 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | # Config file for automatic testing at travis-ci.org 2 | 3 | language: python 4 | 5 | python: 6 | - "2.7" 7 | 8 | before_script: 9 | - wget https://commondatastorage.googleapis.com/appengine-sdks/featured/google_appengine_1.9.4.zip -nv 10 | - unzip -q google_appengine_1.9.4.zip 11 | 12 | # command to install dependencies, e.g. pip install -r requirements.txt --use-mirrors 13 | install: 14 | - pip install -r requirements-test.txt 15 | - pip install coveralls 16 | 17 | # command to run tests, e.g. python setup.py test 18 | script: 19 | - export PYTHONPATH=$PYTHONPATH:google_appengine 20 | - coverage run runtests.py 21 | 22 | after_success: coveralls 23 | -------------------------------------------------------------------------------- /AUTHORS.rst: -------------------------------------------------------------------------------- 1 | ======= 2 | Credits 3 | ======= 4 | 5 | Development Lead 6 | ---------------- 7 | 8 | * Massimiliano Pippi 9 | 10 | Contributors 11 | ------------ 12 | 13 | None yet. Why not be the first? -------------------------------------------------------------------------------- /CONTRIBUTING.rst: -------------------------------------------------------------------------------- 1 | ============ 2 | Contributing 3 | ============ 4 | 5 | Contributions are welcome, and they are greatly appreciated! Every 6 | little bit helps, and credit will always be given. 7 | 8 | You can contribute in many ways: 9 | 10 | Types of Contributions 11 | ---------------------- 12 | 13 | Report Bugs 14 | ~~~~~~~~~~~ 15 | 16 | Report bugs at https://github.com/masci/django-appengine-toolkit/issues. 17 | 18 | If you are reporting a bug, please include: 19 | 20 | * Your operating system name and version. 21 | * Any details about your local setup that might be helpful in troubleshooting. 22 | * Detailed steps to reproduce the bug. 23 | 24 | Fix Bugs 25 | ~~~~~~~~ 26 | 27 | Look through the GitHub issues for bugs. Anything tagged with "bug" 28 | is open to whoever wants to implement it. 29 | 30 | Implement Features 31 | ~~~~~~~~~~~~~~~~~~ 32 | 33 | Look through the GitHub issues for features. Anything tagged with "feature" 34 | is open to whoever wants to implement it. 35 | 36 | Write Documentation 37 | ~~~~~~~~~~~~~~~~~~~ 38 | 39 | appengine-toolkit could always use more documentation, whether as part of the 40 | official appengine-toolkit docs, in docstrings, or even on the web in blog posts, 41 | articles, and such. 42 | 43 | Submit Feedback 44 | ~~~~~~~~~~~~~~~ 45 | 46 | The best way to send feedback is to file an issue at https://github.com/masci/django-appengine-toolkit/issues. 47 | 48 | If you are proposing a feature: 49 | 50 | * Explain in detail how it would work. 51 | * Keep the scope as narrow as possible, to make it easier to implement. 52 | * Remember that this is a volunteer-driven project, and that contributions 53 | are welcome :) 54 | 55 | Get Started! 56 | ------------ 57 | 58 | Ready to contribute? Here's how to set up `django-appengine-toolkit` for local development. 59 | 60 | 1. Fork the `django-appengine-toolkit` repo on GitHub. 61 | 2. Clone your fork locally:: 62 | 63 | $ git clone git@github.com:your_name_here/django-appengine-toolkit.git 64 | 65 | 3. Install your local copy into a virtualenv. Assuming you have virtualenvwrapper installed, this is how you set up your fork for local development:: 66 | 67 | $ mkvirtualenv django-appengine-toolkit 68 | $ cd django-appengine-toolkit/ 69 | $ python setup.py develop 70 | 71 | 4. Create a branch for local development:: 72 | 73 | $ git checkout -b name-of-your-bugfix-or-feature 74 | 75 | Now you can make your changes locally. 76 | 77 | 5. When you're done making changes, check that your changes pass flake8 and the 78 | tests, including testing other Python versions with tox:: 79 | 80 | $ flake8 appengine_toolkit tests 81 | $ python setup.py test 82 | $ tox 83 | 84 | To get flake8 and tox, just pip install them into your virtualenv. 85 | 86 | 6. Commit your changes and push your branch to GitHub:: 87 | 88 | $ git add . 89 | $ git commit -m "Your detailed description of your changes." 90 | $ git push origin name-of-your-bugfix-or-feature 91 | 92 | 7. Submit a pull request through the GitHub website. 93 | 94 | Pull Request Guidelines 95 | ----------------------- 96 | 97 | Before you submit a pull request, check that it meets these guidelines: 98 | 99 | 1. The pull request should include tests. 100 | 2. If the pull request adds functionality, the docs should be updated. Put 101 | your new functionality into a function with a docstring, and add the 102 | feature to the list in README.rst. 103 | 3. The pull request should work for Python 2.6, 2.7, and 3.3, and for PyPy. Check 104 | https://travis-ci.org/masci/django-appengine-toolkit/pull_requests 105 | and make sure that the tests pass for all supported Python versions. 106 | 107 | Tips 108 | ---- 109 | 110 | To run a subset of tests:: 111 | 112 | $ python -m unittest tests.test_appengine_toolkit -------------------------------------------------------------------------------- /HISTORY.rst: -------------------------------------------------------------------------------- 1 | .. :changelog: 2 | 3 | History 4 | ------- 5 | 6 | 0.2.0 (2014-01-09) 7 | ++++++++++++++++++ 8 | 9 | * Fixed setup requirements for GCS library 10 | * App Engine SDK 1.9 compatibility 11 | 12 | 0.2.0 (2014-01-09) 13 | ++++++++++++++++++ 14 | 15 | * Added support for Google Cloud Storage 16 | 17 | 0.1.2 (2013-12-04) 18 | ++++++++++++++++++ 19 | 20 | * Fixed setup script 21 | 22 | 0.1.1 (2013-12-04) 23 | ++++++++++++++++++ 24 | 25 | * Finished first draft of docs 26 | 27 | 0.1.0 (2013-11-30) 28 | ++++++++++++++++++ 29 | 30 | * First release on PyPI. -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2013, Massimiliano Pippi 2 | All rights reserved. 3 | 4 | Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 5 | 6 | * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 7 | 8 | * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 9 | 10 | * Neither the name of appengine-toolkit nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. 11 | 12 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include AUTHORS.rst 2 | include CONTRIBUTING.rst 3 | include HISTORY.rst 4 | include LICENSE 5 | include README.rst 6 | recursive-include appengine_toolkit *.html *js *py -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | ============================= 2 | Django Appengine Toolkit 3 | ============================= 4 | 5 | .. image:: https://badge.fury.io/py/django-appengine-toolkit.png 6 | :target: http://badge.fury.io/py/django-appengine-toolkit 7 | 8 | .. image:: https://travis-ci.org/masci/django-appengine-toolkit.png?branch=master 9 | :target: https://travis-ci.org/masci/django-appengine-toolkit 10 | 11 | .. image:: https://pypip.in/d/django-appengine-toolkit/badge.png 12 | :target: https://crate.io/packages/django-appengine-toolkit?version=latest 13 | 14 | .. image:: https://coveralls.io/repos/masci/django-appengine-toolkit/badge.png 15 | :target: https://coveralls.io/r/masci/django-appengine-toolkit 16 | 17 | Appengine Toolkit pimps Django with some utilities that help deploying 18 | projects on Google App Engine with Google Cloud SQL as data backend. 19 | 20 | Features 21 | -------- 22 | 23 | * collects project dependencies symlinking needed modules and packages and configuring App Engine environment 24 | * configures DATABASE setting parsing connection strings similar to those on Heroku 25 | * provides a custom storage for Google Cloud Storage 26 | 27 | Documentation 28 | ------------- 29 | 30 | The full documentation is at http://django-appengine-toolkit.rtfd.org. 31 | 32 | A tutorial was published on `Google Developers Blog `_ 33 | 34 | Another `how-to upload to cloud storage `_ 35 | 36 | AppEngine SDK version supported: 1.9.4 37 | 38 | Quickstart 39 | ---------- 40 | 41 | Install appengine-toolkit:: 42 | 43 | pip install django-appengine-toolkit 44 | 45 | Add it to the installed apps:: 46 | 47 | INSTALLED_APPS = ( 48 | # ... 49 | 'appengine_toolkit', 50 | ) 51 | 52 | To automatically configure database settings by parsing connection string 53 | contained in DATABASE_URL enviroment var:: 54 | 55 | import appengine_toolkit 56 | DATABASES = { 57 | 'default': appengine_toolkit.config(), 58 | } 59 | 60 | You can set DATABASE_URL directly in your ``app.yaml`` file:: 61 | 62 | env_variables: 63 | DJANGO_SETTINGS_MODULE: 'myapp.settings' 64 | DATABASE_URL: 'mysql://root@project_id:instance_id/database_name' 65 | 66 | 67 | To collect project dependencies, first configure Appengine Toolkit specifying the full 68 | path pointing to the app.yaml file in your `settings.py` module:: 69 | 70 | APPENGINE_TOOLKIT = { 71 | 'APP_YAML': os.path.join(BASE_DIR, '../../', 'app.yaml'), 72 | } 73 | 74 | 75 | ...then run the command ``collectdeps`` specifying the requirement file containing 76 | the list of packages needed by your project to run:: 77 | 78 | python manage.py collectdeps -r my_requirements.txt 79 | 80 | a folder named ``libs`` will be created on your application root (i.e. the same folder 81 | where the YAML file resides) containing symlinks needed by App Engine to include 82 | dependencies in the production runtime enviroment. 83 | 84 | A file ``appengine_config.py`` will be created in the same folder and will contain 85 | code needed to configure the environment. If you need to customize the module 86 | ``appengine_config`` tell the command to not overwrite it - the command will then 87 | output the code you need to paste inside the module to complete the configuration 88 | process 89 | 90 | Need to store your media files on Google Cloud Storage? Just add this to your settings:: 91 | 92 | APPENGINE_TOOLKIT = { 93 | # ..., 94 | 'BUCKET_NAME': 'your-bucket-name', 95 | } 96 | DEFAULT_FILE_STORAGE = 'appengine_toolkit.storage.GoogleCloudStorage' 97 | 98 | -------------------------------------------------------------------------------- /appengine_toolkit/__init__.py: -------------------------------------------------------------------------------- 1 | __version__ = '0.2.1' 2 | 3 | import os 4 | 5 | try: 6 | import urlparse 7 | except ImportError: 8 | import urllib.parse as urlparse 9 | 10 | DEFAULT_ENV = 'DATABASE_URL' 11 | 12 | # Register database schemes in URLs. 13 | urlparse.uses_netloc.append('mysql') 14 | urlparse.uses_netloc.append('rdbms') 15 | 16 | SCHEMES = { 17 | 'mysql': 'django.db.backends.mysql', 18 | 'rdbms': 'google.appengine.ext.django.backends.rdbms', 19 | } 20 | 21 | 22 | def on_appengine(): 23 | """ 24 | Determine if program is running on App Engine servers 25 | """ 26 | return os.getenv('SERVER_SOFTWARE', '').startswith('Google App Engine') 27 | 28 | 29 | def config(env=DEFAULT_ENV, default=None): 30 | """ 31 | Returns configured DATABASE dictionary from DEFAULT_ENV. 32 | """ 33 | config = {} 34 | 35 | s = os.environ.get(env, default) 36 | 37 | if s: 38 | config = parse(s) 39 | 40 | return config 41 | 42 | 43 | def parse(url): 44 | """ 45 | Parses a database URL in this format: 46 | [database type]://[username]:[password]@[host]:[port]/[database name] 47 | 48 | or, for cloud SQL: 49 | [database type]://[username]:[password]@[project_id]:[instance_name]/[database name] 50 | """ 51 | config = {} 52 | 53 | url = urlparse.urlparse(url) 54 | 55 | # Remove query strings. 56 | path = url.path[1:] 57 | path = path.split('?', 2)[0] 58 | 59 | try: 60 | port = url.port 61 | hostname = url.hostname 62 | except ValueError: 63 | port = None 64 | if url.scheme == 'rdbms': 65 | # local appengine stub requires INSTANCE parameter 66 | config['INSTANCE'] = url.netloc.split('@')[-1] 67 | hostname = None 68 | else: 69 | hostname = "/cloudsql/{}".format(url.netloc.split('@')[-1]) 70 | 71 | config.update({ 72 | 'NAME': path, 73 | 'USER': url.username, 74 | 'PASSWORD': url.password, 75 | 'HOST': hostname, 76 | 'PORT': port, 77 | }) 78 | 79 | if url.scheme in SCHEMES: 80 | config['ENGINE'] = SCHEMES[url.scheme] 81 | 82 | return config -------------------------------------------------------------------------------- /appengine_toolkit/management/__init__.py: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /appengine_toolkit/management/commands/__init__.py: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /appengine_toolkit/management/commands/_utils.py: -------------------------------------------------------------------------------- 1 | import pkg_resources 2 | import os 3 | import sys 4 | 5 | 6 | class RequirementNotFoundError(Exception): 7 | pass 8 | 9 | 10 | def collect_dependency_paths(package_name): 11 | """ 12 | TODO docstrings 13 | """ 14 | deps = [] 15 | try: 16 | dist = pkg_resources.get_distribution(package_name) 17 | except (pkg_resources.DistributionNotFound, ValueError): 18 | message = "Distribution '{}' not found.".format(package_name) 19 | raise RequirementNotFoundError(message) 20 | 21 | if dist.has_metadata('top_level.txt'): 22 | for line in dist.get_metadata('top_level.txt').split(): 23 | # do not consider subpackages (e.g. the form 'package/subpackage') 24 | if not os.path.split(line)[0]: 25 | pkg = os.path.join(dist.location, line) 26 | # handle single module packages 27 | if not os.path.isdir(pkg) and os.path.exists(pkg+'.py'): 28 | pkg += '.py' 29 | deps.append(pkg) 30 | 31 | for req in dist.requires(): 32 | deps.extend(collect_dependency_paths(req.project_name)) 33 | 34 | return deps 35 | 36 | 37 | def parse_requirements_file(req_file): 38 | """ 39 | TODO docstrings 40 | """ 41 | lines = [] 42 | for line in req_file.readlines(): 43 | line = line.strip() 44 | if not line or line.startswith('#'): 45 | continue 46 | lines.append(line) 47 | return lines 48 | 49 | 50 | def make_simlinks(dest_dir, paths_list): 51 | """ 52 | TODO docstrings 53 | """ 54 | for path in paths_list: 55 | dest = os.path.join(dest_dir, os.path.split(path)[-1]) 56 | if os.path.exists(dest): 57 | if os.path.islink(dest): 58 | os.remove(dest) 59 | else: 60 | sys.stderr.write('A file or dir named {} already exists, skipping...\n'.format(dest)) 61 | continue 62 | os.symlink(path, dest) 63 | 64 | 65 | def get_config_code(dependencies_root): 66 | """ 67 | TODO docstrings 68 | """ 69 | code = ("# code generated by Appengine Toolkit\n" 70 | "import sys\n" 71 | "import os\n" 72 | "sys.path.append(os.path.join(os.path.dirname(__file__), '{}'))\n" 73 | "# end generated code\n".format(dependencies_root)) 74 | 75 | return code 76 | -------------------------------------------------------------------------------- /appengine_toolkit/management/commands/collectdeps.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import os 3 | from optparse import make_option 4 | 5 | from django.core.management.base import BaseCommand, CommandError 6 | from django.utils.six.moves import input 7 | 8 | from ._utils import collect_dependency_paths, parse_requirements_file, make_simlinks, get_config_code 9 | from ._utils import RequirementNotFoundError 10 | from ...settings import appengine_toolkit_settings 11 | 12 | 13 | class Command(BaseCommand): 14 | args = "" 15 | help = "make symlinks to project dependencies" 16 | 17 | option_list = BaseCommand.option_list + ( 18 | make_option( 19 | '-r', 20 | '--requirements', 21 | action='store', 22 | dest='requirements_file', 23 | help='Collect dependencies for packages contained in requirement file' 24 | ), 25 | make_option( 26 | '--noinput', 27 | action='store_false', 28 | dest='interactive', 29 | default=True, 30 | help='Tells Django to NOT prompt the user for input of any kind.' 31 | ), 32 | ) 33 | 34 | def handle(self, *args, **options): 35 | interactive = options.get('interactive', True) 36 | req_file_path = options.get('requirements_file') 37 | if not len(args) and not req_file_path: 38 | raise CommandError('Please provide at least a package name or a requirement file\n') 39 | 40 | deps = [] 41 | 42 | sys.stdout.write('Collecting dependencies...\n') 43 | if req_file_path: 44 | with open(req_file_path) as f: 45 | for line in parse_requirements_file(f): 46 | try: 47 | deps.extend(collect_dependency_paths(line)) 48 | except RequirementNotFoundError as e: 49 | raise CommandError('Error processing requirement file: {}\n'.format(e)) 50 | 51 | for package in args: 52 | deps.extend(collect_dependency_paths(package)) 53 | 54 | deps = set(deps) 55 | 56 | sys.stdout.write('{} dependencies found...\n'.format(len(deps))) 57 | 58 | sys.stdout.write('Making symlinks...\n') 59 | 60 | app_root = os.path.dirname(appengine_toolkit_settings.APP_YAML) 61 | deps_root = os.path.join(app_root, appengine_toolkit_settings.DEPENDENCIES_ROOT) 62 | 63 | if not os.path.exists(deps_root): 64 | sys.stdout.write('Creating dependencies root folder...\n') 65 | os.mkdir(deps_root) 66 | make_simlinks(deps_root, deps) 67 | 68 | sys.stdout.write('Writing config to appengine_config.py...\n') 69 | 70 | appengine_config = os.path.join(app_root, 'appengine_config.py') 71 | 72 | write_file = True 73 | if interactive and os.path.exists(appengine_config): 74 | msg = ("\nA file called appengine_config.py already exist at " 75 | "application root path.\nWould you like to overwrite it? (yes/no): ") 76 | confirm = input(msg) 77 | while 1: 78 | if confirm not in ('yes', 'no'): 79 | confirm = input('Please enter either "yes" or "no": ') 80 | continue 81 | if confirm == 'no': 82 | write_file = False 83 | break 84 | 85 | msg = get_config_code(appengine_toolkit_settings.DEPENDENCIES_ROOT) 86 | if write_file: 87 | with open(os.path.join(app_root, 'appengine_config.py'), 'w') as f: 88 | f.write(msg) 89 | else: 90 | sys.stdout.write('Please ensure your appengine_config.py contains the following:\n\n') 91 | sys.stdout.write(msg) 92 | sys.stdout.write('\n') 93 | 94 | sys.stdout.write('All done.\n') 95 | -------------------------------------------------------------------------------- /appengine_toolkit/models.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | -------------------------------------------------------------------------------- /appengine_toolkit/settings.py: -------------------------------------------------------------------------------- 1 | """ 2 | Settings are all namespaced in the APPENGINE_TOOLKIT setting. 3 | For example your project's `settings.py` file might look like this:: 4 | 5 | APPENGINE_TOOLKIT = { 6 | 'DEPENDENCIES_ROOT_NAME': 'libs', 7 | } 8 | 9 | This module provides the `appengine_toolkit_settings` object, that is used to 10 | access app's settings, checking for user settings first, then falling back to 11 | the defaults. 12 | """ 13 | from __future__ import unicode_literals 14 | 15 | from django.conf import settings 16 | 17 | USER_SETTINGS = getattr(settings, 'APPENGINE_TOOLKIT', None) 18 | 19 | DEFAULTS = { 20 | 'APP_YAML': None, 21 | 'DEPENDENCIES_ROOT': 'libs', 22 | 'BUCKET_NAME': None, 23 | } 24 | 25 | # List of settings that cannot be empty 26 | MANDATORY = ( 27 | # absolute path to application file 28 | 'APP_YAML', 29 | ) 30 | 31 | 32 | class AppengineToolkitSettings(object): 33 | """ 34 | A settings object, that allows settings to be accessed as properties. 35 | """ 36 | 37 | def __init__(self, user_settings=None, defaults=None, mandatory=None): 38 | self.user_settings = user_settings or {} 39 | self.defaults = defaults or {} 40 | self.mandatory = mandatory or () 41 | 42 | def __getattr__(self, attr): 43 | if attr not in self.defaults.keys(): 44 | raise AttributeError("Invalid Appengine Toolkit setting: '%s'" % attr) 45 | 46 | try: 47 | # Check if present in user settings 48 | val = self.user_settings[attr] 49 | except KeyError: 50 | # Fall back to defaults 51 | val = self.defaults[attr] 52 | 53 | self.validate_setting(attr, val) 54 | 55 | # Cache the result 56 | setattr(self, attr, val) 57 | return val 58 | 59 | def validate_setting(self, attr, val): 60 | if not val and attr in self.mandatory: 61 | raise AttributeError("Appengine Toolkit setting: '%s' is mandatory" % attr) 62 | 63 | 64 | appengine_toolkit_settings = AppengineToolkitSettings(USER_SETTINGS, DEFAULTS, MANDATORY) 65 | -------------------------------------------------------------------------------- /appengine_toolkit/static/css/appengine_toolkit.css: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/masci/django-appengine-toolkit/9ffe8b05a263889787fb34a3e28ebc66b1f0a1d2/appengine_toolkit/static/css/appengine_toolkit.css -------------------------------------------------------------------------------- /appengine_toolkit/static/img/.gitignore: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/masci/django-appengine-toolkit/9ffe8b05a263889787fb34a3e28ebc66b1f0a1d2/appengine_toolkit/static/img/.gitignore -------------------------------------------------------------------------------- /appengine_toolkit/static/js/appengine_toolkit.js: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/masci/django-appengine-toolkit/9ffe8b05a263889787fb34a3e28ebc66b1f0a1d2/appengine_toolkit/static/js/appengine_toolkit.js -------------------------------------------------------------------------------- /appengine_toolkit/storage.py: -------------------------------------------------------------------------------- 1 | from django.core.files.storage import Storage 2 | from django.core.exceptions import ImproperlyConfigured, SuspiciousOperation 3 | from django.utils import timezone 4 | 5 | import os 6 | import mimetypes 7 | 8 | import cloudstorage 9 | from google.appengine.ext import blobstore 10 | from google.appengine.api import images 11 | 12 | from .settings import appengine_toolkit_settings 13 | 14 | 15 | class GoogleCloudStorage(Storage): 16 | """ 17 | Custom storage provider for saving files on Google Cloud Storage. 18 | `url` method retrieves a public url generated by blobstore api so 19 | that files are served directly by Google 20 | """ 21 | def __init__(self): 22 | """ 23 | __init__ must be callable without arguments. 24 | Check for bucket name settings upon initialization 25 | """ 26 | try: 27 | cloudstorage.validate_bucket_name(appengine_toolkit_settings.BUCKET_NAME) 28 | except ValueError: 29 | raise ImproperlyConfigured("Please specify a valid value for APPENGINE_TOOLKIT['BUCKET_NAME'] setting") 30 | self._bucket = '/' + appengine_toolkit_settings.BUCKET_NAME 31 | 32 | def path(self, name): 33 | """ 34 | Returns the full path to the file, including leading '/' and bucket name. 35 | Access to the bucket root are not allowed. 36 | """ 37 | if not name: 38 | raise SuspiciousOperation("Attempted access to '%s' denied." % name) 39 | return os.path.join(self._bucket, name) 40 | 41 | def _open(self, name, mode='rb'): 42 | return cloudstorage.open(self.path(name), 'r') 43 | 44 | def _save(self, name, content): 45 | realname = self.path(name) 46 | content_t = mimetypes.guess_type(realname)[0] 47 | with cloudstorage.open(realname, 'w', content_type=content_t, options={'x-goog-acl': 'public-read'}) as f: 48 | f.write(content.read()) 49 | return os.path.join(self._bucket, realname) 50 | 51 | def delete(self, name): 52 | try: 53 | cloudstorage.delete(self.path(name)) 54 | except cloudstorage.NotFoundError: 55 | pass 56 | 57 | def exists(self, name): 58 | try: 59 | cloudstorage.stat(self.path(name)) 60 | return True 61 | except cloudstorage.NotFoundError: 62 | return False 63 | 64 | def listdir(self, name): 65 | """ 66 | TODO collect directories 67 | """ 68 | return [], [obj.filename for obj in cloudstorage.listbucket(self.path(name))] 69 | 70 | def size(self, name): 71 | filestat = cloudstorage.stat(self.path(name)) 72 | return filestat.st_size 73 | 74 | def url(self, name): 75 | """ 76 | Ask blobstore api for an url to directly serve the file 77 | """ 78 | key = blobstore.create_gs_key('/gs' + name) 79 | return images.get_serving_url(key) 80 | 81 | def created_time(self, name): 82 | filestat = cloudstorage.stat(self.path(name)) 83 | creation_date = timezone.datetime.fromtimestamp(filestat.st_ctime) 84 | return timezone.make_aware(creation_date, timezone.get_current_timezone()) 85 | 86 | def isdir(self, name): 87 | """ 88 | TODO perform actual check, at the moment only happened Mezzanine calls this 89 | method 90 | """ 91 | return True 92 | -------------------------------------------------------------------------------- /appengine_toolkit/templates/appengine_toolkit/base.html: -------------------------------------------------------------------------------- 1 | 2 | {% comment %} 3 | As the developer of this package, don't place anything here if you can help it 4 | since this allows developers to have interoperability between your template 5 | structure and their own. 6 | 7 | Example: Developer melding the 2SoD pattern to fit inside with another pattern:: 8 | 9 | {% extends "base.html" %} 10 | {% load static %} 11 | 12 | 13 | {% block extra_js %} 14 | 15 | 16 | {% block javascript %} 17 | 18 | {% endblock javascript %} 19 | 20 | {% endblock extra_js %} 21 | {% endcomment %} 22 | -------------------------------------------------------------------------------- /docs/Makefile: -------------------------------------------------------------------------------- 1 | # Makefile for Sphinx documentation 2 | # 3 | 4 | # You can set these variables from the command line. 5 | SPHINXOPTS = 6 | SPHINXBUILD = sphinx-build 7 | PAPER = 8 | BUILDDIR = _build 9 | 10 | # User-friendly check for sphinx-build 11 | ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1) 12 | $(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/) 13 | endif 14 | 15 | # Internal variables. 16 | PAPEROPT_a4 = -D latex_paper_size=a4 17 | PAPEROPT_letter = -D latex_paper_size=letter 18 | ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . 19 | # the i18n builder cannot share the environment and doctrees with the others 20 | I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . 21 | 22 | .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext 23 | 24 | help: 25 | @echo "Please use \`make ' where is one of" 26 | @echo " html to make standalone HTML files" 27 | @echo " dirhtml to make HTML files named index.html in directories" 28 | @echo " singlehtml to make a single large HTML file" 29 | @echo " pickle to make pickle files" 30 | @echo " json to make JSON files" 31 | @echo " htmlhelp to make HTML files and a HTML help project" 32 | @echo " qthelp to make HTML files and a qthelp project" 33 | @echo " devhelp to make HTML files and a Devhelp project" 34 | @echo " epub to make an epub" 35 | @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" 36 | @echo " latexpdf to make LaTeX files and run them through pdflatex" 37 | @echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx" 38 | @echo " text to make text files" 39 | @echo " man to make manual pages" 40 | @echo " texinfo to make Texinfo files" 41 | @echo " info to make Texinfo files and run them through makeinfo" 42 | @echo " gettext to make PO message catalogs" 43 | @echo " changes to make an overview of all changed/added/deprecated items" 44 | @echo " xml to make Docutils-native XML files" 45 | @echo " pseudoxml to make pseudoxml-XML files for display purposes" 46 | @echo " linkcheck to check all external links for integrity" 47 | @echo " doctest to run all doctests embedded in the documentation (if enabled)" 48 | 49 | clean: 50 | rm -rf $(BUILDDIR)/* 51 | 52 | html: 53 | $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html 54 | @echo 55 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." 56 | 57 | dirhtml: 58 | $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml 59 | @echo 60 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." 61 | 62 | singlehtml: 63 | $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml 64 | @echo 65 | @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." 66 | 67 | pickle: 68 | $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle 69 | @echo 70 | @echo "Build finished; now you can process the pickle files." 71 | 72 | json: 73 | $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json 74 | @echo 75 | @echo "Build finished; now you can process the JSON files." 76 | 77 | htmlhelp: 78 | $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp 79 | @echo 80 | @echo "Build finished; now you can run HTML Help Workshop with the" \ 81 | ".hhp project file in $(BUILDDIR)/htmlhelp." 82 | 83 | qthelp: 84 | $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp 85 | @echo 86 | @echo "Build finished; now you can run "qcollectiongenerator" with the" \ 87 | ".qhcp project file in $(BUILDDIR)/qthelp, like this:" 88 | @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/complexity.qhcp" 89 | @echo "To view the help file:" 90 | @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/complexity.qhc" 91 | 92 | devhelp: 93 | $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp 94 | @echo 95 | @echo "Build finished." 96 | @echo "To view the help file:" 97 | @echo "# mkdir -p $$HOME/.local/share/devhelp/complexity" 98 | @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/complexity" 99 | @echo "# devhelp" 100 | 101 | epub: 102 | $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub 103 | @echo 104 | @echo "Build finished. The epub file is in $(BUILDDIR)/epub." 105 | 106 | latex: 107 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 108 | @echo 109 | @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." 110 | @echo "Run \`make' in that directory to run these through (pdf)latex" \ 111 | "(use \`make latexpdf' here to do that automatically)." 112 | 113 | latexpdf: 114 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 115 | @echo "Running LaTeX files through pdflatex..." 116 | $(MAKE) -C $(BUILDDIR)/latex all-pdf 117 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 118 | 119 | latexpdfja: 120 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 121 | @echo "Running LaTeX files through platex and dvipdfmx..." 122 | $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja 123 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 124 | 125 | text: 126 | $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text 127 | @echo 128 | @echo "Build finished. The text files are in $(BUILDDIR)/text." 129 | 130 | man: 131 | $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man 132 | @echo 133 | @echo "Build finished. The manual pages are in $(BUILDDIR)/man." 134 | 135 | texinfo: 136 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 137 | @echo 138 | @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." 139 | @echo "Run \`make' in that directory to run these through makeinfo" \ 140 | "(use \`make info' here to do that automatically)." 141 | 142 | info: 143 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 144 | @echo "Running Texinfo files through makeinfo..." 145 | make -C $(BUILDDIR)/texinfo info 146 | @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." 147 | 148 | gettext: 149 | $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale 150 | @echo 151 | @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." 152 | 153 | changes: 154 | $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes 155 | @echo 156 | @echo "The overview file is in $(BUILDDIR)/changes." 157 | 158 | linkcheck: 159 | $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck 160 | @echo 161 | @echo "Link check complete; look for any errors in the above output " \ 162 | "or in $(BUILDDIR)/linkcheck/output.txt." 163 | 164 | doctest: 165 | $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest 166 | @echo "Testing of doctests in the sources finished, look at the " \ 167 | "results in $(BUILDDIR)/doctest/output.txt." 168 | 169 | xml: 170 | $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml 171 | @echo 172 | @echo "Build finished. The XML files are in $(BUILDDIR)/xml." 173 | 174 | pseudoxml: 175 | $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml 176 | @echo 177 | @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml." -------------------------------------------------------------------------------- /docs/authors.rst: -------------------------------------------------------------------------------- 1 | .. include:: ../AUTHORS.rst -------------------------------------------------------------------------------- /docs/conf.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # 3 | # complexity documentation build configuration file, created by 4 | # sphinx-quickstart on Tue Jul 9 22:26:36 2013. 5 | # 6 | # This file is execfile()d with the current directory set to its containing dir. 7 | # 8 | # Note that not all possible configuration values are present in this 9 | # autogenerated file. 10 | # 11 | # All configuration values have a default; values that are commented out 12 | # serve to show the default. 13 | 14 | import sys, os 15 | 16 | # If extensions (or modules to document with autodoc) are in another directory, 17 | # add these directories to sys.path here. If the directory is relative to the 18 | # documentation root, use os.path.abspath to make it absolute, like shown here. 19 | #sys.path.insert(0, os.path.abspath('.')) 20 | 21 | cwd = os.getcwd() 22 | parent = os.path.dirname(cwd) 23 | sys.path.append(parent) 24 | 25 | import appengine_toolkit 26 | 27 | # -- General configuration ----------------------------------------------------- 28 | 29 | # If your documentation needs a minimal Sphinx version, state it here. 30 | #needs_sphinx = '1.0' 31 | 32 | # Add any Sphinx extension module names here, as strings. They can be extensions 33 | # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. 34 | extensions = ['sphinx.ext.autodoc', 'sphinx.ext.viewcode'] 35 | 36 | # Add any paths that contain templates here, relative to this directory. 37 | templates_path = ['_templates'] 38 | 39 | # The suffix of source filenames. 40 | source_suffix = '.rst' 41 | 42 | # The encoding of source files. 43 | #source_encoding = 'utf-8-sig' 44 | 45 | # The master toctree document. 46 | master_doc = 'index' 47 | 48 | # General information about the project. 49 | project = u'appengine-toolkit' 50 | copyright = u'2013, Massimiliano Pippi' 51 | 52 | # The version info for the project you're documenting, acts as replacement for 53 | # |version| and |release|, also used in various other places throughout the 54 | # built documents. 55 | # 56 | # The short X.Y version. 57 | version = appengine_toolkit.__version__ 58 | # The full version, including alpha/beta/rc tags. 59 | release = appengine_toolkit.__version__ 60 | 61 | # The language for content autogenerated by Sphinx. Refer to documentation 62 | # for a list of supported languages. 63 | #language = None 64 | 65 | # There are two options for replacing |today|: either, you set today to some 66 | # non-false value, then it is used: 67 | #today = '' 68 | # Else, today_fmt is used as the format for a strftime call. 69 | #today_fmt = '%B %d, %Y' 70 | 71 | # List of patterns, relative to source directory, that match files and 72 | # directories to ignore when looking for source files. 73 | exclude_patterns = ['_build'] 74 | 75 | # The reST default role (used for this markup: `text`) to use for all documents. 76 | #default_role = None 77 | 78 | # If true, '()' will be appended to :func: etc. cross-reference text. 79 | #add_function_parentheses = True 80 | 81 | # If true, the current module name will be prepended to all description 82 | # unit titles (such as .. function::). 83 | #add_module_names = True 84 | 85 | # If true, sectionauthor and moduleauthor directives will be shown in the 86 | # output. They are ignored by default. 87 | #show_authors = False 88 | 89 | # The name of the Pygments (syntax highlighting) style to use. 90 | pygments_style = 'sphinx' 91 | 92 | # A list of ignored prefixes for module index sorting. 93 | #modindex_common_prefix = [] 94 | 95 | # If true, keep warnings as "system message" paragraphs in the built documents. 96 | #keep_warnings = False 97 | 98 | 99 | # -- Options for HTML output --------------------------------------------------- 100 | 101 | # The theme to use for HTML and HTML Help pages. See the documentation for 102 | # a list of builtin themes. 103 | html_theme = 'default' 104 | 105 | # Theme options are theme-specific and customize the look and feel of a theme 106 | # further. For a list of options available for each theme, see the 107 | # documentation. 108 | #html_theme_options = {} 109 | 110 | # Add any paths that contain custom themes here, relative to this directory. 111 | #html_theme_path = [] 112 | 113 | # The name for this set of Sphinx documents. If None, it defaults to 114 | # " v documentation". 115 | #html_title = None 116 | 117 | # A shorter title for the navigation bar. Default is the same as html_title. 118 | #html_short_title = None 119 | 120 | # The name of an image file (relative to this directory) to place at the top 121 | # of the sidebar. 122 | #html_logo = None 123 | 124 | # The name of an image file (within the static path) to use as favicon of the 125 | # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 126 | # pixels large. 127 | #html_favicon = None 128 | 129 | # Add any paths that contain custom static files (such as style sheets) here, 130 | # relative to this directory. They are copied after the builtin static files, 131 | # so a file named "default.css" will overwrite the builtin "default.css". 132 | html_static_path = ['_static'] 133 | 134 | # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, 135 | # using the given strftime format. 136 | #html_last_updated_fmt = '%b %d, %Y' 137 | 138 | # If true, SmartyPants will be used to convert quotes and dashes to 139 | # typographically correct entities. 140 | #html_use_smartypants = True 141 | 142 | # Custom sidebar templates, maps document names to template names. 143 | #html_sidebars = {} 144 | 145 | # Additional templates that should be rendered to pages, maps page names to 146 | # template names. 147 | #html_additional_pages = {} 148 | 149 | # If false, no module index is generated. 150 | #html_domain_indices = True 151 | 152 | # If false, no index is generated. 153 | #html_use_index = True 154 | 155 | # If true, the index is split into individual pages for each letter. 156 | #html_split_index = False 157 | 158 | # If true, links to the reST sources are added to the pages. 159 | #html_show_sourcelink = True 160 | 161 | # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. 162 | #html_show_sphinx = True 163 | 164 | # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. 165 | #html_show_copyright = True 166 | 167 | # If true, an OpenSearch description file will be output, and all pages will 168 | # contain a tag referring to it. The value of this option must be the 169 | # base URL from which the finished HTML is served. 170 | #html_use_opensearch = '' 171 | 172 | # This is the file name suffix for HTML files (e.g. ".xhtml"). 173 | #html_file_suffix = None 174 | 175 | # Output file base name for HTML help builder. 176 | htmlhelp_basename = 'django-appengine-toolkitdoc' 177 | 178 | 179 | # -- Options for LaTeX output -------------------------------------------------- 180 | 181 | latex_elements = { 182 | # The paper size ('letterpaper' or 'a4paper'). 183 | #'papersize': 'letterpaper', 184 | 185 | # The font size ('10pt', '11pt' or '12pt'). 186 | #'pointsize': '10pt', 187 | 188 | # Additional stuff for the LaTeX preamble. 189 | #'preamble': '', 190 | } 191 | 192 | # Grouping the document tree into LaTeX files. List of tuples 193 | # (source start file, target name, title, author, documentclass [howto/manual]). 194 | latex_documents = [ 195 | ('index', 'django-appengine-toolkit.tex', u'appengine-toolkit Documentation', 196 | u'Massimiliano Pippi', 'manual'), 197 | ] 198 | 199 | # The name of an image file (relative to this directory) to place at the top of 200 | # the title page. 201 | #latex_logo = None 202 | 203 | # For "manual" documents, if this is true, then toplevel headings are parts, 204 | # not chapters. 205 | #latex_use_parts = False 206 | 207 | # If true, show page references after internal links. 208 | #latex_show_pagerefs = False 209 | 210 | # If true, show URL addresses after external links. 211 | #latex_show_urls = False 212 | 213 | # Documents to append as an appendix to all manuals. 214 | #latex_appendices = [] 215 | 216 | # If false, no module index is generated. 217 | #latex_domain_indices = True 218 | 219 | 220 | # -- Options for manual page output -------------------------------------------- 221 | 222 | # One entry per manual page. List of tuples 223 | # (source start file, name, description, authors, manual section). 224 | man_pages = [ 225 | ('index', 'django-appengine-toolkit', u'appengine-toolkit Documentation', 226 | [u'Massimiliano Pippi'], 1) 227 | ] 228 | 229 | # If true, show URL addresses after external links. 230 | #man_show_urls = False 231 | 232 | 233 | # -- Options for Texinfo output ------------------------------------------------ 234 | 235 | # Grouping the document tree into Texinfo files. List of tuples 236 | # (source start file, target name, title, author, 237 | # dir menu entry, description, category) 238 | texinfo_documents = [ 239 | ('index', 'django-appengine-toolkit', u'appengine-toolkit Documentation', 240 | u'Massimiliano Pippi', 'django-appengine-toolkit', 'One line description of project.', 241 | 'Miscellaneous'), 242 | ] 243 | 244 | # Documents to append as an appendix to all manuals. 245 | #texinfo_appendices = [] 246 | 247 | # If false, no module index is generated. 248 | #texinfo_domain_indices = True 249 | 250 | # How to display URL addresses: 'footnote', 'no', or 'inline'. 251 | #texinfo_show_urls = 'footnote' 252 | 253 | # If true, do not generate a @detailmenu in the "Top" node's menu. 254 | #texinfo_no_detailmenu = False -------------------------------------------------------------------------------- /docs/contributing.rst: -------------------------------------------------------------------------------- 1 | .. include:: ../CONTRIBUTING.rst -------------------------------------------------------------------------------- /docs/history.rst: -------------------------------------------------------------------------------- 1 | .. include:: ../HISTORY.rst -------------------------------------------------------------------------------- /docs/index.rst: -------------------------------------------------------------------------------- 1 | Welcome to appengine-toolkit's documentation! 2 | ================================================================= 3 | 4 | Appengine Toolkit pimps Django with some utilities which help deploying 5 | projects on Google App Engine with Google Cloud SQL as data backend. 6 | 7 | Main features: 8 | * collects project dependencies symlinking needed modules and packages and configuring App Engine environment 9 | * configures ``DATABASE`` setting parsing connection strings similar to those on Heroku 10 | 11 | Contents: 12 | 13 | .. toctree:: 14 | :maxdepth: 2 15 | 16 | installation 17 | usage 18 | 19 | Extras: 20 | 21 | .. toctree:: 22 | :maxdepth: 1 23 | 24 | contributing 25 | authors 26 | history -------------------------------------------------------------------------------- /docs/installation.rst: -------------------------------------------------------------------------------- 1 | ============ 2 | Installation 3 | ============ 4 | 5 | Install appengine-toolkit:: 6 | 7 | pip install django-appengine-toolkit 8 | 9 | Add it to the installed apps:: 10 | 11 | INSTALLED_APPS = ( 12 | # ... 13 | 'appengine_toolkit', 14 | ) 15 | -------------------------------------------------------------------------------- /docs/make.bat: -------------------------------------------------------------------------------- 1 | @ECHO OFF 2 | 3 | REM Command file for Sphinx documentation 4 | 5 | if "%SPHINXBUILD%" == "" ( 6 | set SPHINXBUILD=sphinx-build 7 | ) 8 | set BUILDDIR=_build 9 | set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% . 10 | set I18NSPHINXOPTS=%SPHINXOPTS% . 11 | if NOT "%PAPER%" == "" ( 12 | set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS% 13 | set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS% 14 | ) 15 | 16 | if "%1" == "" goto help 17 | 18 | if "%1" == "help" ( 19 | :help 20 | echo.Please use `make ^` where ^ is one of 21 | echo. html to make standalone HTML files 22 | echo. dirhtml to make HTML files named index.html in directories 23 | echo. singlehtml to make a single large HTML file 24 | echo. pickle to make pickle files 25 | echo. json to make JSON files 26 | echo. htmlhelp to make HTML files and a HTML help project 27 | echo. qthelp to make HTML files and a qthelp project 28 | echo. devhelp to make HTML files and a Devhelp project 29 | echo. epub to make an epub 30 | echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter 31 | echo. text to make text files 32 | echo. man to make manual pages 33 | echo. texinfo to make Texinfo files 34 | echo. gettext to make PO message catalogs 35 | echo. changes to make an overview over all changed/added/deprecated items 36 | echo. xml to make Docutils-native XML files 37 | echo. pseudoxml to make pseudoxml-XML files for display purposes 38 | echo. linkcheck to check all external links for integrity 39 | echo. doctest to run all doctests embedded in the documentation if enabled 40 | goto end 41 | ) 42 | 43 | if "%1" == "clean" ( 44 | for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i 45 | del /q /s %BUILDDIR%\* 46 | goto end 47 | ) 48 | 49 | 50 | %SPHINXBUILD% 2> nul 51 | if errorlevel 9009 ( 52 | echo. 53 | echo.The 'sphinx-build' command was not found. Make sure you have Sphinx 54 | echo.installed, then set the SPHINXBUILD environment variable to point 55 | echo.to the full path of the 'sphinx-build' executable. Alternatively you 56 | echo.may add the Sphinx directory to PATH. 57 | echo. 58 | echo.If you don't have Sphinx installed, grab it from 59 | echo.http://sphinx-doc.org/ 60 | exit /b 1 61 | ) 62 | 63 | if "%1" == "html" ( 64 | %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html 65 | if errorlevel 1 exit /b 1 66 | echo. 67 | echo.Build finished. The HTML pages are in %BUILDDIR%/html. 68 | goto end 69 | ) 70 | 71 | if "%1" == "dirhtml" ( 72 | %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml 73 | if errorlevel 1 exit /b 1 74 | echo. 75 | echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml. 76 | goto end 77 | ) 78 | 79 | if "%1" == "singlehtml" ( 80 | %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml 81 | if errorlevel 1 exit /b 1 82 | echo. 83 | echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml. 84 | goto end 85 | ) 86 | 87 | if "%1" == "pickle" ( 88 | %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle 89 | if errorlevel 1 exit /b 1 90 | echo. 91 | echo.Build finished; now you can process the pickle files. 92 | goto end 93 | ) 94 | 95 | if "%1" == "json" ( 96 | %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json 97 | if errorlevel 1 exit /b 1 98 | echo. 99 | echo.Build finished; now you can process the JSON files. 100 | goto end 101 | ) 102 | 103 | if "%1" == "htmlhelp" ( 104 | %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp 105 | if errorlevel 1 exit /b 1 106 | echo. 107 | echo.Build finished; now you can run HTML Help Workshop with the ^ 108 | .hhp project file in %BUILDDIR%/htmlhelp. 109 | goto end 110 | ) 111 | 112 | if "%1" == "qthelp" ( 113 | %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp 114 | if errorlevel 1 exit /b 1 115 | echo. 116 | echo.Build finished; now you can run "qcollectiongenerator" with the ^ 117 | .qhcp project file in %BUILDDIR%/qthelp, like this: 118 | echo.^> qcollectiongenerator %BUILDDIR%\qthelp\complexity.qhcp 119 | echo.To view the help file: 120 | echo.^> assistant -collectionFile %BUILDDIR%\qthelp\complexity.ghc 121 | goto end 122 | ) 123 | 124 | if "%1" == "devhelp" ( 125 | %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp 126 | if errorlevel 1 exit /b 1 127 | echo. 128 | echo.Build finished. 129 | goto end 130 | ) 131 | 132 | if "%1" == "epub" ( 133 | %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub 134 | if errorlevel 1 exit /b 1 135 | echo. 136 | echo.Build finished. The epub file is in %BUILDDIR%/epub. 137 | goto end 138 | ) 139 | 140 | if "%1" == "latex" ( 141 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex 142 | if errorlevel 1 exit /b 1 143 | echo. 144 | echo.Build finished; the LaTeX files are in %BUILDDIR%/latex. 145 | goto end 146 | ) 147 | 148 | if "%1" == "latexpdf" ( 149 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex 150 | cd %BUILDDIR%/latex 151 | make all-pdf 152 | cd %BUILDDIR%/.. 153 | echo. 154 | echo.Build finished; the PDF files are in %BUILDDIR%/latex. 155 | goto end 156 | ) 157 | 158 | if "%1" == "latexpdfja" ( 159 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex 160 | cd %BUILDDIR%/latex 161 | make all-pdf-ja 162 | cd %BUILDDIR%/.. 163 | echo. 164 | echo.Build finished; the PDF files are in %BUILDDIR%/latex. 165 | goto end 166 | ) 167 | 168 | if "%1" == "text" ( 169 | %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text 170 | if errorlevel 1 exit /b 1 171 | echo. 172 | echo.Build finished. The text files are in %BUILDDIR%/text. 173 | goto end 174 | ) 175 | 176 | if "%1" == "man" ( 177 | %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man 178 | if errorlevel 1 exit /b 1 179 | echo. 180 | echo.Build finished. The manual pages are in %BUILDDIR%/man. 181 | goto end 182 | ) 183 | 184 | if "%1" == "texinfo" ( 185 | %SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo 186 | if errorlevel 1 exit /b 1 187 | echo. 188 | echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo. 189 | goto end 190 | ) 191 | 192 | if "%1" == "gettext" ( 193 | %SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale 194 | if errorlevel 1 exit /b 1 195 | echo. 196 | echo.Build finished. The message catalogs are in %BUILDDIR%/locale. 197 | goto end 198 | ) 199 | 200 | if "%1" == "changes" ( 201 | %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes 202 | if errorlevel 1 exit /b 1 203 | echo. 204 | echo.The overview file is in %BUILDDIR%/changes. 205 | goto end 206 | ) 207 | 208 | if "%1" == "linkcheck" ( 209 | %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck 210 | if errorlevel 1 exit /b 1 211 | echo. 212 | echo.Link check complete; look for any errors in the above output ^ 213 | or in %BUILDDIR%/linkcheck/output.txt. 214 | goto end 215 | ) 216 | 217 | if "%1" == "doctest" ( 218 | %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest 219 | if errorlevel 1 exit /b 1 220 | echo. 221 | echo.Testing of doctests in the sources finished, look at the ^ 222 | results in %BUILDDIR%/doctest/output.txt. 223 | goto end 224 | ) 225 | 226 | if "%1" == "xml" ( 227 | %SPHINXBUILD% -b xml %ALLSPHINXOPTS% %BUILDDIR%/xml 228 | if errorlevel 1 exit /b 1 229 | echo. 230 | echo.Build finished. The XML files are in %BUILDDIR%/xml. 231 | goto end 232 | ) 233 | 234 | if "%1" == "pseudoxml" ( 235 | %SPHINXBUILD% -b pseudoxml %ALLSPHINXOPTS% %BUILDDIR%/pseudoxml 236 | if errorlevel 1 exit /b 1 237 | echo. 238 | echo.Build finished. The pseudo-XML files are in %BUILDDIR%/pseudoxml. 239 | goto end 240 | ) 241 | 242 | :end -------------------------------------------------------------------------------- /docs/readme.rst: -------------------------------------------------------------------------------- 1 | .. include:: ../README.rst -------------------------------------------------------------------------------- /docs/usage.rst: -------------------------------------------------------------------------------- 1 | Usage 2 | ===== 3 | 4 | Collect project dependencies 5 | ---------------------------- 6 | Google App Engine does not provide a virtual environment where installing dependencies at deploy time, like Heroku does. 7 | Dependencies must be present inside the application directory in the filesystem (i.e. where the ``.yaml`` file resides) 8 | at the moment users deploy the application (either with the Google App Engine Launcher or with ``appcfg.py`` script 9 | at the command line. Also, the path to the dependecies must be added to the ``sys.path`` so the Python runtime can 10 | import them. 11 | 12 | Both of those operations can be automated with App Engine Toolkit. 13 | 14 | collectdeps 15 | +++++++++++ 16 | ``python manage.py collectdeps`` 17 | 18 | Takes in input one or more package names (or a requirement file) and makes the symlink needed in the application directory 19 | beside writing the code needed to adjust the ``sys.path`` in the ``appengine_config.py`` module. If the 20 | ``appengine_config.py`` is already present, the command prompts users whether they want to overwrite the file or print 21 | needed python instructions in the terminal. 22 | 23 | ``--requirements requirements.txt`` 24 | 25 | Parse the list of dependencies from a requirement file 26 | 27 | ``--noinput`` 28 | 29 | Tells Django to NOT prompt the user for input of any kind. 30 | 31 | 32 | Setup database configuration settings 33 | ------------------------------------- 34 | At the moment, the only supported database backend for Django on App Engine is Google Cloud SQL, which 35 | is basically a MySQL instance. You may configure a MySQL backend adding something like this 36 | to your settings file:: 37 | 38 | # a typical configuration to access a local MySQL instance 39 | DATABASES = { 40 | 'default': { 41 | 'ENGINE': 'django.db.backends.mysql', 42 | 'HOST': 'localhost', 43 | 'NAME': 'django_test', 44 | 'USER': 'root', 45 | 'PASSWORD': 'secret', 46 | } 47 | } 48 | 49 | using Google Cloud SQL is not very different indeed, but you have to compose the ``HOST`` string 50 | carefully:: 51 | 52 | # configuration needed to access a Google Cloud SQL instance 53 | DATABASES = { 54 | 'default': { 55 | 'ENGINE': 'django.db.backends.mysql', 56 | 'HOST': '/cloudsql/your-project-id:your-instance-name', 57 | 'NAME': 'django_test', 58 | 'USER': 'root', 59 | } 60 | } 61 | 62 | Django App Engine Toolkit makes things a lot simpler, provided that you set an environment 63 | variable named ``DATABASE_URL`` following this schema:: 64 | 65 | [database type]://[username]:[password]@[host]:[port]/[database name] 66 | 67 | or, specifically for cloud SQL:: 68 | 69 | [database type]://[username]:[password]@[project_id]:[instance_name]/[database name] 70 | 71 | Once you defined such variable, just write this in your settings file:: 72 | 73 | import appengine_toolkit 74 | DATABASES = { 75 | 'default': appengine_toolkit.config(), 76 | } 77 | 78 | You can set the ``DATABASE_URL`` env var in your ``app.yaml`` like this:: 79 | 80 | env_variables: 81 | DATABASE_URL: 'mysql://root@my_project_id:my_instance_name/my_dbname' 82 | 83 | 84 | If you want to work with the local development server but still accessing the remote Cloud SQL 85 | instance, you can use the following ``DATABASE_URL`` string:: 86 | 87 | 'rdbms://root@my_project_id:my_instance_name/my_dbname' 88 | 89 | To work with the local development server and a local MySQL instance, ``DATABASE_URL`` will look like:: 90 | 91 | 'mysql://root:password@localhost/my_dbname' 92 | -------------------------------------------------------------------------------- /requirements-test.txt: -------------------------------------------------------------------------------- 1 | -r requirements.txt 2 | coverage 3 | mock>=1.0.1 4 | nose>=1.3.0 5 | django-nose>=1.2 6 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | django<1.6 # this is due to AppEngine 2 | -e svn+http://appengine-gcs-client.googlecode.com/svn/trunk/python/src#egg=GoogleAppEngineCloudStorageClient -------------------------------------------------------------------------------- /runtests.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import os 3 | from optparse import OptionParser 4 | 5 | import google 6 | 7 | here = os.path.dirname(os.path.abspath(__file__)) 8 | gae_path = os.path.dirname(os.path.abspath(google.__file__)) 9 | dir_path = os.path.join(gae_path, '..') 10 | 11 | GAE_LIBRARY_PATHS = [ 12 | dir_path, 13 | os.path.join(dir_path, 'lib', 'cherrypy'), 14 | os.path.join(dir_path, 'lib', 'fancy_urllib'), 15 | os.path.join(dir_path, 'lib', 'yaml-3.10'), 16 | os.path.join(dir_path, 'lib', 'antlr3'), 17 | os.path.join(dir_path, 'lib', 'concurrent'), 18 | os.path.join(dir_path, 'lib', 'ipaddr'), 19 | os.path.join(dir_path, 'lib', 'jinja2-2.6'), 20 | os.path.join(dir_path, 'lib', 'webob-1.2.3'), 21 | os.path.join(dir_path, 'lib', 'webapp2-2.5.1'), 22 | os.path.join(dir_path, 'lib', 'mox'), 23 | os.path.join(dir_path, 'lib', 'protorpc-1.0'), 24 | os.path.join(dir_path, 'lib', 'simplejson'), 25 | ] 26 | 27 | try: 28 | from django.conf import settings 29 | 30 | settings.configure( 31 | DEBUG=True, 32 | USE_TZ=True, 33 | DATABASES={ 34 | "default": { 35 | "ENGINE": "django.db.backends.sqlite3", 36 | } 37 | }, 38 | ROOT_URLCONF="appengine_toolkit.urls", 39 | INSTALLED_APPS=[ 40 | "django.contrib.auth", 41 | "django.contrib.contenttypes", 42 | "django.contrib.sites", 43 | "appengine_toolkit", 44 | ], 45 | SITE_ID=1, 46 | NOSE_ARGS=['-s'], 47 | APPENGINE_TOOLKIT={ 48 | 'APP_YAML': os.path.join(here, 'tests', 'foo.yaml'), 49 | 'BUCKET_NAME': 'test_bucket', 50 | }, 51 | DEFAULT_FILE_STORAGE='appengine_toolkit.storage.GoogleCloudStorage', 52 | ) 53 | 54 | from django_nose import NoseTestSuiteRunner 55 | except ImportError: 56 | raise ImportError("To fix this error, run: pip install -r requirements-test.txt") 57 | 58 | 59 | def run_tests(*test_args): 60 | if not test_args: 61 | test_args = ['tests'] 62 | 63 | # Run tests 64 | test_runner = NoseTestSuiteRunner(verbosity=1) 65 | 66 | failures = test_runner.run_tests(test_args) 67 | 68 | if failures: 69 | sys.exit(failures) 70 | 71 | 72 | if __name__ == '__main__': 73 | sys.path.extend(GAE_LIBRARY_PATHS) 74 | 75 | from google.appengine.tools import old_dev_appserver 76 | from google.appengine.tools.dev_appserver_main import ParseArguments 77 | 78 | option_dict = ParseArguments(sys.argv)[1] 79 | old_dev_appserver.SetupStubs('local', **option_dict) 80 | 81 | parser = OptionParser() 82 | (options, args) = parser.parse_args() 83 | run_tests(*args) -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | #!/usr/bin/env python 3 | 4 | import os 5 | import sys 6 | 7 | import appengine_toolkit 8 | 9 | try: 10 | from setuptools import setup 11 | except ImportError: 12 | from distutils.core import setup 13 | 14 | version = appengine_toolkit.__version__ 15 | 16 | if sys.argv[-1] == 'publish': 17 | os.system('python setup.py sdist upload') 18 | print("You probably want to also tag the version now:") 19 | print(" git tag -a %s -m 'version %s'" % (version, version)) 20 | print(" git push --tags") 21 | sys.exit() 22 | 23 | readme = open('README.rst').read() 24 | history = open('HISTORY.rst').read().replace('.. :changelog:', '') 25 | 26 | setup( 27 | name='django-appengine-toolkit', 28 | version=version, 29 | description='Deploy Django projects on Google App Engine with ease', 30 | long_description=readme + '\n\n' + history, 31 | author='Massimiliano Pippi', 32 | author_email='mpippi@gmail.com', 33 | url='https://github.com/masci/django-appengine-toolkit', 34 | packages=[ 35 | 'appengine_toolkit', 36 | ], 37 | include_package_data=True, 38 | install_requires=[ 39 | 'django<1.6', 40 | 'GoogleAppEngineCloudStorageClient', 41 | ], 42 | license="BSD", 43 | zip_safe=False, 44 | keywords='django-appengine-toolkit', 45 | classifiers=[ 46 | 'Development Status :: 2 - Pre-Alpha', 47 | 'Framework :: Django', 48 | 'Intended Audience :: Developers', 49 | 'License :: OSI Approved :: BSD License', 50 | 'Natural Language :: English', 51 | "Programming Language :: Python :: 2", 52 | 'Programming Language :: Python :: 2.7', 53 | ], 54 | ) -------------------------------------------------------------------------------- /tests/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/masci/django-appengine-toolkit/9ffe8b05a263889787fb34a3e28ebc66b1f0a1d2/tests/__init__.py -------------------------------------------------------------------------------- /tests/test_commands.py: -------------------------------------------------------------------------------- 1 | from django.test import TestCase 2 | from django.core.management import call_command, CommandError 3 | 4 | import os 5 | 6 | import mock 7 | 8 | from appengine_toolkit.settings import appengine_toolkit_settings 9 | 10 | 11 | class TestCommands(TestCase): 12 | def tearDown(self): 13 | appengine_config = os.path.join(os.path.dirname(appengine_toolkit_settings.APP_YAML), 'appengine_config.py') 14 | if os.path.exists(appengine_config): 15 | os.remove(appengine_config) 16 | 17 | 18 | class TestCollectDeps(TestCommands): 19 | def test_call_wrong(self): 20 | self.assertRaises(CommandError, call_command, 'collectdeps', interactive=False) 21 | 22 | def test_call_package(self): 23 | with mock.patch('appengine_toolkit.management.commands.collectdeps.collect_dependency_paths') as mock_collect: 24 | mock_collect.return_value = [] 25 | call_command('collectdeps', 'foo', interactive=False) 26 | self.assertEqual(mock_collect.call_args[0], ('foo',)) 27 | 28 | def test_call_req_file(self): 29 | with mock.patch('__builtin__.open'), \ 30 | mock.patch('appengine_toolkit.management.commands.collectdeps.parse_requirements_file') as mock_parse, \ 31 | mock.patch('appengine_toolkit.management.commands.collectdeps.collect_dependency_paths') as mock_collect: 32 | mock_parse.return_value = ['foo'] 33 | mock_collect.return_value = [] 34 | call_command('collectdeps', requirements_file='foofile', interactive=False) 35 | 36 | def test_call_req_file_fail(self): 37 | with mock.patch('__builtin__.open'), \ 38 | mock.patch('appengine_toolkit.management.commands.collectdeps.parse_requirements_file') as mock_parse:#, \ 39 | mock_parse.return_value = ['foo'] 40 | self.assertRaises(CommandError, call_command, 'collectdeps', requirements_file='foofile', interactive=False) 41 | 42 | def test_call_create_deps_dir(self): 43 | with mock.patch('appengine_toolkit.management.commands.collectdeps.os.path.exists') as mock_exists,\ 44 | mock.patch('appengine_toolkit.management.commands.collectdeps.os.mkdir') as mock_mkdir,\ 45 | mock.patch('appengine_toolkit.management.commands.collectdeps.collect_dependency_paths'): 46 | mock_exists.return_value = False 47 | call_command('collectdeps', 'foo', interactive=False) 48 | self.assertTrue('/libs' in mock_mkdir.call_args[0][0]) -------------------------------------------------------------------------------- /tests/test_storage.py: -------------------------------------------------------------------------------- 1 | from django.test import TestCase 2 | from django.core.exceptions import ImproperlyConfigured, SuspiciousOperation 3 | from django.core.files.base import ContentFile 4 | from django.core.files.storage import default_storage 5 | from django.utils import timezone 6 | 7 | from appengine_toolkit.storage import GoogleCloudStorage 8 | 9 | from google.appengine.ext import testbed 10 | import cloudstorage 11 | import mock 12 | 13 | import urlparse 14 | import os 15 | 16 | 17 | class TestStorage(TestCase): 18 | def setUp(self): 19 | self.storage = default_storage 20 | self.testbed = testbed.Testbed() 21 | self.testbed.activate() 22 | self.testbed.init_urlfetch_stub() 23 | self.testbed.init_app_identity_stub() 24 | self.testbed.init_files_stub() 25 | self.testbed.init_blobstore_stub() 26 | cloudstorage.set_default_retry_params(None) 27 | # cleanup storage stub 28 | for elem in cloudstorage.listbucket('/test_bucket/'): 29 | cloudstorage.delete(elem.filename) 30 | 31 | def tearDown(self): 32 | self.testbed.deactivate() 33 | 34 | def test_bucket_name(self): 35 | with mock.patch('appengine_toolkit.storage.appengine_toolkit_settings') as test_settings: 36 | test_settings.BUCKET_NAME = None 37 | self.assertRaises(ImproperlyConfigured, GoogleCloudStorage) 38 | test_settings.BUCKET_NAME = 'suitable' 39 | s = GoogleCloudStorage() 40 | self.assertIsInstance(s, GoogleCloudStorage) 41 | 42 | def test_exists(self): 43 | self.assertFalse(self.storage.exists('test.txt')) 44 | path = self.storage.save('test.txt', ContentFile('new content')) 45 | self.assertTrue(self.storage.exists(path)) 46 | # empty names are not allowed 47 | self.assertRaises(SuspiciousOperation, self.storage.exists, '') 48 | 49 | def test_file_created_time(self): 50 | cf = ContentFile('some contents') 51 | filename = self.storage.save('test.file', cf) 52 | now = timezone.now() 53 | ctime = self.storage.created_time(filename) 54 | self.assertTrue((now-ctime).seconds < 1) 55 | # empty names are not allowed 56 | self.assertRaises(SuspiciousOperation, self.storage.created_time, '') 57 | 58 | def test_delete(self): 59 | path = self.storage.save('test.txt', ContentFile('new content')) 60 | self.storage.delete(path) 61 | self.assertFalse(self.storage.exists('test.txt')) 62 | # empty names are not allowed 63 | self.assertRaises(SuspiciousOperation, self.storage.delete, '') 64 | 65 | def test_delete_nonexistent(self): 66 | self.storage.delete('fake.txt') 67 | 68 | def test_size(self): 69 | path = self.storage.save('test.txt', ContentFile('new content')) 70 | self.assertEqual(self.storage.size('test.txt'), 11) 71 | 72 | def test_listdir(self): 73 | self.storage.save('test.txt', ContentFile('a content')) 74 | self.storage.save('test.txt', ContentFile('another content')) 75 | files = self.storage.listdir(self.storage._bucket)[1] 76 | self.assertEqual(len(files), 2) 77 | 78 | def test_url(self): 79 | path = self.storage.save('test.txt', ContentFile('new content')) 80 | url = urlparse.urlparse(self.storage.url(path)) 81 | self.assertTrue('_ah/img/' in url.path) 82 | 83 | def test_save(self): 84 | f = ContentFile('moar contents') 85 | path = self.storage.save('test.txt', f) 86 | with self.storage.open(path, 'r') as f: 87 | self.assertEqual(f.read(), 'moar contents') 88 | 89 | def test_file_save_without_name(self): 90 | """ 91 | File storage extracts the filename from the content object if no 92 | name is given explicitly. 93 | """ 94 | cf = ContentFile('contents') 95 | cf.name = 'foo_name.txt' 96 | path = self.storage.save(None, cf) 97 | self.assertEqual(path, os.path.join('/', self.storage._bucket, cf.name)) -------------------------------------------------------------------------------- /tests/test_toolkit.py: -------------------------------------------------------------------------------- 1 | from django.test import TestCase 2 | 3 | import os 4 | import mock 5 | 6 | from appengine_toolkit import on_appengine, config, parse 7 | 8 | 9 | class TestToolkit(TestCase): 10 | def test_on_appengine(self): 11 | self.assertFalse(on_appengine()) 12 | os.environ['SERVER_SOFTWARE'] = 'Google App Engine Fake' 13 | self.assertTrue(on_appengine()) 14 | del os.environ['SERVER_SOFTWARE'] 15 | 16 | def test_config(self): 17 | with mock.patch('appengine_toolkit.parse') as mock_parse: 18 | env_var = 'FOO_ENVVAR' 19 | os.environ[env_var] = 'Foo' 20 | config(env_var) 21 | self.assertEqual(mock_parse.call_args[0], ('Foo',)) 22 | del os.environ[env_var] 23 | 24 | def test_parse_wrong_string(self): 25 | dbconf = parse("foo://bar:baz@foo:8080/url") 26 | self.assertFalse('ENGINE' in dbconf) 27 | 28 | def test_parse_local_db_string(self): 29 | dbconf = parse("mysql://root:pass@localhost:3306/dbname") 30 | expected = { 31 | 'NAME': 'dbname', 32 | 'USER': 'root', 33 | 'PASSWORD': 'pass', 34 | 'HOST': 'localhost', 35 | 'PORT': 3306, 36 | 'ENGINE': 'django.db.backends.mysql', 37 | } 38 | self.assertEqual(dbconf, expected) 39 | 40 | def test_parse_cloudsql_string(self): 41 | dbconf = parse("mysql://root:pass@project:instance/dbname") 42 | expected = { 43 | 'NAME': 'dbname', 44 | 'USER': 'root', 45 | 'PASSWORD': 'pass', 46 | 'HOST': '/cloudsql/project:instance', 47 | 'PORT': None, 48 | 'ENGINE': 'django.db.backends.mysql', 49 | } 50 | self.assertEqual(dbconf, expected) 51 | 52 | def test_parse_cloudsql_local(self): 53 | dbconf = parse("rdbms://root:pass@project:instance/dbname") 54 | expected = { 55 | 'NAME': 'dbname', 56 | 'USER': 'root', 57 | 'PASSWORD': 'pass', 58 | 'HOST': None, 59 | 'INSTANCE': 'project:instance', 60 | 'PORT': None, 61 | 'ENGINE': 'google.appengine.ext.django.backends.rdbms', 62 | } 63 | self.assertEqual(dbconf, expected) 64 | -------------------------------------------------------------------------------- /tests/test_utils.py: -------------------------------------------------------------------------------- 1 | from django.test import TestCase 2 | 3 | import StringIO 4 | import os 5 | 6 | import mock 7 | 8 | from appengine_toolkit.management.commands._utils import collect_dependency_paths 9 | from appengine_toolkit.management.commands._utils import parse_requirements_file 10 | from appengine_toolkit.management.commands._utils import RequirementNotFoundError 11 | from appengine_toolkit.management.commands._utils import make_simlinks 12 | 13 | 14 | class TestUtils(TestCase): 15 | def test_collect_dependency_paths(self): 16 | with mock.patch('pkg_resources.get_distribution') as mock_get_d, \ 17 | mock.patch('os.path.isdir') as mock_isdir, mock.patch('os.path.exists'): 18 | dist = mock_get_d.return_value 19 | dist.has_metadata.return_value = True 20 | dist.get_metadata.return_value = 'foo\nfoo/bar\n' 21 | dist.location = '' 22 | req = mock.MagicMock() 23 | req.project_name = 'baz' 24 | dist.requires.side_effect = [[req], []] 25 | mock_isdir.return_value = False 26 | deps = collect_dependency_paths('foo') 27 | self.assertEqual(2, len(deps)) 28 | self.assertTrue('foo.py' in deps) 29 | 30 | def test_collect_dependency_paths_fail(self): 31 | self.assertRaises(RequirementNotFoundError, collect_dependency_paths, 'foo') 32 | self.assertRaises(RequirementNotFoundError, collect_dependency_paths, 'wrong/foo') 33 | 34 | def test_parse_requirements_file(self): 35 | input = """ 36 | django<1.6 37 | 38 | # comment 39 | # another comment 40 | """ 41 | infile = StringIO.StringIO() 42 | infile.write(input) 43 | infile.seek(0) 44 | lines = parse_requirements_file(infile) 45 | self.assertEqual(1, len(lines)) 46 | self.assertTrue('django' in lines[0]) 47 | 48 | def test_make_symlinks(self): 49 | with mock.patch('os.symlink') as mock_symlink: 50 | make_simlinks('/my/dest', ['/from/source_1', '/from/source_2']) 51 | calls = mock_symlink.call_args_list 52 | self.assertEqual(len(calls), 2) 53 | self.assertEqual(calls[0][0][1], '/my/dest/source_1') 54 | self.assertEqual(calls[1][0][1], '/my/dest/source_2') 55 | 56 | def test_make_symlinks_link_exists(self): 57 | with mock.patch('os.symlink'), mock.patch('os.path.islink'), \ 58 | mock.patch('os.remove') as mock_remove: 59 | this = os.path.abspath(__file__) 60 | make_simlinks(os.path.dirname(this), [this]) 61 | arg = mock_remove.call_args[0][0] 62 | self.assertEqual(arg, this) 63 | 64 | def test_make_symlink_path_exists(self): 65 | with mock.patch('os.symlink') as mock_symlink: 66 | this = os.path.abspath(__file__) 67 | make_simlinks(os.path.dirname(this), [this]) 68 | self.assertEqual(0, mock_symlink.call_count) -------------------------------------------------------------------------------- /tox.ini: -------------------------------------------------------------------------------- 1 | [tox] 2 | envlist = py26, py27, py33 3 | 4 | [testenv] 5 | setenv = 6 | PYTHONPATH = {toxinidir}:{toxinidir}/appengine_toolkit 7 | commands = python runtests.py 8 | deps = 9 | -r{toxinidir}/requirements-test.txt --------------------------------------------------------------------------------